diff options
Diffstat (limited to 'catalog-be/src/test/java/org/openecomp/sdc/be/components')
118 files changed, 14681 insertions, 6763 deletions
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java index 87dfbc45de..06c22bca69 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,56 +20,53 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import java.util.EnumMap; -import java.util.UUID; - import org.junit.Before; import org.junit.Test; -import org.mockito.InjectMocks; +import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.AuditingDao; -import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import junit.framework.Assert; +import java.util.EnumMap; +import java.util.UUID; -public class AuditingManagerTest extends BaseConfDependentTest{ +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; - @InjectMocks - private AuditingManager auditingManager = Mockito.spy(AuditingManager.class); - public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class); +@RunWith(MockitoJUnitRunner.class) +public class AuditingManagerTest extends BeConfDependentTest { - public AuditingManagerTest() { - } + private AuditingManager auditingManager; + @Mock + private AuditingDao auditingDao; - @SuppressWarnings("unchecked") - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); + @Before + public void setup() { + auditingManager = new AuditingManager(auditingDao, null); + when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); - } + } - @Test - public void testNormalizeEmptyStringValuesAndUuid() { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); + @Test + public void testNormalizeEmptyStringValuesAndUuid() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); - String randomUUID = UUID.randomUUID().toString(); - ThreadLocalsHolder.setUuid(randomUUID); + String randomUUID = UUID.randomUUID().toString(); + ThreadLocalsHolder.setUuid(randomUUID); - auditingManager.auditEvent(auditingFields); - // Checking normalization - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC), Constants.EMPTY_STRING); - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT), Constants.EMPTY_STRING); - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID), randomUUID); - } + auditingManager.auditEvent(auditingFields); + // Checking normalization + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)).isEqualTo(randomUUID); + } } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java new file mode 100644 index 0000000000..bbd827eb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java @@ -0,0 +1,355 @@ +package org.openecomp.sdc.be.components; + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +public class BaseServiceBusinessLogicTest { + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + ForwardingPathOperation forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = null; + + protected static final String CERTIFIED_VERSION = "1.0"; + protected static final String UNCERTIFIED_VERSION = "0.2"; + protected static final String COMPONNET_ID = "myUniqueId"; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<>(); + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<>(); + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<>(); + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + //forwardingPath + when(forwardingPathOperation.addForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.updateForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.deleteForwardingPath(any(),any())).thenReturn(Either.left(Sets.newHashSet("Wow-It-Works"))); + when(toscaOperationFacade.getToscaElement("delete_forward_test")).thenReturn(Either.left(createServiceObject(true))); + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setForwardingPathOperation(forwardingPathOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + protected Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i<listSize; ++i){ + ci = new ComponentInstance(); + ci.setName("ciName" + i); + ci.setUniqueId("ciId" + i); + List<GroupInstance> groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j<listSize; ++j){ + gi = new GroupInstance(); + gi.setName(ci.getName( )+ "giName" + j); + gi.setUniqueId(ci.getName() + "giId" + j); + groupInstances.add(gi); + } + ci.setGroupInstances(groupInstances); + componentInstances.add(ci); + } + service.setComponentInstances(componentInstances); + return service; + } + + private void mockAuditingDaoLogic() { + FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); + + final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); + createResourceAudit.setModifier("Carlos Santana(cs0008)"); + createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + createResourceAudit.setCurrVersion("0.1"); + createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); + createResourceAudit.setDesc("OK"); + createResourceAudit.setResourceType("Resource"); + createResourceAudit.setStatus("201"); + createResourceAudit.setPrevVersion(""); + createResourceAudit.setAction("Create"); + // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + // createResourceAudit.setFields(fields); + + final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); + checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); + checkInResourceAudit.setCurrVersion("0.1"); + checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); + checkInResourceAudit.setDesc("OK"); + checkInResourceAudit.setComment("Stam"); + checkInResourceAudit.setResourceType("Resource"); + checkInResourceAudit.setStatus("200"); + checkInResourceAudit.setPrevVersion("0.1"); + checkInResourceAudit.setAction("Checkin"); + // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); + checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); + checkInResourceAudit.setResourceName("MyTestResource"); + + final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); + checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + checkOutResourceAudit.setCurrVersion("0.2"); + checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); + checkOutResourceAudit.setDesc("OK"); + checkOutResourceAudit.setComment(""); + checkOutResourceAudit.setResourceType("Resource"); + checkOutResourceAudit.setStatus("200"); + checkOutResourceAudit.setPrevVersion("0.1"); + checkOutResourceAudit.setAction("Checkout"); + // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + // checkOutResourceAudit.setFields(fields); + + // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>, + // ActionStatus> >() { + // public Either<List<ESTimeBasedEvent>, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either<List<ESTimeBasedEvent>, ActionStatus> either; + // final List<ESTimeBasedEvent> list; + // Object[] args = invocation.getArguments(); + // Map<AuditingFieldsKeysEnum, Object> filterMap = + // (Map<AuditingFieldsKeysEnum, Object>) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList<ESTimeBasedEvent>(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>(); + Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() { + { + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + protected Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List<String> tgs = new ArrayList<String>(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + return service; + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected static ForwardingPathDataDefinition forwardingPathDataDefinition; + + protected static ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null){ + return forwardingPathDataDefinition ; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol("http"); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode","toNode", "333","444","2222","5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode","toNode2", "4444","44444","4","44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java index ad5471e852..01d003f2a4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java @@ -20,29 +20,15 @@ package org.openecomp.sdc.be.components; -import java.io.File; - import org.junit.BeforeClass; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; - -public class BaseConfDependentTest { - protected static ConfigurationManager configurationManager; - - @BeforeClass - public static void setupBeforeClass() { - - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - configurationManager = new ConfigurationManager(configurationSource); +import org.openecomp.sdc.common.test.BaseConfDependent; - configurationManager.getConfiguration().setTitanInMemoryGraph(true); +public class BeConfDependentTest extends BaseConfDependent { + @BeforeClass + public static void setupBeforeClass() { + componentName = "catalog-be"; + confPath = "src/test/resources/config"; + setUp(); + } - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java index 7774b7f412..d7bfdcd1a4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,80 +42,85 @@ import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ComponentBusinessLogicTest { - private static final User USER = new User(); - private static final String ARTIFACT_LABEL = "toscaArtifact1"; - private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; - - @InjectMocks - private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - return null; - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return null; - } - - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - @Override - public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) { - return null; - } - }; - - @Mock - private ArtifactsBusinessLogic artifactsBusinessLogic; - - @BeforeClass - public static void setUp() throws Exception { - new DummyConfigurationManager(); - } - - @SuppressWarnings("unchecked") - @Test - public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { - Resource resource = new ResourceBuilder().setUniqueId("uid") - .setComponentType(ComponentTypeEnum.RESOURCE) - .setSystemName("myResource") - .build(); - Map<String, Object> artifactsFromConfig = new HashMap<>(); - artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); - artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); - when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); - testInstance.setToscaArtifactsPlaceHolders(resource, USER); - - Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts(); - assertThat(toscaArtifacts).hasSize(2); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); - assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); - ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); - assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); - } - - private Map<String, Object> buildArtifactMap(String artifactName) { - Map<String, Object> artifact = new HashMap<>(); - artifact.put("artifactName", artifactName); - return artifact; - } - - private ArtifactDefinition buildArtifactDef(String artifactLabel) { - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - artifactDefinition.setArtifactLabel(artifactLabel); - return artifactDefinition; - } + private static final User USER = new User(); + private static final String ARTIFACT_LABEL = "toscaArtifact1"; + private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; + + @InjectMocks + private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + return null; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return null; + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + @Override + public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) { + return null; + } + }; + + @Mock + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @BeforeClass + public static void setUp() throws Exception { + new DummyConfigurationManager(); + } + + @SuppressWarnings("unchecked") + @Test + public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { + Resource resource = new ResourceBuilder().setUniqueId("uid") + .setComponentType(ComponentTypeEnum.RESOURCE) + .setSystemName("myResource") + .build(); + Map<String, Object> artifactsFromConfig = new HashMap<>(); + artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); + artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); + testInstance.setToscaArtifactsPlaceHolders(resource, USER); + + Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts(); + assertThat(toscaArtifacts).hasSize(2); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); + assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); + ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); + assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); + } + + private Map<String, Object> buildArtifactMap(String artifactName) { + Map<String, Object> artifact = new HashMap<>(); + artifact.put("artifactName", artifactName); + return artifact; + } + + private ArtifactDefinition buildArtifactDef(String artifactLabel) { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactLabel(artifactLabel); + return artifactDefinition; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java index 9bf7f16a50..c114f340b8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java @@ -20,10 +20,6 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,206 +42,193 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import javax.servlet.ServletContext; + +import static org.mockito.Mockito.when; /** * tests GroupBusinessLogic class * @author ns019t * */ public class GroupBusinessLogicTest { - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); - ComponentsUtils componentsUtils = new ComponentsUtils(); - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - final ServletContext servletContext = Mockito.mock(ServletContext.class); - private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); - private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); - private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); - private static User user = Mockito.mock(User.class); - private static String componentId = "vfUniqueId-xxxx"; - private static String groupUniqueId = "groupUniqueId-xxxx"; - @InjectMocks - static GroupBusinessLogic bl = new GroupBusinessLogic(); - - - @Before - public void setupBeforeMethod() { - MockitoAnnotations.initMocks(this); - ExternalConfiguration.setAppName("catalog-be"); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - } - @BeforeClass - public static void setupBeforeClass() { - when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); -// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); - } - - public enum ResponseEnum{ - INVALID_MIN_MAX("SVC4654"), - INVALID_INITIAL_COUNT("SVC4655"); - - String messageId; - - private ResponseEnum(String messageId){ - this.messageId = messageId; - } - public String getMessageId() { - return messageId; - } - - } - /** - * tests the ValidateMinMaxAndInitialCountPropertyValues() method - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testValidateMinMaxAndInitialCountPropertyValues(){ - -// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class; -// String methodName = "validateMinMaxAndInitialCountPropertyValues"; -// Either<Boolean, ResponseFormat> validationRes; -// -// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); -// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); -// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); -// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); -// -// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); -// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); -// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); -// -// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); -// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); -// -// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); -// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); -// -// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); -// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); -// -// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); -// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); -// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); -// -// -// Class[] argClasses = {Map.class, Map.class}; -// try { -// Method method = targetClass.getDeclaredMethod(methodName, argClasses); -// method.setAccessible(true); -// -// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// -// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// } -// catch (Exception e) { -// e.printStackTrace(); -// } - } + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + ComponentsUtils componentsUtils; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); + private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); + private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); + private static User user = Mockito.mock(User.class); + private static String componentId = "vfUniqueId-xxxx"; + private static String groupUniqueId = "groupUniqueId-xxxx"; + @InjectMocks + static GroupBusinessLogic bl = new GroupBusinessLogic(); + + + @Before + public void setupBeforeMethod() { + MockitoAnnotations.initMocks(this); + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + + bl.setComponentsUtils(componentsUtils); + } + @BeforeClass + public static void setupBeforeClass() { + when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); +// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); + } + + /** + * tests the ValidateMinMaxAndInitialCountPropertyValues() method + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void testValidateMinMaxAndInitialCountPropertyValues(){ + +// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class; +// String methodName = "validateMinMaxAndInitialCountPropertyValues"; +// Either<Boolean, ResponseFormat> validationRes; +// +// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); +// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); +// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); +// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); +// +// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); +// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); +// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); +// +// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); +// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); +// +// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); +// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); +// +// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); +// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); +// +// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); +// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); +// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); +// +// +// Class[] argClasses = {Map.class, Map.class}; +// try { +// Method method = targetClass.getDeclaredMethod(methodName, argClasses); +// method.setAccessible(true); +// +// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// +// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// } +// catch (Exception e) { +// e.printStackTrace(); +// } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java index 2a34baeb0f..04c2100ed8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java @@ -20,66 +20,66 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - import org.junit.Test; -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HealthCheckBusinessLogicTest { - HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); - - @Test - public void checkStausUpdated() { + HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); + + @Test + public void checkStausUpdated() { - boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); - assertFalse("check false", statusChanged); + boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); + assertFalse("check false", statusChanged); - List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>(); - List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>(); + List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>(); + List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>(); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); - HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); + HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); - /* - * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); - */ + /* + * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); + */ - checkInfosLeft.add(checkInfoTitanUp); + checkInfosLeft.add(checkInfoTitanUp); - checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - checkInfosRight.remove(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.remove(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanDown); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.add(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.remove(checkInfoTitanDown); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.remove(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + checkInfosRight.add(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); - assertTrue("check true", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); + assertTrue("check true", statusChanged); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java new file mode 100644 index 0000000000..f9412c1643 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java @@ -0,0 +1,143 @@ +package org.openecomp.sdc.be.components; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datamodel.ServiceRelations; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class PathTest extends BaseServiceBusinessLogicTest { + public static final String fromNode = "fromNode"; + + @Override + protected Service createServiceObject(boolean afterCreate) { + Service service = super.createServiceObject(afterCreate); + ArrayList<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + String toNode = "toNode"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode, "1", toNode, "2", "capability", "3", "requirement", "4")); + String fromNode1 = "fromNode1"; + String toNode1 = "toNode1"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode1, "11", toNode1, "21", "capability1", "31", "requirement1", "41")); + service.setComponentInstances(new java.util.ArrayList<>()); + service.getComponentInstances().add(getComponentInstance(fromNode, "fromNode")); + service.getComponentInstances().add(getComponentInstance(fromNode1, "fromNode1")); + service.getComponentInstances().add(getComponentInstance(toNode, toNode)); + service.getComponentInstances().add(getComponentInstance(toNode1, toNode1)); + + service.setComponentInstancesRelations(resourceInstancesRelations); + return service; + } + + private ComponentInstance getComponentInstance(String uniquId, String normalizedName) { + ComponentInstance ci = new ComponentInstance(); + ci.setUniqueId(uniquId); + ci.setNormalizedName(normalizedName); + ci.setName(normalizedName); + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + ci.setCapabilities(capabilities); + return ci; + } + + private static int i = 0; + + private CapabilityDefinition getCapabilityDefinition(ComponentInstance ci) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setUniqueId(UUID.randomUUID().toString()); + capabilityDefinition.setName("My name " + i++); + capabilityDefinition.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + capabilityDefinition.setOwnerId(ci.getUniqueId()); + return capabilityDefinition; + } + + + protected RequirementCapabilityRelDef createRequirementCapabilityRelDef(String fromNode, String fromNodeId, String toNode, String toNodeId, String capability, String capabilityId, String requirement, String requirementId) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(fromNode); + requirementCapabilityRelDef.setRelationships(new ArrayList<>()); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("something.LINK"); + requirementCapabilityRelDef.getRelationships().add(capabilityRequirementRelationship); + requirementCapabilityRelDef.setToNode(toNode); + return requirementCapabilityRelDef; + } + + @Test + public void validateSerialization() throws IOException { + Service service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("Name"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + ObjectMapper mapper = new ObjectMapper(); + String jsonResult = mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(service); + System.out.println(jsonResult); + + Either<Service, ResponseFormat> serviceResponseFormatEither = new ComponentsUtils(Mockito.mock(AuditingManager.class)).convertJsonToObjectUsingObjectMapper(jsonResult, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + assertTrue(serviceResponseFormatEither.isLeft()); + Map<String, ForwardingPathDataDefinition> paths = serviceResponseFormatEither.left().value().getForwardingPaths(); + assertEquals(paths.size(), 1); + ForwardingPathDataDefinition forwardingPathDataDefinition = paths.values().stream().findAny().get(); + assertEquals(protocol, forwardingPathDataDefinition.getProtocol()); + List<ForwardingPathElementDataDefinition> listToscaDataDefinition = forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition(); + assertEquals(3, listToscaDataDefinition.size()); + assertTrue(listToscaDataDefinition.get(0).getFromNode().equals(nodeA)); + } + + @Test + public void shouldReturnEmptyRelationsObjectsWhenNoComponentInstanceExist() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(super.createServiceObject(false)); + assertTrue(serviceRelations.isEmpty()); + } + + @Test + public void convertServiceToServiceRelations() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(createServiceObject(false)); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String resultString = gson.toJson(serviceRelations); + System.out.println(" RESPONSE BODY: " + resultString); + assertTrue(resultString.contains(fromNode)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java index 572804636d..38aaf92335 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -20,17 +20,8 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; +import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -38,6 +29,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -60,171 +52,152 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; -import fj.data.Either; -import junit.framework.Assert; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class PropertyBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName()); - @Mock - private ServletContext servletContext; - @Mock - private IPropertyOperation propertyOperation; - @Mock - private WebAppContextWrapper webAppContextWrapper; - @Mock - private UserBusinessLogic mockUserAdmin; - @Mock - private WebApplicationContext webAppContext; - @Mock - private ComponentsUtils componentsUtils; - @Mock - private ToscaOperationFacade toscaOperationFacade; - - @InjectMocks - private PropertyBusinessLogic bl = new PropertyBusinessLogic(); - private User user = null; - private String resourceId = "resourceforproperty.0.1"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // User data and management - user = new User(); - user.setUserId("jh003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); -// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - - // Resource Operation mock methods - // getCount -// Either<Integer, StorageOperationStatus> eitherCount = Either.left(0); -// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); -// Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1); -// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); -// Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); -// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class); + @Mock + private ServletContext servletContext; + @Mock + private IPropertyOperation propertyOperation; + @Mock + private WebAppContextWrapper webAppContextWrapper; + @Mock + private UserBusinessLogic mockUserAdmin; + @Mock + private WebApplicationContext webAppContext; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private UserValidations userValidations; + + @InjectMocks + private PropertyBusinessLogic bl = new PropertyBusinessLogic(); + private User user = null; + private String resourceId = "resourceforproperty.0.1"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq("jh003"), anyString(), eq(false))).thenReturn(Either.left(user)); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); +// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + + // Resource Operation mock methods + // getCount +// Either<Integer, StorageOperationStatus> eitherCount = Either.left(0); +// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); +// Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); +// Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); // -// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true)); -// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName("MyResourceName"); - resource.addCategory("Generic", "VoIP"); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - - if (afterCreate) { - resource.setName(resource.getName().toLowerCase()); - resource.setVersion("0.1"); - ; - resource.setUniqueId(resourceId); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - } - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - log.debug(gson.toJson(resource)); - return resource; - } - - // @Test - public void testHappyScenario() { - - String propertyName = "disk_size"; - PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); - Either<EntryData<String, PropertyDefinition>, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); - - if (either.isRight()) { - Assert.assertFalse(true); - } - Assert.assertEquals(newPropertyDefinition, either.left().value()); - } - - @Test - public void getProperty_propertyNotFound() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); - resource.setProperties(Arrays.asList(property1, property2)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); - assertTrue(nonExistingProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty_propertyNotBelongsToResource() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - resource.setProperties(Arrays.asList(property1)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); - assertTrue(notFoundProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty() throws Exception { - Resource resource = new Resource(); - resource.setUniqueId(resourceId); - PropertyDefinition property1 = createPropertyObject("someProperty", null); - resource.setProperties(Arrays.asList(property1)); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); - assertTrue(foundProperty.isLeft()); - assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); - } - - private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { - PropertyDefinition pd = new PropertyDefinition(); - List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); - pd.setConstraints(null); - pd.setDefaultValue("100"); - pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); - pd.setPassword(false); - pd.setRequired(true); - pd.setType("Integer"); - pd.setOwnerId(resourceId); - pd.setUniqueId(resourceId + "." + propertyName); - return pd; - } +// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true)); +// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); + + } + + // @Test + public void testHappyScenario() { + + String propertyName = "disk_size"; + PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); + Either<EntryData<String, PropertyDefinition>, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); + + if (either.isRight()) { + Assert.assertFalse(true); + } + Assert.assertEquals(newPropertyDefinition, either.left().value()); + } + + @Test + public void getProperty_propertyNotFound() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); + resource.setProperties(Arrays.asList(property1, property2)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); + assertTrue(nonExistingProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty_propertyNotBelongsToResource() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + resource.setProperties(Arrays.asList(property1)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); + assertTrue(notFoundProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty() throws Exception { + Resource resource = new Resource(); + resource.setUniqueId(resourceId); + PropertyDefinition property1 = createPropertyObject("someProperty", null); + resource.setProperties(Arrays.asList(property1)); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); + assertTrue(foundProperty.isLeft()); + assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); + } + + private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { + PropertyDefinition pd = new PropertyDefinition(); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + pd.setConstraints(null); + pd.setDefaultValue("100"); + pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); + pd.setPassword(false); + pd.setRequired(true); + pd.setType("Integer"); + pd.setOwnerId(resourceId); + pd.setUniqueId(resourceId + "." + propertyName); + return pd; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java index 30e12e85d0..82389822f3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.BeforeClass; @@ -37,7 +28,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ImportUtils; import org.openecomp.sdc.be.components.impl.ImportUtilsTest; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; @@ -63,310 +54,313 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.PolicyException; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class ResourceImportManagerTest { - private static ConfigurationManager configurationManager; - static ResourceImportManager importManager; - static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class); - static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); - static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); - static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); - static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - static Logger log = Mockito.spy(Logger.class); - - @BeforeClass - public static void beforeClass() throws IOException { - importManager = new ResourceImportManager(); - importManager.setAuditingManager(auditingManager); - when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); - importManager.setResponseFormatManager(responseFormatManager); - importManager.setResourceBusinessLogic(resourceBusinessLogic); - importManager.setToscaOperationFacade(toscaOperationFacade); - ResourceImportManager.setLog(log); - - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - - Configuration configuration = new Configuration(); - configuration.setTitanInMemoryGraph(true); - configurationManager.setConfiguration(configuration); - } + private static ConfigurationManager configurationManager; + static ResourceImportManager importManager; + static AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); + static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + @BeforeClass + public static void beforeClass() throws IOException { + importManager = new ResourceImportManager(); + importManager.setAuditingManager(auditingManager); + when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); + importManager.setResponseFormatManager(responseFormatManager); + importManager.setResourceBusinessLogic(resourceBusinessLogic); + importManager.setToscaOperationFacade(toscaOperationFacade); + + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + Configuration configuration = new Configuration(); + configuration.setTitanInMemoryGraph(true); + configurationManager.setConfiguration(configuration); + } + + @Before + public void beforeTest() { + Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin); + } + + @Test + public void testBasicResourceCreation() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); - @Before - public void beforeTest() { - Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log); - } + User user = new User(); + user.setUserId(resourceMD.getContactId()); + user.setRole("ADMIN"); + user.setFirstName("Jhon"); + user.setLastName("Doh"); + Either<User, ActionStatus> eitherUser = Either.left(user); - @Test - public void testBasicResourceCreation() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - user.setRole("ADMIN"); - user.setFirstName("Jhon"); - user.setLastName("Doh"); - Either<User, ActionStatus> eitherUser = Either.left(user); + setResourceBusinessLogicMock(); - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - Resource resource = createResource.left().value().left; - - testSetConstantMetaData(resource); - testSetMetaDataFromJson(resource, resourceMD); - - testSetDerivedFrom(resource); - testSetProperties(resource); - - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - } - - @Test - public void testResourceCreationFailed() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either<User, ActionStatus> eitherUser = Either.left(user); - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); - - when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); - setResourceBusinessLogicMock(); - - String jsonContent = "this is an invalid yml!"; - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isRight()); - ResponseFormat errorInfoFromTest = createResource.right().value(); - assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); - assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); - assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); - Mockito.verify(log).debug(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Exception.class)); - // Mockito.verify(log).error(Mockito.anyString(), Mockito.anyString(), - // Mockito.anyString()); - - Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)); - - Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - - } - - @Test - public void testResourceCreationWithCapabilities() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either<User, ActionStatus> eitherUser = Either.left(user); - - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - Resource resource = createResource.left().value().left; - testSetCapabilities(resource); - - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); - - } - - @Test - public void testResourceCreationWithRequirments() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either<User, ActionStatus> eitherUser = Either.left(user); - - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - testSetRequirments(createResource.left().value().left); - - } - - private void setResourceBusinessLogicMock() { - when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); - when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) - .thenAnswer(new Answer<Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat>>() { - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left(new ImmutablePair<Resource, ActionStatus>((Resource) args[0], ActionStatus.CREATED)); - - } - }); - when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false))) - .thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { - public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[1]); - - } - }); - when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(EnumMap.class))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { - public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[0]); - - } - }); - when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { - public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[0]); - - } - }); - - Either<Boolean, ResponseFormat> either = Either.left(true); - when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); - } - - public ResponseFormat createGeneralErrorInfo() { - ResponseFormat responseFormat = new ResponseFormat(500); - responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); - return responseFormat; - } - - private UploadResourceInfo createDummyResourceMD() { - UploadResourceInfo resourceMD = new UploadResourceInfo(); - resourceMD.setName("tosca.nodes.BlockStorage"); - resourceMD.setPayloadName("payLoad"); - resourceMD.addSubCategory("Generic", "Infrastructure"); - resourceMD.setContactId("ya107f"); - resourceMD.setResourceIconPath("defaulticon"); - resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); - resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); - return resourceMD; - } - - private void testSetProperties(Resource resource) { - List<PropertyDefinition> propertiesList = resource.getProperties(); - - Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); - for (PropertyDefinition propertyDefinition : propertiesList) { - properties.put(propertyDefinition.getName(), propertyDefinition); - } - - assertTrue(properties.size() == 3); - assertTrue(properties.containsKey("size")); - PropertyDefinition propertyDefinition = properties.get("size"); - assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); - assertTrue(propertyDefinition.getConstraints().size() == 1); - PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); - assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); - - assertTrue(properties.containsKey("volume_id")); - propertyDefinition = properties.get("volume_id"); - assertTrue(propertyDefinition.getType().equals("string")); - assertTrue(propertyDefinition.isRequired() == false); - - assertTrue(properties.containsKey("snapshot_id")); - propertyDefinition = properties.get("snapshot_id"); - assertTrue(propertyDefinition.getType().equals("string")); - assertTrue(propertyDefinition.isRequired() == false); - - } - - private void testSetCapabilities(Resource resource) { - Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities(); - assertTrue(capabilities.size() == 3); - assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); - List<CapabilityDefinition> capabilityList = capabilities.get("tosca.capabilities.Endpoint"); - CapabilityDefinition capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); - assertTrue(capability.getName().equals("data_endpoint")); - - assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); - capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); - capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); - assertTrue(capability.getName().equals("admin_endpoint")); - - assertTrue(capabilities.containsKey("tosca.capabilities.Container")); - capabilityList = capabilities.get("tosca.capabilities.Container"); - capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Container")); - assertTrue(capability.getName().equals("host")); - - List<String> validSourceTypes = capability.getValidSourceTypes(); - assertTrue(validSourceTypes.size() == 1); - assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); - - } - - private void testSetRequirments(Resource resource) { - Map<String, List<RequirementDefinition>> requirements = resource.getRequirements(); - assertTrue(requirements.size() == 2); - - assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); - List<RequirementDefinition> requirementList = requirements.get("tosca.capabilities.network.Linkable"); - RequirementDefinition requirement = requirementList.get(0); - assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); - assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); - assertTrue(requirement.getName().equals("link")); - - assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); - requirementList = requirements.get("tosca.capabilities.network.Bindable"); - requirement = requirementList.get(0); - assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); - assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); - assertTrue(requirement.getName().equals("binding")); - - } - - private void testSetDerivedFrom(Resource resource) { - assertTrue(resource.getDerivedFrom().size() == 1); - assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); - - } - - private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { - - // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) - // ); - assertTrue(resource.getDescription().equals(resourceMD.getDescription())); - assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); - assertTrue(resource.getName().equals(resourceMD.getName())); - - assertTrue(resource.getContactId().equals(resourceMD.getContactId())); - assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); - - // assertTrue( resource.isAbstract() == - // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); - - assertTrue(resourceMD.getTags().size() == resource.getTags().size()); - for (String tag : resource.getTags()) { - assertTrue(resourceMD.getTags().contains(tag)); - } - - } - - private void testSetConstantMetaData(Resource resource) { - assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); - assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); - assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); - assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); - } + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + + testSetConstantMetaData(resource); + testSetMetaDataFromJson(resource, resourceMD); + + testSetDerivedFrom(resource); + testSetProperties(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + } + + @Test + public void testResourceCreationFailed() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); + + when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); + setResourceBusinessLogicMock(); + + String jsonContent = "this is an invalid yml!"; + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isRight()); + ResponseFormat errorInfoFromTest = createResource.right().value(); + assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); + assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); + assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + + } + + @Test + public void testResourceCreationWithCapabilities() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + testSetCapabilities(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); + + } + + @Test + public void testResourceCreationWithRequirments() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + testSetRequirments(createResource.left().value().left); + + } + + private void setResourceBusinessLogicMock() { + when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); + when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) + .thenAnswer(new Answer<Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat>>() { + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left(new ImmutablePair<Resource, ActionStatus>((Resource) args[0], ActionStatus.CREATED)); + + } + }); + when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false))) + .thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[1]); + + } + }); + when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + + Either<Boolean, ResponseFormat> either = Either.left(true); + when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); + } + + public ResponseFormat createGeneralErrorInfo() { + ResponseFormat responseFormat = new ResponseFormat(500); + responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); + return responseFormat; + } + + private UploadResourceInfo createDummyResourceMD() { + UploadResourceInfo resourceMD = new UploadResourceInfo(); + resourceMD.setName("tosca.nodes.BlockStorage"); + resourceMD.setPayloadName("payLoad"); + resourceMD.addSubCategory("Generic", "Infrastructure"); + resourceMD.setContactId("ya107f"); + resourceMD.setResourceIconPath("defaulticon"); + resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); + resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); + resourceMD.setResourceVendorModelNumber("vendorReleaseNumber"); + return resourceMD; + } + + private void testSetProperties(Resource resource) { + List<PropertyDefinition> propertiesList = resource.getProperties(); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + for (PropertyDefinition propertyDefinition : propertiesList) { + properties.put(propertyDefinition.getName(), propertyDefinition); + } + + assertTrue(properties.size() == 3); + assertTrue(properties.containsKey("size")); + PropertyDefinition propertyDefinition = properties.get("size"); + assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); + assertTrue(propertyDefinition.getConstraints().size() == 1); + PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); + assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); + + assertTrue(properties.containsKey("volume_id")); + propertyDefinition = properties.get("volume_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + assertTrue(properties.containsKey("snapshot_id")); + propertyDefinition = properties.get("snapshot_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + } + + private void testSetCapabilities(Resource resource) { + Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities(); + assertTrue(capabilities.size() == 3); + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); + List<CapabilityDefinition> capabilityList = capabilities.get("tosca.capabilities.Endpoint"); + CapabilityDefinition capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); + assertTrue(capability.getName().equals("data_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); + assertTrue(capability.getName().equals("admin_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + capabilityList = capabilities.get("tosca.capabilities.Container"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Container")); + assertTrue(capability.getName().equals("host")); + + List<String> validSourceTypes = capability.getValidSourceTypes(); + assertTrue(validSourceTypes.size() == 1); + assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); + + } + + private void testSetRequirments(Resource resource) { + Map<String, List<RequirementDefinition>> requirements = resource.getRequirements(); + assertTrue(requirements.size() == 2); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); + List<RequirementDefinition> requirementList = requirements.get("tosca.capabilities.network.Linkable"); + RequirementDefinition requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); + assertTrue(requirement.getName().equals("link")); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); + requirementList = requirements.get("tosca.capabilities.network.Bindable"); + requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); + assertTrue(requirement.getName().equals("binding")); + + } + + private void testSetDerivedFrom(Resource resource) { + assertTrue(resource.getDerivedFrom().size() == 1); + assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); + + } + + private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { + + // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) + // ); + assertTrue(resource.getDescription().equals(resourceMD.getDescription())); + assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); + assertTrue(resource.getName().equals(resourceMD.getName())); + assertEquals(resource.getResourceVendorModelNumber(), resourceMD.getResourceVendorModelNumber()); + assertTrue(resource.getContactId().equals(resourceMD.getContactId())); + assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); + + // assertTrue( resource.isAbstract() == + // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); + + assertTrue(resourceMD.getTags().size() == resource.getTags().size()); + for (String tag : resource.getTags()) { + assertTrue(resourceMD.getTags().contains(tag)); + } + + } + + private void testSetConstantMetaData(Resource resource) { + assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); + assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); + assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); + assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java index 9a8f1c5ad8..e750d3ab51 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java @@ -20,71 +20,71 @@ package org.openecomp.sdc.be.components; -import java.util.ArrayList; -import java.util.List; - import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; +import java.util.ArrayList; +import java.util.List; + public class ResourceTestUtils { - public static Resource prepareResource(int resourceIndex) { - Resource r = new Resource(); - r.setName("resource_" + resourceIndex); - r.setDescription("description"); - r.setVendorName("vendor name"); - r.setVendorRelease("vendor release"); - r.setContactId("as123y"); - r.addCategory("Generic", "Infrastructure"); - List<String> arr = new ArrayList<String>(); - arr.add("tosca.nodes.Root"); - r.setDerivedFrom(arr); - List<String> arr1 = new ArrayList<String>(); - arr1.add(r.getName()); - r.setTags(arr1); - r.setIcon("borderElement"); - return r; - } + public static Resource prepareResource(int resourceIndex) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.addCategory("Generic", "Infrastructure"); + List<String> arr = new ArrayList<String>(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List<String> arr1 = new ArrayList<String>(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } - public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { - Resource r = new Resource(); - r.setName("resource_" + resourceIndex); - r.setToscaResourceName("resource_" + resourceIndex); - r.setDescription("description"); - r.setVendorName("vendor name"); - r.setVendorRelease("vendor release"); - r.setContactId("as123y"); - r.setResourceType(resourceType); - r.addCategory("Generic", "Infrastructure"); - List<String> arr = new ArrayList<String>(); - arr.add("tosca.nodes.Root"); - r.setDerivedFrom(arr); - List<String> arr1 = new ArrayList<String>(); - arr1.add(r.getName()); - r.setTags(arr1); - r.setIcon("borderElement"); - return r; - } + public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setToscaResourceName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.setResourceType(resourceType); + r.addCategory("Generic", "Infrastructure"); + List<String> arr = new ArrayList<String>(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List<String> arr1 = new ArrayList<String>(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } - public static Service prepareService(int serviceIndex) { - Service service = new Service(); - service.setName("service_" + serviceIndex); - service.setDescription("desc"); - service.setIcon("icon-service-red1"); - List<String> tags = new ArrayList<String>(); - tags.add(service.getName()); - service.setTags(tags); - CategoryDefinition category = new CategoryDefinition(); - category.setName("Mobility"); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setContactId("as123y"); - service.setProjectCode("123456"); + public static Service prepareService(int serviceIndex) { + Service service = new Service(); + service.setName("service_" + serviceIndex); + service.setDescription("desc"); + service.setIcon("icon-service-red1"); + List<String> tags = new ArrayList<String>(); + tags.add(service.getName()); + service.setTags(tags); + CategoryDefinition category = new CategoryDefinition(); + category.setName("Mobility"); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setContactId("as123y"); + service.setProjectCode("123456"); - return service; - } + return service; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java index 1af1ac3070..bbb381bad3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java @@ -20,31 +20,19 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -83,940 +71,881 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; - -public class ServiceBusinessLogicTest { - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); - private static final String SERVICE_CATEGORY = "Mobility"; - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - ServiceBusinessLogic bl = new ServiceBusinessLogic(); - ResponseFormatManager responseManager = null; - IElementOperation mockElementDao; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - ComponentsUtils componentsUtils = new ComponentsUtils(); - AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); - ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - - User user = null; - Service serviceResponse = null; - Resource genericService = null; - - private static final String CERTIFIED_VERSION = "1.0"; - private static final String UNCERTIFIED_VERSION = "0.2"; - private static final String COMPONNET_ID = "myUniqueId"; - private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; - private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>(); - private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>(); - private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>(); - - public ServiceBusinessLogicTest() { - - } - - @Before - public void setup() { - - ExternalConfiguration.setAppName("catalog-be"); - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); -// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - - // artifact bussinesslogic - ArtifactDefinition artifactDef = new ArtifactDefinition(); - when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); - - // createService - serviceResponse = createServiceObject(true); - Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); - - genericService = setupGenericServiceMock(); - Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); - - - bl = new ServiceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setArtifactBl(artifactBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setCassandraAuditingDao(auditingDao); - bl.setCacheManagerOperation(cacheManager); - - mockAuditingDaoLogic(); - - responseManager = ResponseFormatManager.getInstance(); - - } - - @Test - public void testGetComponentAuditRecordsCertifiedVersion() { - Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); - assertTrue(componentAuditRecords.isLeft()); - int size = componentAuditRecords.left().value().size(); - assertTrue(size == 3); - } - - @Test - public void testGetComponentAuditRecordsUnCertifiedVersion() { - Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); - assertTrue(componentAuditRecords.isLeft()); - int size = componentAuditRecords.left().value().size(); - assertTrue(size == 1); - } - - @Test - public void testHappyScenario() { - Service service = createServiceObject(false); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); - Either<Service, ResponseFormat> createResponse = bl.createService(service, user); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); - } - - private void assertEqualsServiceObject(Service origService, Service newService) { - assertEquals(origService.getContactId(), newService.getContactId()); - assertEquals(origService.getCategories(), newService.getCategories()); - assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); - assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); - assertEquals(origService.getDescription(), newService.getDescription()); - assertEquals(origService.getIcon(), newService.getIcon()); - assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); - assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); - assertEquals(origService.getName(), newService.getName()); - assertEquals(origService.getName(), newService.getName()); - assertEquals(origService.getUniqueId(), newService.getUniqueId()); - assertEquals(origService.getVersion(), newService.getVersion()); - assertEquals(origService.getArtifacts(), newService.getArtifacts()); - assertEquals(origService.getCreationDate(), newService.getCreationDate()); - assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); - assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); - assertEquals(origService.getTags(), newService.getTags()); - } - - private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - /* CREATE validations - start ***********************/ - // Service name - start - - @Test - public void testFailedServiceValidations() { - testServiceNameAlreadyExists(); - testServiceNameEmpty(); - // testServiceNameExceedsLimit(); - testServiceNameWrongFormat(); - testServiceDescriptionEmpty(); - testServiceDescriptionMissing(); - testServiceDescExceedsLimitCreate(); - testServiceDescNotEnglish(); - testServiceIconEmpty(); - testServiceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - // testTagsExceedsLimitCreate(); - // testTagsSingleExcessLimit(); - testTagsNoServiceName(); - testInvalidTag(); - testServiceTagNotExist(); - testServiceTagEmpty(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testInvalidProjectCode(); - testProjectCodeTooLong(); - testProjectCodeTooShort(); - - testResourceContactIdMissing(); - testServiceCategoryExist(); - testServiceBadCategoryCreate(); - testMissingProjectCode(); - } - - private void testServiceNameAlreadyExists() { - String serviceName = "alreadyExist"; - Service serviceExccedsNameLimit = createServiceObject(false); - // 51 chars, the limit is 50 - serviceExccedsNameLimit.setName(serviceName); - List<String> tgs = new ArrayList<String>(); - tgs.add(serviceName); - serviceExccedsNameLimit.setTags(tgs); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); - } - - private void testServiceNameEmpty() { - Service serviceExccedsNameLimit = createServiceObject(false); - serviceExccedsNameLimit.setName(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceNameExceedsLimit() { - Service serviceExccedsNameLimit = createServiceObject(false); - // 51 chars, the limit is 50 - String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse"; - serviceExccedsNameLimit.setName(tooLongServiceName); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testServiceNameWrongFormat() { - Service service = createServiceObject(false); - // contains : - String nameWrongFormat = "ljg\fd"; - service.setName(nameWrongFormat); - - Either<Service, ResponseFormat> createResponse = bl.createService(service, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service name - end - // Service description - start - private void testServiceDescriptionEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setDescription(""); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceDescriptionMissing() { - Service serviceExist = createServiceObject(false); - serviceExist.setDescription(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceDescExceedsLimitCreate() { - Service serviceExccedsDescLimit = createServiceObject(false); - // 1025 chars, the limit is 1024 - String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - serviceExccedsDescLimit.setDescription(tooLongServiceDesc); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testServiceDescNotEnglish() { - Service notEnglish = createServiceObject(false); - // Not english - String tooLongServiceDesc = "\uC2B5"; - notEnglish.setDescription(tooLongServiceDesc); - - Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service description - stop - // Service icon - start - private void testServiceIconEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setIcon(""); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceIconMissing() { - Service serviceExist = createServiceObject(false); - serviceExist.setIcon(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceIconInvalid() { - Service resourceExist = createServiceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Service resourceExist = createServiceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Service icon - stop - // Service tags - start - private void testTagsExceedsLimitCreate() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(serviceExccedsNameLimit.getName()); - - serviceExccedsNameLimit.setTags(tagsList); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExcessLimit() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a"; - String tag2 = serviceExccedsNameLimit.getName(); - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb%#%"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); - - } - - private void testServiceTagNotExist() { - Service serviceExist = createServiceObject(false); - serviceExist.setTags(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testServiceTagEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setTags(new ArrayList<String>()); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - // Service tags - stop - // Service contactId - start - private void testContactIdTooLong() { - Service serviceContactId = createServiceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - serviceContactId.setContactId(contactIdTooLong); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Service serviceContactId = createServiceObject(false); - // 3 letters and 3 digits and special characters - String contactIdTooLong = "yrt134!!!"; - serviceContactId.setContactId(contactIdTooLong); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceContactIdMissing() { - Service resourceExist = createServiceObject(false); - resourceExist.setContactId(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service contactId - stop - // Service category - start - private void testServiceCategoryExist() { - Service serviceExist = createServiceObject(false); - serviceExist.setCategories(null); - - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - } +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; - public void markDistributionAsDeployedTestAlreadyDeployed() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String resultAction = "DResult"; - String did = "123456"; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; - setupBeforeDeploy(notifyAction, requestAction, did); - List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>(); - Map<String, Object> params = new HashMap<String, Object>(); - DistributionDeployEvent event = new DistributionDeployEvent(); +public class ServiceBusinessLogicTest { - event.setAction(resultAction); - event.setDid(did); - event.setStatus("200"); - // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); - // deployEvent.setFields(params); - resultList.add(event); - Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList); + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = null; + + private static final String CERTIFIED_VERSION = "1.0"; + private static final String UNCERTIFIED_VERSION = "0.2"; + private static final String COMPONNET_ID = "myUniqueId"; + private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>(); + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>(); + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>(); + + public ServiceBusinessLogicTest() { + + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); +// when(userValidations.validateUserRole(user)) + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setUserValidations(userValidations); + + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + @Test + public void testGetComponentAuditRecordsCertifiedVersion() { + Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 3); + } + + @Test + public void testGetComponentAuditRecordsUnCertifiedVersion() { + Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 1); + } + + @Test + public void testHappyScenario() { + Service service = createServiceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); + } + + private void validateUserRoles(Role ... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + private void assertEqualsServiceObject(Service origService, Service newService) { + assertEquals(origService.getContactId(), newService.getContactId()); + assertEquals(origService.getCategories(), newService.getCategories()); + assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); + assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); + assertEquals(origService.getDescription(), newService.getDescription()); + assertEquals(origService.getIcon(), newService.getIcon()); + assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); + assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getUniqueId(), newService.getUniqueId()); + assertEquals(origService.getVersion(), newService.getVersion()); + assertEquals(origService.getArtifacts(), newService.getArtifacts()); + assertEquals(origService.getCreationDate(), newService.getCreationDate()); + assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); + assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); + assertEquals(origService.getTags(), newService.getTags()); + } + + private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + /* CREATE validations - start ***********************/ + // Service name - start + + @Test + public void testFailedServiceValidations() { + testServiceNameAlreadyExists(); + testServiceNameEmpty(); + // testServiceNameExceedsLimit(); + testServiceNameWrongFormat(); + testServiceDescriptionEmpty(); + testServiceDescriptionMissing(); + testServiceDescExceedsLimitCreate(); + testServiceDescNotEnglish(); + testServiceIconEmpty(); + testServiceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + // testTagsExceedsLimitCreate(); + // testTagsSingleExcessLimit(); + testTagsNoServiceName(); + testInvalidTag(); + testServiceTagNotExist(); + testServiceTagEmpty(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testInvalidProjectCode(); + testProjectCodeTooLong(); + testProjectCodeTooShort(); + + testResourceContactIdMissing(); + testServiceCategoryExist(); + testServiceBadCategoryCreate(); + testMissingProjectCode(); + } + + private void testServiceNameAlreadyExists() { + String serviceName = "alreadyExist"; + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + serviceExccedsNameLimit.setName(serviceName); + List<String> tgs = new ArrayList<String>(); + tgs.add(serviceName); + serviceExccedsNameLimit.setTags(tgs); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); + } + + private void testServiceNameEmpty() { + Service serviceExccedsNameLimit = createServiceObject(false); + serviceExccedsNameLimit.setName(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceNameWrongFormat() { + Service service = createServiceObject(false); + // contains : + String nameWrongFormat = "ljg\fd"; + service.setName(nameWrongFormat); + + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service name - end + // Service description - start + private void testServiceDescriptionEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(""); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescriptionMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescExceedsLimitCreate() { + Service serviceExccedsDescLimit = createServiceObject(false); + // 1025 chars, the limit is 1024 + String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + serviceExccedsDescLimit.setDescription(tooLongServiceDesc); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testServiceDescNotEnglish() { + Service notEnglish = createServiceObject(false); + // Not english + String tooLongServiceDesc = "\uC2B5"; + notEnglish.setDescription(tooLongServiceDesc); + + Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service description - stop + // Service icon - start + private void testServiceIconEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(""); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceIconMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconInvalid() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + private void testTagsNoServiceName() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb%#%"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); + + } + + private void testServiceTagNotExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testServiceTagEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(new ArrayList<String>()); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + // Service tags - stop + // Service contactId - start + private void testContactIdTooLong() { + Service serviceContactId = createServiceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + serviceContactId.setContactId(contactIdTooLong); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Service serviceContactId = createServiceObject(false); + // 3 letters and 3 digits and special characters + String contactIdTooLong = "yrt134!!!"; + serviceContactId.setContactId(contactIdTooLong); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceContactIdMissing() { + Service resourceExist = createServiceObject(false); + resourceExist.setContactId(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service contactId - stop + // Service category - start + private void testServiceCategoryExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setCategories(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + public void markDistributionAsDeployedTestAlreadyDeployed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String resultAction = "DResult"; + String did = "123456"; - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); + setupBeforeDeploy(notifyAction, requestAction, did); + List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>(); + Map<String, Object> params = new HashMap<String, Object>(); + DistributionDeployEvent event = new DistributionDeployEvent(); - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + event.setAction(resultAction); + event.setDid(did); + event.setStatus("200"); + // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); + // deployEvent.setFields(params); + resultList.add(event); + Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList); - Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); - } + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); - @Test - public void markDistributionAsDeployedTestSuccess() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String did = "123456"; + Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); - setupBeforeDeploy(notifyAction, requestAction, did); + } - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + @Test + public void markDistributionAsDeployedTestSuccess() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; - } + setupBeforeDeploy(notifyAction, requestAction, did); + List<Role> roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.OPS); + when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true)); + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + } - @Test - public void markDistributionAsDeployedTestNotDistributed() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String did = "123456"; + //@Test + public void markDistributionAsDeployedTestNotDistributed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; - setupBeforeDeploy(notifyAction, requestAction, did); - List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>(); - Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList); - Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); + setupBeforeDeploy(notifyAction, requestAction, did); + List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>(); + Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); - Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND); - Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); + Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND); + Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isRight()); - assertEquals(404, markDeployed.right().value().getStatus().intValue()); + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isRight()); + assertEquals(404, markDeployed.right().value().getStatus().intValue()); - } + } - private void testServiceBadCategoryCreate() { + private void testServiceBadCategoryCreate() { - Service serviceExist = createServiceObject(false); - CategoryDefinition category = new CategoryDefinition(); - category.setName("koko"); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - serviceExist.setCategories(categories); + Service serviceExist = createServiceObject(false); + CategoryDefinition category = new CategoryDefinition(); + category.setName("koko"); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + serviceExist.setCategories(categories); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - } + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } - // Service category - stop - // Service projectCode - start - private void testInvalidProjectCode() { + // Service category - stop + // Service projectCode - start + private void testInvalidProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("koko!!"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("koko!!"); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooLong() { + private void testProjectCodeTooLong() { - Service serviceExist = createServiceObject(false); - String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; - serviceExist.setProjectCode(tooLongProjectCode); + Service serviceExist = createServiceObject(false); + String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; + serviceExist.setProjectCode(tooLongProjectCode); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooShort() { + private void testProjectCodeTooShort() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("333"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("333"); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testMissingProjectCode() { + private void testMissingProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode(null); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode(null); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); + } -// @Test -// public void testDeleteMarkedServicesNoServices() { -// List<String> ids = new ArrayList<String>(); -// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// @Test +// public void testDeleteMarkedServicesNoServices() { +// List<String> ids = new ArrayList<String>(); +// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// } - - @Test - @Ignore - public void testDeleteMarkedServices() { - List<String> ids = new ArrayList<String>(); - String resourceInUse = "123"; - ids.add(resourceInUse); - String resourceFree = "456"; - ids.add(resourceFree); - Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); - when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); - - Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); - Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); - - List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); - Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); - - when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); - when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); - - Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); - when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); - - Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); - assertTrue(deleteMarkedResources.isLeft()); - List<String> resourceIdList = deleteMarkedResources.left().value(); - assertFalse(resourceIdList.isEmpty()); - assertTrue(resourceIdList.contains(resourceFree)); - assertFalse(resourceIdList.contains(resourceInUse)); - - } - - private Service createServiceObject(boolean afterCreate) { - Service service = new Service(); - service.setName("Service"); - CategoryDefinition category = new CategoryDefinition(); - category.setName(SERVICE_CATEGORY); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - - service.setDescription("description"); - List<String> tgs = new ArrayList<String>(); - tgs.add(service.getName()); - service.setTags(tgs); - // service.setVendorName("Motorola"); - // service.setVendorRelease("1.0.0"); - service.setIcon("MyIcon"); - // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - service.setContactId("aa1234"); - service.setProjectCode("12345"); - - if (afterCreate) { - service.setVersion("0.1"); - service.setUniqueId(service.getName() + ":" + service.getVersion()); - service.setCreatorUserId(user.getUserId()); - service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - } - return service; - } - - private void mockAuditingDaoLogic() { - FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - - FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); - FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); - - final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); - createResourceAudit.setModifier("Carlos Santana(cs0008)"); - createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); - createResourceAudit.setCurrVersion("0.1"); - createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); - createResourceAudit.setDesc("OK"); - createResourceAudit.setResourceType("Resource"); - createResourceAudit.setStatus("201"); - createResourceAudit.setPrevVersion(""); - createResourceAudit.setAction("Create"); - // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); - createResourceAudit.setPrevState(""); - createResourceAudit.setResourceName("MyTestResource"); - // createResourceAudit.setFields(fields); - - final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); - checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); - checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); - checkInResourceAudit.setCurrVersion("0.1"); - checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); - checkInResourceAudit.setDesc("OK"); - checkInResourceAudit.setComment("Stam"); - checkInResourceAudit.setResourceType("Resource"); - checkInResourceAudit.setStatus("200"); - checkInResourceAudit.setPrevVersion("0.1"); - checkInResourceAudit.setAction("Checkin"); - // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); - checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); - checkInResourceAudit.setResourceName("MyTestResource"); - - final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); - checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); - checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); - checkOutResourceAudit.setCurrVersion("0.2"); - checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); - checkOutResourceAudit.setDesc("OK"); - checkOutResourceAudit.setComment(""); - checkOutResourceAudit.setResourceType("Resource"); - checkOutResourceAudit.setStatus("200"); - checkOutResourceAudit.setPrevVersion("0.1"); - checkOutResourceAudit.setAction("Checkout"); - // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); - checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); - checkOutResourceAudit.setResourceName("MyTestResource"); - // checkOutResourceAudit.setFields(fields); - - // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>, - // ActionStatus> >() { - // public Either<List<ESTimeBasedEvent>, ActionStatus> - // answer(InvocationOnMock invocation) { - // final Either<List<ESTimeBasedEvent>, ActionStatus> either; - // final List<ESTimeBasedEvent> list; - // Object[] args = invocation.getArguments(); - // Map<AuditingFieldsKeysEnum, Object> filterMap = - // (Map<AuditingFieldsKeysEnum, Object>) args[0]; - // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ - // list = new - // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; - // either = Either.left(list); - // - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ - // list = new ArrayList<ESTimeBasedEvent>(); - // either = Either.left(list); - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ - // list = new - // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; - // either = Either.left(list); - // } - // else{ - // either = null; - // } - // return either; - // } - // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); - // - // - List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() { - { - add(createResourceAudit); - add(checkInResourceAudit); - add(checkOutResourceAudit); - } - }; - Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list); - Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); - - List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>(); - Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev); - Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); - - List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() { - { - add(checkOutResourceAudit); - } - }; - Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr); - Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); - - } - - private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { - - DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); - notifyEvent.setAction(notifyAction); - notifyEvent.setDid(did); - notifyEvent.setStatus("200"); - - ResourceAdminEvent requestEvent = new ResourceAdminEvent(); - requestEvent.setAction(requestAction); - requestEvent.setDid(did); - requestEvent.setStatus("200"); - - ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>(); - List<DistributionNotificationEvent> notifyResults = arrayList; - notifyResults.add(notifyEvent); - Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults); - - Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); - - List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>(); - requestResults.add(requestEvent); - Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults); - Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); - - Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true)); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); - - List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>(); - Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList); - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testFindGroupInstanceOnRelatedComponentInstance() { - - Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class; - String methodName = "findGroupInstanceOnRelatedComponentInstance"; - Object invalidId = "invalidId"; - - Component service = createNewService(); - List<ComponentInstance> componentInstances = service.getComponentInstances(); - - Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; - Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - Class[] argClasses = {Component.class, String.class,String.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); - assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); - - Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); - - Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private Component createNewService() { - - Service service = new Service(); - int listSize = 3; - service.setName("serviceName"); - service.setUniqueId("serviceUniqueId"); - List<ComponentInstance> componentInstances = new ArrayList<>(); - ComponentInstance ci; - for(int i= 0; i<listSize; ++i){ - ci = new ComponentInstance(); - ci.setName("ciName" + i); - ci.setUniqueId("ciId" + i); - List<GroupInstance> groupInstances= new ArrayList<>(); - GroupInstance gi; - for(int j = 0; j<listSize; ++j){ - gi = new GroupInstance(); - gi.setName(ci.getName( )+ "giName" + j); - gi.setUniqueId(ci.getName() + "giId" + j); - groupInstances.add(gi); - } - ci.setGroupInstances(groupInstances); - componentInstances.add(ci); - } - service.setComponentInstances(componentInstances); - return service; - } - - - @Test - public void testDerivedFromGeneric() { - Service service = createServiceObject(true); - when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); - Either<Service, ResponseFormat> createResponse = bl.createService(service, user); - assertTrue(createResponse.isLeft()); - service = createResponse.left().value(); - assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); - assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); - } - - - private Resource setupGenericServiceMock(){ - Resource genericService = new Resource(); - genericService.setVersion("1.0"); - genericService.setToscaResourceName(GENERIC_SERVICE_NAME); - return genericService; - } +// } + + @Test + @Ignore + public void testDeleteMarkedServices() { + List<String> ids = new ArrayList<String>(); + String resourceInUse = "123"; + ids.add(resourceInUse); + String resourceFree = "456"; + ids.add(resourceFree); + Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + + Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); + Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); + + List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); + Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); + + when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); + when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); + + Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + List<String> resourceIdList = deleteMarkedResources.left().value(); + assertFalse(resourceIdList.isEmpty()); + assertTrue(resourceIdList.contains(resourceFree)); + assertFalse(resourceIdList.contains(resourceInUse)); + + } + + private Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setUniqueId("sid"); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List<String> tgs = new ArrayList<String>(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + return service; + } + + private void mockAuditingDaoLogic() { + FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); + + final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); + createResourceAudit.setModifier("Carlos Santana(cs0008)"); + createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + createResourceAudit.setCurrVersion("0.1"); + createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); + createResourceAudit.setDesc("OK"); + createResourceAudit.setResourceType("Resource"); + createResourceAudit.setStatus("201"); + createResourceAudit.setPrevVersion(""); + createResourceAudit.setAction("Create"); + // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + // createResourceAudit.setFields(fields); + + final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); + checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); + checkInResourceAudit.setCurrVersion("0.1"); + checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); + checkInResourceAudit.setDesc("OK"); + checkInResourceAudit.setComment("Stam"); + checkInResourceAudit.setResourceType("Resource"); + checkInResourceAudit.setStatus("200"); + checkInResourceAudit.setPrevVersion("0.1"); + checkInResourceAudit.setAction("Checkin"); + // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); + checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); + checkInResourceAudit.setResourceName("MyTestResource"); + + final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); + checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + checkOutResourceAudit.setCurrVersion("0.2"); + checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); + checkOutResourceAudit.setDesc("OK"); + checkOutResourceAudit.setComment(""); + checkOutResourceAudit.setResourceType("Resource"); + checkOutResourceAudit.setStatus("200"); + checkOutResourceAudit.setPrevVersion("0.1"); + checkOutResourceAudit.setAction("Checkout"); + // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + // checkOutResourceAudit.setFields(fields); + + // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>, + // ActionStatus> >() { + // public Either<List<ESTimeBasedEvent>, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either<List<ESTimeBasedEvent>, ActionStatus> either; + // final List<ESTimeBasedEvent> list; + // Object[] args = invocation.getArguments(); + // Map<AuditingFieldsKeysEnum, Object> filterMap = + // (Map<AuditingFieldsKeysEnum, Object>) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList<ESTimeBasedEvent>(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>(); + Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() { + { + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { + + DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); + notifyEvent.setAction(notifyAction); + notifyEvent.setDid(did); + notifyEvent.setStatus("200"); + + ResourceAdminEvent requestEvent = new ResourceAdminEvent(); + requestEvent.setAction(requestAction); + requestEvent.setDid(did); + requestEvent.setStatus("200"); + + ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>(); + List<DistributionNotificationEvent> notifyResults = arrayList; + notifyResults.add(notifyEvent); + Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults); + + Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); + + List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>(); + requestResults.add(requestEvent); + Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); + + Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true)); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); + + List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>(); + Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test @Ignore + public void testFindGroupInstanceOnRelatedComponentInstance() { + + Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class; + String methodName = "findGroupInstanceOnRelatedComponentInstance"; + Object invalidId = "invalidId"; + + Component service = createNewService(); + List<ComponentInstance> componentInstances = service.getComponentInstances(); + + Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; + Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + Class[] argClasses = {Component.class, String.class,String.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); + assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); + + Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); + + Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i<listSize; ++i){ + ci = new ComponentInstance(); + ci.setName("ciName" + i); + ci.setUniqueId("ciId" + i); + List<GroupInstance> groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j<listSize; ++j){ + gi = new GroupInstance(); + gi.setName(ci.getName( )+ "giName" + j); + gi.setUniqueId(ci.getName() + "giId" + j); + groupInstances.add(gi); + } + ci.setGroupInstances(groupInstances); + componentInstances.add(ci); + } + service.setComponentInstances(componentInstances); + return service; + } + + + @Test + public void testDerivedFromGeneric() { + Service service = createServiceObject(true); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + assertTrue(createResponse.isLeft()); + service = createResponse.left().value(); + assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); + assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); + } + + + private Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java new file mode 100644 index 0000000000..fe7152608c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java @@ -0,0 +1,202 @@ +package org.openecomp.sdc.be.components; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionBLTest { + + @InjectMocks + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + + @Mock + ServiceDistributionValidation serviceDistributionValidation; + + @Mock + HealthCheckBusinessLogic healthCheckBusinessLogic; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + ComponentsUtils componentsUtils; + + @Mock + DistributionEngine distributionEngine; + + private Service serviceToActivate; + private ActivationRequestInformation activationRequestInformation; + private String WORKLOAD_CONTEXT = "vnfContext"; + private String TENANT = "tenant"; + private String DID = "distributionId"; + private User modifier; + + + public ServiceDistributionBLTest() { + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + MockitoAnnotations.initMocks(this); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + bl.setComponentsUtils(componentsUtils); + serviceToActivate = new Service(); + serviceToActivate.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + activationRequestInformation = new ActivationRequestInformation(serviceToActivate, WORKLOAD_CONTEXT, TENANT); + when(toscaOperationFacade.getToscaElement(anyString(), any(ComponentParametersView.class))) + .thenReturn(Either.left(serviceToActivate)); + when(distributionEngine.buildServiceForDistribution(any(Service.class), anyString(), anyString())) + .thenReturn(new NotificationDataImpl()); + modifier = new User(); + modifier.setUserId("uid"); + modifier.setFirstName("user"); + } + + @Test + public void testActivateServiceOnTenantValidationFails() { + int VALIDATION_FAIL_STATUS = 666; + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS))); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == VALIDATION_FAIL_STATUS); + } + + @Test + public void testNoDeploymentArtifacts() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 409); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4139")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionAuthenticationFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.AUTHENTICATION_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionUnknownHostFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.UNKNOWN_HOST); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionConnectionErrorFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.CONNNECTION_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionObjectNotFoundFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.OBJECT_NOT_FOUND); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionGeneralFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.GENERAL_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionOk() { + mockAllMethodsUntilDENotification(); + ThreadLocalsHolder.setUuid(DID); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.OK); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isLeft()); + assertTrue(stringResponseFormatEither.left().value().equals(DID)); + } + + private void mockAllMethodsUntilDENotification() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.OK); + } + + private Either<String, ResponseFormat> callActivateServiceOnTenantWIthDefaults() { + return bl.activateServiceOnTenantEnvironment("serviceId", "envId", modifier, new ServiceDistributionReqInfo("workload")); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java deleted file mode 100644 index 90a02a2fc5..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.openecomp.sdc.be.components.clean; - -import org.junit.Test; - - -public class AsdcComponentsCleanerTaskTest { - - private AsdcComponentsCleanerTask createTestSubject() { - return new AsdcComponentsCleanerTask(); - } - - - @Test - public void testInit() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.init(); - } - - - @Test - public void testDestroy() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.destroy(); - } - - - @Test - public void testStartTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.startTask(); - } - - - @Test - public void testStopTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.stopTask(); - } - - - - - - @Test - public void testRun() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.run(); - } -}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java new file mode 100644 index 0000000000..7df88c1cd9 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.http.HttpStatus; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static org.junit.Assert.assertTrue; + +public class AaiMockRequestHandlerTest extends BeConfDependentTest { + + @Ignore + @Test + public void testGetOperationalEnvJson() { + String id = "OEid4"; + AaiRequestHandler aaiRequestHandler = new AaiRequestHandler(); + aaiRequestHandler.init(); + HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id); + + if (resp.getStatusCode() == HttpStatus.SC_OK) { + try { + String response = resp.getResponse(); + System.out.println("The rest response is:"); + System.out.println(response); + + OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(response); + + System.out.println(String.format("Get \"%s\" operational environment. %s", id, operationalEnvInfo)); + System.out.println(operationalEnvInfo); + } + catch (Exception e) { + System.out.println(String.format("Json convert to OperationalEnvInfo failed with exception %s", e)); + System.out.println(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + else { + System.out.println("The rest response is:"); + String response = resp.getResponse(); + System.out.println(response); + System.out.println(String.format("Get \"%s\" operational environment failed with statusCode: %s, response: %s, description: %s", id, resp.getStatusCode(), resp.getResponse(), resp.getDescription())); + System.out.println(resp.getStatusCode()); + } + + assertTrue(true); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java new file mode 100644 index 0000000000..d425e6d0f5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java @@ -0,0 +1,77 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaIdentityManager; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class CambriaHandlerTest { + @Spy + private CambriaHandler handler = new CambriaHandler(); + + @Mock + private CambriaIdentityManager createIdentityManager; + + private ApiCredential apiCredential = new ApiCredential("apiKey", "apiSecret"); + + @BeforeClass + public static void beforeClass() { + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + new ConfigurationManager(configurationSource); + } + + + @Before + public void startUp() throws MalformedURLException, GeneralSecurityException { + doReturn(createIdentityManager).when(handler).buildCambriaClient(any()); + } + + @Test + public void testCreateUebKeys() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenReturn(apiCredential); + Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + + Mockito.verify(createIdentityManager).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isLeft()); + + } + + @Test + public void testCreateUebKeys_FAIL() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenThrow(new CambriaApiException("Error Message")); + Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + Mockito.verify(createIdentityManager, Mockito.never()).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isRight()); + CambriaErrorResponse response = eitherCreateUebKeys.right().value(); + assertEquals("Unexpected Operational Status", CambriaOperationStatus.CONNNECTION_ERROR, response.getOperationStatus()); + assertEquals("Unexpected HTTP Code", 500, response.getHttpCode().intValue()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java new file mode 100644 index 0000000000..45906c6f30 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRConsumer; +import com.google.gson.GsonBuilder; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.concurrent.ExecutorService; +import java.util.stream.IntStream; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class Dev2DevDmaapConsumerTest { + @Autowired + private ExecutorFactory executorFactory; + @Autowired + private DmaapClientFactory dmaapClientFactory; + + static ExecutorService notificationExecutor; + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @Test + public void runConsumer() throws Exception{ + boolean isRunConsumer = false ; //change this to true if you wish to run consumer,default should be false + if ( isRunConsumer ){ + consumeDmaapTopic(); + }else{ + System.out.println( "CONSUMER TEST is disabled!!!! "); + } + assert true; + } + //@Ignore + //@Test + public void consumeDmaapTopic() throws Exception { + Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + System.out.println("uncaughtException -> "); + } + }; + + DmaapConsumerConfiguration dmaapConsumerParams = configurationManager.getConfiguration().getDmaapConsumerConfiguration(); + String topic = dmaapConsumerParams.getTopic(); + System.out.println(String.format( "Starting to consume topic %s for DMAAP consumer with the next parameters %s. ", topic, dmaapConsumerParams) ); + MRConsumer consumer = dmaapClientFactory.create( dmaapConsumerParams ); + notificationExecutor = executorFactory.create(topic + "Consumer", handler); + final int LIMIT = 2; + IntStream.range(0,LIMIT).forEach( i -> { + System.out.println("Trying to fetch messages from topic: "+ topic); + try { + Iterable<String> messages = consumer.fetch(); + if (messages != null) { + for (String msg : messages) { + System.out.println(String.format( "The DMAAP message %s received. The topic is %s.", msg, topic) ); + handleMessage(msg); + } + } + } + catch (Exception e) { + System.out.println("The exception occured upon fetching DMAAP message "+ e); + } + } + ); + + + } + private void handleMessage(String msg){ + try{ + DmaapNotificationDataImpl notificationData = new GsonBuilder().create().fromJson(msg,DmaapNotificationDataImpl.class); + System.out.println( "successfully parsed notification for environemnt "+notificationData.getOperationalEnvironmentId()); + }catch (Exception e){ + System.out.println( "failed to parse notification"); + } + } + @After + public void after(){ + if (notificationExecutor!=null && !notificationExecutor.isTerminated()) + notificationExecutor.shutdown(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java index 8d48a4c320..04aa242b03 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java @@ -20,13 +20,6 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -38,131 +31,138 @@ import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class DistributionEngineConfigTest { - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } - @Test - public void validateMissingEnvironments() { + @Test + public void validateMissingEnvironments() { - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - String uebPublicKey = "uebPublicKey"; - String uebSecretKey = "uebSecretKey"; + String uebPublicKey = "uebPublicKey"; + String uebSecretKey = "uebSecretKey"; - DistributionEngine distributionEngine = new DistributionEngine(); + DistributionEngine distributionEngine = new DistributionEngine(); - List<String> environments = new ArrayList<String>(); - environments.add("PROD"); - deConfiguration.setEnvironments(environments); + List<String> environments = new ArrayList<String>(); + environments.add("PROD"); + deConfiguration.setEnvironments(environments); - List<String> servers = new ArrayList<String>(); - servers.add("server1:80"); - servers.add("server2:8080"); + List<String> servers = new ArrayList<String>(); + servers.add("server1:80"); + servers.add("server2:8080"); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); - ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); + ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); - ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); + ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); - deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); - deConfiguration.setDistributionStatusTopicName("statusTopic"); + deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); + deConfiguration.setDistributionStatusTopicName("statusTopic"); - DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); - distributionStatusTopic.setConsumerGroup("asdc-group"); - distributionStatusTopic.setConsumerId("asdc-id"); - distributionStatusTopic.setFetchTimeSec(20); - distributionStatusTopic.setPollingIntervalSec(20); - deConfiguration.setDistributionStatusTopic(distributionStatusTopic); + DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); + distributionStatusTopic.setConsumerGroup("asdc-group"); + distributionStatusTopic.setConsumerId("asdc-id"); + distributionStatusTopic.setFetchTimeSec(20); + distributionStatusTopic.setPollingIntervalSec(20); + deConfiguration.setDistributionStatusTopic(distributionStatusTopic); - deConfiguration.setUebServers(servers); - deConfiguration.setUebPublicKey(uebPublicKey); - deConfiguration.setUebSecretKey(uebSecretKey); - deConfiguration.setInitMaxIntervalSec(8); - deConfiguration.setInitRetryIntervalSec(3); + deConfiguration.setUebServers(servers); + deConfiguration.setUebPublicKey(uebPublicKey); + deConfiguration.setUebSecretKey(uebSecretKey); + deConfiguration.setInitMaxIntervalSec(8); + deConfiguration.setInitRetryIntervalSec(3); - boolean isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + boolean isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebServers(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebServers(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebServers(servers); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebServers(servers); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setEnvironments(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setEnvironments(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setEnvironments(environments); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setEnvironments(environments); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebPublicKey(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebPublicKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebPublicKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebPublicKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebSecretKey(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebSecretKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebSecretKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebSecretKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setDistributionNotifTopicName(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setDistributionNotifTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionNotifTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setDistributionNotifTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setDistributionStatusTopicName(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setDistributionStatusTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionStatusTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setDistributionStatusTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setInitMaxIntervalSec(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setInitMaxIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitMaxIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setInitMaxIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setInitRetryIntervalSec(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setInitRetryIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitRetryIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setInitRetryIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java index 990ea4f99b..1fa0fc60b7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java @@ -20,115 +20,114 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.List; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; -import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; -public class DistributionEngineHealthCheckTest extends BaseConfDependentTest { - - @Mock - private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); - - DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); - - Gson gson = new Gson(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - // - // @Test - // public void validateDownWhenEnvAreDown() { - // - // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); - // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); - // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); - // - // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); - // - // HealthCheckInfo healthCheckInfo = - // distributionEngineClusterHealth.getHealthCheckInfo(); - // assertEquals("verify down", HealthCheckStatus.DOWN, - // healthCheckInfo.getHealthCheckStatus()); - // assertEquals("verify DE component", HealthCheckComponent.DE, - // healthCheckInfo.getHealthCheckComponent()); - // - // } - - @Test - public void validateUpWhenQuerySucceed() { - - // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); - // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); - // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); - // - // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, - // false); - - CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); - - List<String> uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - } - - UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - Boolean call1 = healthCheckCall1.call(); - assertTrue("check response okay", call1); - - UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - Boolean call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - } - healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - - call1 = healthCheckCall1.call(); - assertFalse("check response okay", call1); - - healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); - } - healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - - call1 = healthCheckCall1.call(); - assertFalse("check response okay", call1); - - healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - } +public class DistributionEngineHealthCheckTest extends BeConfDependentTest { + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); + + Gson gson = new Gson(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + // + // @Test + // public void validateDownWhenEnvAreDown() { + // + // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + // + // HealthCheckInfo healthCheckInfo = + // distributionEngineClusterHealth.getHealthCheckInfo(); + // assertEquals("verify down", HealthCheckStatus.DOWN, + // healthCheckInfo.getHealthCheckStatus()); + // assertEquals("verify DE component", HealthCheckComponent.DE, + // healthCheckInfo.getHealthCheckComponent()); + // + // } + + @Test + public void validateUpWhenQuerySucceed() { + + // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, + // false); + + CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); + + List<String> uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + + UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + Boolean call1 = healthCheckCall1.call(); + assertTrue("check response okay", call1); + + UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + Boolean call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java index 5bf12d56bc..03a6625cae 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java @@ -20,19 +20,9 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.BeforeClass; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -41,224 +31,252 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; -import fj.data.Either; - -public class DistributionEngineInitTaskTest { - - @Mock - private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - @Mock - private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); - - // public static final IAuditingDao iAuditingDao = - // Mockito.mock(AuditingDao.class); - - @BeforeClass - public static void setup() { - // ExternalConfiguration.setAppName("distribEngine1"); - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } - - @Test - public void checkIncrement() { - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - - for (int i = 1; i < 5; i++) { - initTask.incrementRetryInterval(); - assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); - } - - initTask.incrementRetryInterval(); - assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); - - } - - @Test - public void testInitFlowScenarioSuccess() { - - String notifTopic = "notif"; - String statusTopic = "status"; - - List<String> uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); - Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); - - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(cambriaErrorResponse); - - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - boolean initFlow = initTask.initFlow(); - assertTrue("check init flow succeed", initFlow); - - } - - @Test - public void testInitFlowScenarioSuccessTopicsAlreadyExists() { - - String envName = "PrOD"; - String notifTopic = "notif"; - String statusTopic = "status"; - - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; - Set<String> topics = new HashSet<String>(); - topics.add(realNotifTopic); - topics.add(realStatusTopic); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - List<String> uebServers = new ArrayList<>(); - uebServers.add("server1"); - Either<Set<String>, CambriaErrorResponse> left = Either.left(topics); - - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(cambriaErrorResponse); - - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - try { - boolean initFlow = initTask.initFlow(); - assertTrue("check init flow succeed", initFlow); - } catch (Exception e) { - assertTrue("Should not throw exception", false); - } - - } +public class DistributionEngineInitTaskTest { - @Test - public void testInitFlowScenarioFailToRegister() { + @Mock + private ComponentsUtils componentsUtils; - String notifTopic = "notif"; - String statusTopic = "status"; - - List<String> uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); - Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); + @Mock + private CambriaHandler cambriaHandler; - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + new ConfigurationManager(configurationSource); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + componentsUtils = Mockito.mock(ComponentsUtils.class); + cambriaHandler = Mockito.mock(CambriaHandler.class); + } + + @Test + public void checkIncrement() { - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + + for (int i = 1; i < 5; i++) { + initTask.incrementRetryInterval(); + assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); + } + + initTask.incrementRetryInterval(); + assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioSuccess() { + String notifTopic = "notif"; + String statusTopic = "status"; + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); - boolean initFlow = initTask.initFlow(); - assertFalse("check init flow failed", initFlow); + } - } + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioSuccessTopicsAlreadyExists() { - @Test - public void testInitFlowScenario1GetTopicsFailed() { - - List<String> uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); - Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - boolean initFlow = initTask.initFlow(); - assertFalse("check init flow failed", initFlow); - - } + String envName = "PrOD"; + String notifTopic = "notif"; + String statusTopic = "status"; + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + + Set<String> topics = new HashSet<String>(); + topics.add(realNotifTopic); + topics.add(realStatusTopic); + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + Either<Set<String>, CambriaErrorResponse> left = Either.left(topics); + + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + try { + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + } catch (Exception e) { + assertTrue("Should not throw exception", false); + } + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioFailToRegister() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenario1GetTopicsFailed() { + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + private OperationalEnvironmentEntry readEnvFromConfig(DistributionEngineConfiguration distributionEngineConfiguration) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey()); + entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey()); + Set<String> puebEndpoints = new HashSet<>(); + if(distributionEngineConfiguration.getUebServers() != null) + puebEndpoints.addAll(distributionEngineConfiguration.getUebServers()); + entry.setDmaapUebAddress(puebEndpoints); + String envName = "UNKNOWN"; + if(CollectionUtils.isNotEmpty(distributionEngineConfiguration.getEnvironments())) + envName = distributionEngineConfiguration.getEnvironments().get(0); + entry.setEnvironmentId(envName); + return entry; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java new file mode 100644 index 0000000000..b1a43eaa57 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.OperationalEnvironmentBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class DistributionEngineTest { + + public static final String DISTRIBUTION_ID = "distId"; + public static final String ENV_ID = "envId"; + public static final String USER_ID = "userId"; + public static final String MODIFIER = "modifier"; + + @InjectMocks + private DistributionEngine testInstance; + + @Mock + private EnvironmentsEngine environmentsEngine; + + @Mock + private DistributionNotificationSender distributionNotificationSender; + + private DummyDistributionConfigurationManager distributionEngineConfigurationMock; + + private Map<String, OperationalEnvironmentEntry> envs; + + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + envs = getEnvs(ENV_ID); + } + + @Test + public void notifyService() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.OK, actionStatus); + } + + @Test + public void notifyService_couldNotResolveEnvironment() throws Exception { + when(environmentsEngine.getEnvironments()).thenReturn(envs); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, new Service(), new NotificationDataImpl(), "someNonExisitngEnv", USER_ID, MODIFIER); + assertEquals(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, actionStatus); + verifyZeroInteractions(distributionNotificationSender); + } + + @Test + public void notifyService_failedWhileSendingNotification() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); + } + + private Map<String, OperationalEnvironmentEntry> getEnvs(String ... environmentIds) { + Set<String> uebAddress = new HashSet<>(); + uebAddress.add("someAddress"); + return Stream.of(environmentIds) + .map(id -> new OperationalEnvironmentBuilder().setEnvId(id).setDmaapUebAddress(uebAddress).build()) + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java new file mode 100644 index 0000000000..1118385143 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; + +public class DummyDistributionConfigurationManager { + + private DistributionEngineConfiguration configurationMock = Mockito.mock(DistributionEngineConfiguration.class); + + public DummyDistributionConfigurationManager() { + new ConfigurationManager(new DummyConfigurationSource()); + } + + public class DummyConfigurationSource implements ConfigurationSource { + + @SuppressWarnings("unchecked") + @Override + public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + if (className.equals(DistributionEngineConfiguration.class)) { + return (T)configurationMock; + } + return null; + } + + @Override + public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + + } + } + + public DistributionEngineConfiguration getConfigurationMock() { + return configurationMock; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java new file mode 100644 index 0000000000..514618c89a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java @@ -0,0 +1,190 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import fj.data.Either; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(value = MockitoJUnitRunner.class) +public class EnvironmentsEngineTest { + + @InjectMocks + private EnvironmentsEngine envEngine; + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ConfigurationManager configurationManager; + @Mock + private DistributionEngineConfiguration distributionEngineConfiguration; + @Mock + private AaiRequestHandler aaiRequestHandler; + + @Before + public void preStart() { + when(configurationManager.getDistributionEngineConfiguration()).thenReturn(distributionEngineConfiguration); + envEngine.setConfigurationManager(configurationManager); + } + + @Test + public void testInit() { + List<OperationalEnvironmentEntry> entryList = Arrays.asList(createOpEnvEntry("Env1"), createOpEnvEntry("Env2")); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> successEither = Either.left(entryList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(successEither); + + when(distributionEngineConfiguration.getEnvironments()).thenReturn(Arrays.asList("Env Loaded From Configuration")); + when(distributionEngineConfiguration.getUebPublicKey()).thenReturn("Dummy Public Key"); + when(distributionEngineConfiguration.getUebSecretKey()).thenReturn("Dummy Private Key"); + when(distributionEngineConfiguration.getUebServers()).thenReturn( + Arrays.asList("uebsb91kcdc.it.att.com:3904", "uebsb92kcdc.it.att.com:3904", "uebsb91kcdc.it.att.com:3904")); + + envEngine.init(); + + Map<String, OperationalEnvironmentEntry> mapEnvs = envEngine.getEnvironments(); + assertEquals("unexpected size of map",3, mapEnvs.size()); + } + + + @Test + public void testGetFullOperationalEnvByIdSuccess() { + String json = getFullOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + @Test + public void testGetPartialOperationalEnvByIdSuccess() { + String json = getPartialOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + + @Test + public void testGetOperationalEnvByIdFailedByJsonConvert() { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(jsonCorrupted, HttpStatus.SC_OK, "Successfully Completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_INTERNAL_SERVER_ERROR, response.right().value()); + } + + @Test + public void testGetOperationalEnvByIdFailed404() { + String json = getFullOperationalEnvJson(); + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_NOT_FOUND, "Not Found"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_NOT_FOUND, response.right().value()); + } + + + @Test(expected = IOException.class) + public void testCorruptedOperationalEnvJson() throws IOException { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + OperationalEnvInfo.createFromJson(jsonCorrupted); + } + + private String getCorruptedOperationalEnvJson() { + return "{\"OPERATIONAL-environment-name\":\"Op Env Name\"," + + "\"OPERATIONAL-environment-type\":\"VNF\"," + + "\"OPERATIONAL-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"}"; + } + + private String getPartialOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"UUID of Operational Environment\"," + + "\"operational-environment-name\":\"Op Env Name\"," + + "\"operational-environment-type\":\"VNF\"," + + "\"operational-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"," + + "\"workload-context\":\"VNF_Development\"," + + "\"resource-version\":\"1505228226913\"," + + "\"relationship-list\":{" + + "\"relationship\":[]" + + "}" + + "}"; + } + + private String getFullOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"OEid1\"," + + "\"operational-environment-name\":\"OEname1\"," + + "\"operational-environment-type\":\"OEtype1\"," + + "\"operational-environment-status\":\"OEstatus1\"," + + "\"tenant-context\":\"OEtenantcontext1\"," + + "\"workload-context\":\"OEworkloadcontext1\"," + + "\"resource-version\":\"1511363173278\"," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-to\":\"operational-environment\"," + + "\"relationship-label\":\"managedBy\"," + + "\"related-link\":\"/aai/v12/cloud-infrastructure/operational-environments/operational-environment/OEid3\"," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"operational-environment.operational-environment-id\"," + + "\"relationship-value\":\"OEid3\"" + + "}" + + "]," + + "\"related-to-property\":[" + + "{" + + "\"property-key\":\"operational-environment.operational-environment-name\"," + + "\"property-value\":\"OEname3\"" + + "}]}]}}"; + } + + private OperationalEnvironmentEntry createOpEnvEntry(String name) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setEnvironmentId(name); + return entry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java new file mode 100644 index 0000000000..1a2ca4840d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java @@ -0,0 +1,310 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import cucumber.api.java.Before; +import cucumber.api.java.en.Given; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; +import fj.data.Either; +import org.apache.commons.lang.NotImplementedException; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.http.HttpStatus; +import org.junit.Assert; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static java.util.Objects.isNull; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class StepsTenantIsolation { + + // Notification Fields + private String operationalEnvironmentId = "28122015552391"; + private String operationalEnvironmentName = "Operational Environment Name"; + private String operationalEnvironmentType; + private String tenantContext ; + private String workloadContext; + private String action; + + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private AaiRequestHandler aaiRequestHandler; + @Mock + private CambriaHandler cambriaHandler; + @InjectMocks + @Spy + private EnvironmentsEngine envEngine; + + private boolean isSuccessful; + private boolean cassandraUp; + + @Before + public void beforeScenario() { + MockitoAnnotations.initMocks(this); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)) + .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND)); + doNothing().when(envEngine).createUebTopicsForEnvironments(); + envEngine.init(); + } + + // ############################# Given - Start ############################# + @Given("^Dmaap consumer recieved notification with fields (.*)$") + public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable { + Gson gson = new GsonBuilder().create(); + IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class); + if (!isNull(notification.getOperationalEnvironmentType())) { + this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName(); + } + if( !isEmpty(notification.getOperationalEnvironmentId()) ){ + this.operationalEnvironmentId = notification.getOperationalEnvironmentId(); + } + if( !isNull(notification.getAction()) ){ + this.action = notification.getAction().getActionName(); + } + + } + + @Given("^Cassandra service status is (.*)$") + public void cassandra_service_status_is(String status) throws Throwable { + switch (status) { + case "UP": + this.cassandraUp = true; + break; + case "DOWN": + when(operationalEnvironmentDao.get(operationalEnvironmentId)) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.GENERAL_ERROR); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^Record status is (.*)$") + public void record_status_is(String status) throws Throwable { + if (!cassandraUp) { + return; + } + Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherResult; + final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class); + switch (status) { + case "FOUND_IN_PROGRESS": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_COMPLETED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_FAILED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName()); + eitherResult = Either.left(entryMock); + break; + case "NOT_FOUND": + eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND); + break; + default: + throw new NotImplementedException(); + } + + when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.OK); + } + + @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$") + public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable { + this.tenantContext = tenant; + this.workloadContext = workload; + HttpResponse<String> resp = Mockito.mock(HttpResponse.class); + when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp); + switch (aaiServiceStatus) { + case "UP": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK); + String aaiResponseTemplate = + //@formatter:off + "{\r\n" + + " \"operational-environment-id\": \"%s\",\r\n" + + " \"operational-environment-name\": \"%s\",\r\n" + + " \"operational-environment-type\": \"%s\",\r\n" + + " \"operational-environment-status\": \"IN-PROGRESS\",\r\n" + + " \"tenant-context\": \"%s\",\r\n" + + " \"workload-context\": \"%s\"\r\n" + + " }"; + //@formatter:on + when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId, + operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext)); + + break; + case "DOWN": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^AFT_DME service status is (.*)$") + public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable { + switch (aftDmeStatus) { + case "UP": + DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class); + when(mockItr.hasNext()).thenReturn(false); + when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr); + break; + case "DOWN": + when(epIterCreator.create(Mockito.anyString())) + .thenThrow(new DME2Exception("dummyCode", new NotImplementedException())); + break; + default: + throw new NotImplementedException(); + } + } + + @SuppressWarnings("unchecked") + @Given("^UEB service status is (.*)$") + public void ueb_service_status_is(String status) throws Throwable { + + Either<ApiCredential, CambriaErrorResponse> response; + switch (status) { + case "UP": + ApiCredential apiCredential = Mockito.mock(ApiCredential.class); + when(apiCredential.getApiKey()).thenReturn("MockAPIKey"); + when(apiCredential.getApiSecret()).thenReturn("MockSecretKey"); + response = Either.left(apiCredential); + break; + case "DOWN": + CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class); + response = Either.right(cambriaError); + break; + default: + throw new NotImplementedException(); + } + when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response); + } + // ############################# Given - End ############################# + + // ############################# When - Start ############################# + + @When("^handle message is activated$") + public void handle_message_is_activated() throws Throwable { + this.isSuccessful = envEngine.handleMessage(buildNotification()); + } + // ############################# When - End ############################# + + // ############################# Then - Start ############################# + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of eventType (.*)$") + public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class), + Mockito.any(IDmaapAuditNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to write message to audit log and table (.*)$") + public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable { + int count = isUnsupportedTypeEventRecorded ? 2 : 1; + verify(componentsUtils, Mockito.atLeast(count)) + .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId), + Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of action (.*)$") + public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of state (.*)$") + public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to save in-progress record (.*)$") + public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to get environment info from A&AI API (.*)$") + public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$") + public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts( + Mockito.anyString(), Mockito.anyString()); + + } + + @SuppressWarnings("unchecked") + @Then("^trying to create Ueb keys (.*)$") + public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^trying to create Ueb Topics (.*)$") + public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^handle message finished successfully (.*)$") + public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable { + Assert.assertTrue(this.isSuccessful == isSuccessfull); + } + + // ############################# Then - End ############################# + + private String buildNotification() { + String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n" + + " \"operationalEnvironmentName\": \"%s\",\r\n" + + " \"operationalEnvironmentType\": \"%s\",\r\n" + " \"tenantContext\": \"%s\",\r\n" + + " \"workloadContext\": \"%s\",\r\n" + " \"action\": \"%s\"}"; + + String notification = String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + return notification; + } + + private int getNumberOfCallsToValidate(boolean isValidated) { + return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java deleted file mode 100644 index 712e16d97a..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.openecomp.sdc.be.components.distribution.engine; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses( - -{ DistributionEngineInitTaskTest.class, DistributionEngineConfigTest.class, DistributionEngineHealthCheckTest.class, - VfModuleArtifactPayloadTest.class }) -public class TestSuite { // nothing -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java new file mode 100644 index 0000000000..9d0e8cd683 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java @@ -0,0 +1,135 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.matching.AnythingPattern; +import com.github.tomakehurst.wiremock.matching.UrlPattern; +import fj.data.Either; +import org.apache.http.HttpHeaders; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum; +import org.openecomp.sdc.be.components.distribution.engine.DummyDistributionConfigurationManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.*; +import org.openecomp.sdc.security.SecurityUtil; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +public class MsoRestClientTest { + + private static final String MSO_HOST = "127.0.0.1"; + private static final String MSO_API_URL = "onap/mso/infra/modelDistributions/v1"; + private static final String DISTRIBUTION_ID = "1000"; + + private MSORestClient msoRestClient; + + @ClassRule + public static WireMockRule msoRestServer = new WireMockRule(options() + .dynamicPort() + .bindAddress(MSO_HOST)); + + @Before + public void setupMsoServer() throws Exception { + String encodedPw = ""; + Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(getPwd()); + if(passkey.isLeft()) { + encodedPw = passkey.left().value(); + } + else { + throw new IllegalArgumentException(passkey.right().value()); + } + + msoRestServer.resetToDefaultMappings(); + msoRestServer.stubFor(patch(urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl()))) + .withBasicAuth(getUserName(), encodedPw) + .withHeader(HttpHeaders.CONTENT_TYPE, containing("application/json")) + .withRequestBody(matchingJsonPath("$.status")) + .withRequestBody(matchingJsonPath("$.errorReason", new AnythingPattern()))//error reason is not mandatory + .willReturn(aResponse().withStatus(200))); + } + + @Before + public void setUp() throws Exception { + DummyDistributionConfigurationManager distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + when(distributionEngineConfigurationMock.getConfigurationMock().getMsoConfig()).thenReturn(new MsoDummyConfig(msoRestServer.port())); + msoRestClient = new MSORestClient(); + } + + @Test + public void notifyDistributionComplete_emptyErrReason() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, ""); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + private int getNumOfRetries() { + return ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getNumOfRetries(); + } + + @Test + public void notifyDistributionComplete_noErrReason() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, null); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void notifyDistributionComplete_completeWithError() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void testRetries() throws Exception { + int readTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getTimeouts().getReadTimeoutMs(); + int expectedNumOfRetries = getNumOfRetries(); + + UrlPattern msoReqUrlPattern = urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl())); + msoRestServer.stubFor(patch(msoReqUrlPattern) + .willReturn(new ResponseDefinitionBuilder().withFixedDelay(readTimeout + 1))); + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + verify(expectedNumOfRetries + 1, patchRequestedFor(msoReqUrlPattern)); + assertThat(response.getStatusCode()).isEqualTo(500); + } + + private static String getDistributionsUrl() { + return "/distributions"; + } + + private static String getUserName() { + return "asdc"; + } + + private static String getPwd() { + return "OTLEp5lfVhYdyw5EAtTUBQ=="; + } + + private static class MsoDummyConfig extends ExternalServiceConfig { + int port; + + MsoDummyConfig(int port) { + this.port = port; + + BasicAuthorization basicAuthorization = new BasicAuthorization(); + basicAuthorization.setUserName(MsoRestClientTest.getUserName()); + basicAuthorization.setPassword(getPwd()); + HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(500, 2000), basicAuthorization); + httpClientConfig.setNumOfRetries(getNumOfRetries()); + super.setHttpClientConfig(httpClientConfig); + + HttpRequestConfig httpRequestConfig = new HttpRequestConfig(); + httpRequestConfig.setServerRootUrl(String.format("http://%s:%s/%s", MSO_HOST, this.port, MSO_API_URL)); + httpRequestConfig.getResourceNamespaces().put(MSORestClient.DISTRIBUTIONS_RESOURCE_CONFIG_PARAM, getDistributionsUrl()); + super.setHttpRequestConfig(httpRequestConfig); + } + + int getNumOfRetries() { + return 1; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index c57f2a65af..bebe29f13e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -20,28 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -55,6 +41,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -70,6 +57,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -84,294 +72,359 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; public class ArtifactBusinessLogicTest { - public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - @InjectMocks - private static ArtifactsBusinessLogic artifactBL; - @Mock - private ArtifactOperation artifactOperation; - @Mock - public ComponentsUtils componentsUtils; - @Mock - private IInterfaceLifecycleOperation lifecycleOperation; - @Mock - private IUserAdminOperation userOperation; - @Mock - private IElementOperation elementOperation; - @Mock - private ArtifactCassandraDao artifactCassandraDao; - @Mock - public ToscaOperationFacade toscaOperationFacade; - @Mock - private UserBusinessLogic userBusinessLogic; - @Mock - private NodeTemplateOperation nodeTemplateOperation; - @Mock - private ArtifactsOperations artifactsOperations; - - // public static final InformationDeployedArtifactsBusinessLogic - // informationDeployedArtifactsBusinessLogic = - // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); - - public static final Resource resource = Mockito.mock(Resource.class); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - - private static List<ArtifactType> getAllTypes() { - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); - for (String artifactType : artifactTypesList) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return artifactTypes; - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); - - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); - when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); - - Either<User, ActionStatus> getUserResult = Either.left(USER); - - when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); - - Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); - when(elementOperation.getAllArtifactTypes()).thenReturn(getType); - - when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); - } - - @Test - public void testValidJson() { - ArtifactDefinition ad = createArtifactDef(); - - String jsonArtifact = ""; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - try { - jsonArtifact = mapper.writeValueAsString(ad); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); - assertEquals(ad, afterConvert); - } - - private ArtifactDefinition createArtifactDef() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1.yaml"); - ad.setArtifactLabel("label1"); - ad.setDescription("description"); - ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - return ad; - } - - @Test - public void testInvalidStringGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidNumberGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidGroupTypeWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidTimeoutWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testValidMibAritactsConfiguration() { - Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - } - - @Test - public void testDownloadServiceArtifactByNames() { - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); - esArtifactData.setDataAsArray(payload); - Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); - when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); - List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); - serviceList.add(service); - Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); - when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); - Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = - artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - assertTrue(downloadServiceArtifactByNamesRes.isLeft()); - assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); - } - - @Test - public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) - .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) - .build(); - - Resource component = new Resource(); - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); - assertTrue(heatEnvPlaceHolder.isLeft()); - assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); - } - - @Test - public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { - HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); - HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); - HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(heatParam1) - .addHeatParam(heatParam2) - .addHeatParam(heatParam3) - .build(); - - Resource component = new Resource(); - - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); - - assertTrue(heatEnvPlaceHolder.isLeft()); - ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); - List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); - assertEquals(listHeatParameters.size(), 3); - verifyHeatParam(listHeatParameters.get(0), heatParam1); - verifyHeatParam(listHeatParameters.get(1), heatParam2); - verifyHeatParam(listHeatParameters.get(2), heatParam3); - } - - private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { - assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); - assertNull(heatEnvParam.getCurrentValue()); - } + public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + private final static String RESOURCE_INSTANCE_NAME = "Service-111"; + private final static String INSTANCE_ID = "S-123-444-ghghghg"; + + private final static String ARTIFACT_NAME = "service-Myservice-template.yml"; + private final static String ARTIFACT_LABEL = "assettoscatemplate"; + private final static String ES_ARTIFACT_ID = "123123dfgdfgd0"; + private final static byte[] PAYLOAD = "some payload".getBytes(); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + private static ArtifactsBusinessLogic artifactBL; + @Mock + private ArtifactOperation artifactOperation; + @Mock + public ComponentsUtils componentsUtils; + @Mock + private IInterfaceLifecycleOperation lifecycleOperation; + @Mock + private IUserAdminOperation userOperation; + @Mock + private IElementOperation elementOperation; + @Mock + private ArtifactCassandraDao artifactCassandraDao; + @Mock + public ToscaOperationFacade toscaOperationFacade; + @Mock + private UserBusinessLogic userBusinessLogic; + @Mock + private NodeTemplateOperation nodeTemplateOperation; + @Mock + private ArtifactsOperations artifactsOperations; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + TitanDao titanDao; + + // public static final InformationDeployedArtifactsBusinessLogic + // informationDeployedArtifactsBusinessLogic = + // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); + + public static final Resource resource = Mockito.mock(Resource.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + + private static List<ArtifactType> getAllTypes() { + List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); + List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return artifactTypes; + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); + when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); + + Either<User, ActionStatus> getUserResult = Either.left(USER); + + when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); + + Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); + when(elementOperation.getAllArtifactTypes()).thenReturn(getType); + + when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = ""; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try { + jsonArtifact = mapper.writeValueAsString(ad); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); + assertEquals(ad, afterConvert); + } + + private ArtifactDefinition createArtifactDef() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1.yaml"); + ad.setArtifactLabel("label1"); + ad.setDescription("description"); + ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + return ad; + } + + @Test + public void testInvalidStringGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidNumberGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidGroupTypeWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidTimeoutWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testValidMibAritactsConfiguration() { + Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + } + + @Test + public void testDownloadServiceArtifactByNames() { + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); + + ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); + esArtifactData.setDataAsArray(payload); + Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); + when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); + List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); + serviceList.add(service); + Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); + when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); + Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = + artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + assertTrue(downloadServiceArtifactByNamesRes.isLeft()); + assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); + } + + @Test + public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) + .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) + .build(); + + Resource component = new Resource(); + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); + assertTrue(heatEnvPlaceHolder.isLeft()); + assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); + } + + @Test + public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { + HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); + HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); + HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(heatParam1) + .addHeatParam(heatParam2) + .addHeatParam(heatParam3) + .build(); + + Resource component = new Resource(); + + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); + + assertTrue(heatEnvPlaceHolder.isLeft()); + ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); + List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); + assertEquals(listHeatParameters.size(), 3); + verifyHeatParam(listHeatParameters.get(0), heatParam1); + verifyHeatParam(listHeatParameters.get(1), heatParam2); + verifyHeatParam(listHeatParameters.get(2), heatParam3); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, true); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndNotInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, false); + verify(titanDao, times(1)).commit(); + } + + private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { + assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); + assertNull(heatEnvParam.getCurrentValue()); + } // @Test - // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ - // ArtifactDefinition createArtifactDef = createArtifactDef(); - // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); - // - // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL - // - // assertTrue(validateResult.isLeft()); - // ArtifactDefinition validatedArtifact = validateResult.left().value(); - // - // assertEquals(createArtifactDef.getArtifactGroupType(), - // validatedArtifact.getArtifactGroupType()); - // assertEquals(new Integer(0), validatedArtifact.getTimeout()); - // assertFalse(validatedArtifact.getMandatory()); - // assertFalse(validatedArtifact.getServiceApi()); - // - // } + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL + // + // assertTrue(validateResult.isLeft()); + // ArtifactDefinition validatedArtifact = validateResult.left().value(); + // + // assertEquals(createArtifactDef.getArtifactGroupType(), + // validatedArtifact.getArtifactGroupType()); + // assertEquals(new Integer(0), validatedArtifact.getTimeout()); + // assertFalse(validatedArtifact.getMandatory()); + // assertFalse(validatedArtifact.getServiceApi()); + // + // } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java index 8ad9bf80b2..18af7a035a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.Collections; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,12 +28,21 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + public class ArtifactResolverTest { private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); - private Service service, noArtifactsService; - private Resource resource, noArtifactsResource; - private ComponentInstance componentInstance, noArtifactsInstance; + private Service service; + private Service noArtifactsService; + private Resource resource; + private Resource noArtifactsResource; + private ComponentInstance componentInstance; + private ComponentInstance noArtifactsInstance; @Before public void setUp() throws Exception { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java index 41835a6cdc..9b2fb3773b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -20,17 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,58 +36,68 @@ import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.common.util.CapabilityTypeNameEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class CapabilityTypeImportManagerTest { - @InjectMocks - private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + @InjectMocks + private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() { - when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { - public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() { + when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { + public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void testCreateCapabilityTypes() throws IOException { - String ymlContent = getCapabilityTypesYml(); - Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void testCreateCapabilityTypes() throws IOException { + String ymlContent = getCapabilityTypesYml(); + Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); - assertTrue(capabilityTypesList.size() == 14); - Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); - for (CapabilityTypeDefinition capType : capabilityTypesList) { - capibilityTypeMap.put(capType.getType(), capType); - } - assertTrue(capabilityTypesList.size() == 14); + List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); + assertTrue(capabilityTypesList.size() == 14); + Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); + for (CapabilityTypeDefinition capType : capabilityTypesList) { + capibilityTypeMap.put(capType.getType(), capType); + } + assertTrue(capabilityTypesList.size() == 14); - for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { - assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); - } + for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { + assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); + } - } + } - private String getCapabilityTypesYml() throws IOException { - Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getCapabilityTypesYml() throws IOException { + Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java index 2c83c60fc6..8a07e26161 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -45,64 +36,66 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; - -import fj.data.Either; - -public class CategoriesImportManagerTest { - @InjectMocks - static CategoriesImportManager importManager = new CategoriesImportManager(); - public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - static Logger log = Mockito.spy(Logger.class); - private static SubCategoryDefinition subcategory; - - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId("123"); - - when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { - Object[] args = invocation.getArguments(); - CategoryDefinition category = (CategoryDefinition) args[0]; - category.setUniqueId("123"); - Either<CategoryDefinition, ActionStatus> ans = Either.left(category); - return ans; - }); - when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { - public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); - Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); - return ans; - } - - }); - - // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void importCategoriesTest() throws IOException { - String ymlContent = getYmlContent(); - Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; - } +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } +public class CategoriesImportManagerTest { + @InjectMocks + static CategoriesImportManager importManager = new CategoriesImportManager(); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + private static SubCategoryDefinition subcategory; + + @BeforeClass + public static void beforeClass() throws IOException { + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId("123"); + + when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { + Object[] args = invocation.getArguments(); + CategoryDefinition category = (CategoryDefinition) args[0]; + category.setUniqueId("123"); + Either<CategoryDefinition, ActionStatus> ans = Either.left(category); + return ans; + }); + when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { + public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); + Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); + return ans; + } + + }); + + // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importCategoriesTest() throws IOException { + String ymlContent = getYmlContent(); + Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 65f7ac46b6..a5d05eff2c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -1,23 +1,22 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiPredicate; - +import fj.data.Either; import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; @@ -32,214 +31,354 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiPredicate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceBusinessLogic class */ public class ComponentInstanceBusinessLogicTest { - - private final static String USER_ID = "jh0003"; - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - private static ToscaOperationFacade toscaOperationFacade; - private static UserBusinessLogic userAdmin; - - private static ComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentInstanceBusinessLogic resourceBusinessLogic; - private static User user; - private static Component service; - private static Component resource; - private static ComponentInstance toInstance; - private static ComponentInstance fromInstance; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - @BeforeClass - public static void setup() { - createMocks(); - setMocks(); - stubMethods(); - createComponents(); - } - - @Test - public void testGetRelationByIdSuccess(){ - getServiceRelationByIdSuccess(service); - getServiceRelationByIdSuccess(resource); - } - - @Test - public void testGetRelationByIdUserValidationFailure(){ - getServiceRelationByIdUserValidationFailure(service); - getServiceRelationByIdUserValidationFailure(resource); - } - - @Test - public void testGetRelationByIdComponentNotFoundFailure(){ - getRelationByIdComponentNotFoundFailure(service); - getRelationByIdComponentNotFoundFailure(resource); - } - - @SuppressWarnings("unchecked") - private void getServiceRelationByIdSuccess(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); - when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); - - Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); - when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isLeft()); - } - - private void getServiceRelationByIdUserValidationFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private void getRelationByIdComponentNotFoundFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private static void createMocks() { - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - userAdmin = Mockito.mock(UserBusinessLogic.class); - user = Mockito.mock(User.class); - } - - private static void setMocks() { - serviceBusinessLogic = new ServiceComponentInstanceBusinessLogic(); - serviceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - serviceBusinessLogic.setUserAdmin(userAdmin); - serviceBusinessLogic.setComponentsUtils(componentsUtils); - - resourceBusinessLogic = new VFComponentInstanceBusinessLogic(); - resourceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - resourceBusinessLogic.setUserAdmin(userAdmin); - resourceBusinessLogic.setComponentsUtils(componentsUtils); - } - - private static void stubMethods() { - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); - } - - private static void createComponents() { - createRelation(); - createInstances(); - createService(); - createResource(); - } - - private static void createResource() { - resource = new Resource(); - resource.setUniqueId(COMPONENT_ID); - resource.setComponentInstancesRelations(Lists.newArrayList(relation)); - resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - resource.setCapabilities(toInstance.getCapabilities()); - resource.setRequirements(fromInstance.getRequirements()); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - } - - - private static void createService() { - service = new Service(); - service.setUniqueId(COMPONENT_ID); - service.setComponentInstancesRelations(Lists.newArrayList(relation)); - service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - service.setCapabilities(toInstance.getCapabilities()); - service.setRequirements(fromInstance.getRequirements()); - service.setComponentType(ComponentTypeEnum.SERVICE); - } - - - private static void createInstances() { - toInstance = new ComponentInstance(); - toInstance.setUniqueId(TO_INSTANCE_ID); - - fromInstance = new ComponentInstance(); - fromInstance.setUniqueId(FROM_INSTANCE_ID); - - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - - Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); - capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); - - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - - - Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); - requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); - - toInstance.setCapabilities(capabilities); - fromInstance.setRequirements(requirements); - } - - - private static void createRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } + + private final static String USER_ID = "jh0003"; + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + private static ToscaOperationFacade toscaOperationFacade; + private static UserBusinessLogic userAdmin; + + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ForwardingPathOperation forwardingPathOperation; + private static User user; + private static UserValidations userValidations; + private static Component service; + private static Component resource; + private static ComponentInstance toInstance; + private static ComponentInstance fromInstance; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + @BeforeClass + public static void setup() { + createMocks(); + setMocks(); + stubMethods(); + createComponents(); + + } + + @Before + public void init(){ + MockitoAnnotations.initMocks(this); + } + @Test + public void testGetRelationByIdSuccess(){ + getServiceRelationByIdSuccess(service); + getServiceRelationByIdSuccess(resource); + } + + @Test + public void testGetRelationByIdUserValidationFailure(){ + getServiceRelationByIdUserValidationFailure(service); + getServiceRelationByIdUserValidationFailure(resource); + } + + @Test + public void testGetRelationByIdComponentNotFoundFailure(){ + getRelationByIdComponentNotFoundFailure(service); + getRelationByIdComponentNotFoundFailure(resource); + } + + + + + @Test + public void testForwardingPathOnVersionChange(){ + getforwardingPathOnVersionChange(); + } + + private void getforwardingPathOnVersionChange(){ + String containerComponentParam="services"; + String containerComponentID="121-cont"; + String componentInstanceID="121-cont-1-comp"; + Service component=new Service(); + Map<String, ForwardingPathDataDefinition> forwardingPaths = generateForwardingPath(componentInstanceID); + + //Add existing componentInstance to component + List<ComponentInstance> componentInstanceList=new ArrayList<>(); + ComponentInstance oldComponentInstance=new ComponentInstance(); + oldComponentInstance.setName("OLD_COMP_INSTANCE"); + oldComponentInstance.setUniqueId(componentInstanceID); + oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,"1-comp"); + componentInstanceList.add(oldComponentInstance); + component.setComponentInstances(componentInstanceList); + component.setForwardingPaths(forwardingPaths); + + List<ComponentInstance> componentInstanceListNew=new ArrayList<>(); + ComponentInstance newComponentInstance=new ComponentInstance(); + String new_Comp_UID="2-comp"; + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,new_Comp_UID); + newComponentInstance.setUniqueId(new_Comp_UID); + componentInstanceListNew.add(newComponentInstance); + Component component2=new Service(); + component2.setComponentInstances(componentInstanceListNew); + + //Mock for getting component + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE)); + //Mock for getting component for componentInstance + when(toscaOperationFacade.getToscaFullElement(eq("1-comp"))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaFullElement(eq(new_Comp_UID))).thenReturn(Either.left(component2)); + + Either<Set<String>, ResponseFormat> resultOp = componentInstanceBusinessLogic.forwardingPathOnVersionChange + (containerComponentParam,containerComponentID,componentInstanceID,newComponentInstance); + Assert.assertEquals(1,resultOp.left().value().size()); + Assert.assertEquals("FP-ID-1",resultOp.left().value().iterator().next()); + + } + + + @Test + public void testDeleteForwardingPathsWhenComponentinstanceDeleted(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.left(new ComponentInstance())); + Assert.assertTrue(responseFormatEither.isLeft()); + + } + + @Test + public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.right(new ResponseFormat())); + Assert.assertTrue(responseFormatEither.isRight()); + + } + + + private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode , String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol("protocol"); + forwardingPath.setDestinationPortNumber("port"); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(fromNode, toNode, + "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } + + + + private Map<String, ForwardingPathDataDefinition> generateForwardingPath(String componentInstanceID) { + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + forwardingPath.setUniqueId("FP-ID-1"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = + new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY", + "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("1122", forwardingPath); + return forwardingPaths; + } + + @SuppressWarnings("unchecked") + private void getServiceRelationByIdSuccess(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); + when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); + + Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); + when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isLeft()); + } + + private void getServiceRelationByIdUserValidationFailure(Component component){ + //Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); + //when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.right(new ResponseFormat(404))); + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private void getRelationByIdComponentNotFoundFailure(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private static void createMocks() { + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + userAdmin = Mockito.mock(UserBusinessLogic.class); + user = Mockito.mock(User.class); + userValidations = Mockito.mock(UserValidations.class); + forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + } + + private static void setMocks() { + componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic(); + componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); + componentInstanceBusinessLogic.setUserAdmin(userAdmin); + componentInstanceBusinessLogic.setComponentsUtils(componentsUtils); + componentInstanceBusinessLogic.setUserValidations(userValidations); + componentInstanceBusinessLogic.setForwardingPathOperation(forwardingPathOperation); + } + + private static void stubMethods() { + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.left(user)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); + } + + private static void createComponents() { + createRelation(); + createInstances(); + createService(); + createResource(); + } + + private static void createResource() { + resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setComponentInstancesRelations(Lists.newArrayList(relation)); + resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + resource.setCapabilities(toInstance.getCapabilities()); + resource.setRequirements(fromInstance.getRequirements()); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + } + + + private static void createService() { + service = new Service(); + service.setUniqueId(COMPONENT_ID); + service.setComponentInstancesRelations(Lists.newArrayList(relation)); + service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + service.setCapabilities(toInstance.getCapabilities()); + service.setRequirements(fromInstance.getRequirements()); + service.setComponentType(ComponentTypeEnum.SERVICE); + } + + + private static void createInstances() { + toInstance = new ComponentInstance(); + toInstance.setUniqueId(TO_INSTANCE_ID); + + fromInstance = new ComponentInstance(); + fromInstance.setUniqueId(FROM_INSTANCE_ID); + + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); + + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + + + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); + + toInstance.setCapabilities(capabilities); + fromInstance.setRequirements(requirements); + } + + + private static void createRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java new file mode 100644 index 0000000000..a9245d2897 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java @@ -0,0 +1,402 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESC_ERROR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_500; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentsUtilsTest { + + private static User modifier = new User(); + private Component service = new Service(); + private Resource resource = new Resource(); + + @Mock + private AuditingManager manager; + + @Mock + private ResponseFormat responseFormat; + + @Captor + private ArgumentCaptor<AuditBaseEventFactory> factoryCaptor; + + @InjectMocks + private static ComponentsUtils utils; + + @BeforeClass + public static void setUpClass() { + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + @Before + public void setUp() { + ThreadLocalsHolder.setUuid(REQUEST_ID); + utils = new ComponentsUtils(manager); + } + + @Test + public void auditComponentWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + } + + @Test + public void auditComponentWhenAllParamsPassedAndMostFromComponent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + + } + + @Test + public void auditComponentDistStateWithoutArtDataCommentAndDid() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build()); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), + STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, false, false, true); + } + + @Test + public void auditComponentWhenError() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE, + ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(PREV_RESOURCE_STATE).version(PREV_RESOURCE_VERSION).artifactUuid(ARTIFACT_UUID).build()); + verifyResourceAdminEvent(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName(), STATUS_500, DESC_ERROR, + service.getComponentType().getValue(), false, true, false, false, false, false); + } + + @Test + public void auditComponentWhenCompIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE, + RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT); + verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + true, false, false, false, true, false); + } + + @Test + public void auditComponentAdmin() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setName(RESOURCE_NAME); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponentAdmin(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType()); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + resource.setToscaResourceName(TOSCA_NODE_TYPE); + utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .build(), + ARTIFACT_UUID, ARTIFACT_DATA); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(), + false, true, true, true, false, false); + } + + @Test + public void auditResourceWithoutPrevFields() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + utils.auditResource(responseFormat, modifier, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + verifyResourceAdminEvent(AuditingActionEnum.UPDATE_RESOURCE_METADATA.getName(), STATUS_500, DESC_ERROR, resource.getResourceType().name(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenResourceIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditResource(responseFormat, modifier, RESOURCE_NAME, AuditingActionEnum.CHECKOUT_RESOURCE); + verifyResourceAdminEvent(AuditingActionEnum.CHECKOUT_RESOURCE.getName(), STATUS_500, DESC_ERROR, ComponentTypeEnum.RESOURCE.getValue(), + true, false, false, false, false, false); + } + + @Test + public void auditUserAdminEvent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + User userAfter = new User(); + userAfter.setFirstName(USER_FIRST_NAME); + userAfter.setUserId(USER_ID); + userAfter.setLastName(USER_LAST_NAME); + userAfter.setRole(TESTER_USER_ROLE); + userAfter.setEmail(USER_EMAIL); + + utils.auditAdminUserAction(AuditingActionEnum.ADD_USER, modifier, null, userAfter, responseFormat); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + UserAdminEvent event = (UserAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.ADD_USER.getName()); + assertThat(event.getUserBefore()).isNull(); + assertThat(event.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + } + + @Test + public void auditEcompOpEnvEvent() { + utils.auditEnvironmentEngine(AuditingActionEnum.CREATE_ENVIRONMENT, OP_ENV_ID, OP_ENV_TYPE, OP_ENV_ACTION, OP_ENV_NAME, TENANT_CONTEXT); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + EcompOperationalEnvironmentEvent event = (EcompOperationalEnvironmentEvent)factory.getDbEvent(); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + assertThat(event.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(event.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(event.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(event.getOperationalEnvironmentAction()).isEqualTo(OP_ENV_ACTION); + assertThat(event.getTenantContext()).isEqualTo(TENANT_CONTEXT); + } + + @Test + public void auditDistrDownloadEvent(){ + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + utils.auditDistributionDownload(responseFormat, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + DistributionDownloadEvent event = (DistributionDownloadEvent)factory.getDbEvent(); + assertThat(event.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + } + + private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull, + boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided, + boolean isDistStatusProvided) { + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(status); + assertThat(event.getDesc()).isEqualTo(desc); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(action); + assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME); + + if (isComponentNull) { + assertThat(event.getServiceInstanceId()).isNull(); + assertThat(event.getCurrState()).isNull(); + assertThat(event.getCurrVersion()).isNull(); + assertThat(event.getInvariantUUID()).isNull(); + assertThat(event.getResourceType()).isEqualTo(resourceType); + } + else { + assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(event.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(event.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + } + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(event.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } + else { + assertThat(event.getToscaNodeType()).isEmpty(); + } + if (isPrevStateAndVersionSet) { + assertThat(event.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(event.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getPrevState()).isNull(); + assertThat(event.getPrevVersion()).isNull(); + assertThat(event.getPrevArtifactUUID()).isNull(); + } + if (isCurrFieldsProvided) { + assertThat(event.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getCurrArtifactUUID()).isNull(); + } + if (isArtDataProvided) { + assertThat(event.getArtifactData()).isEqualTo(ARTIFACT_DATA); + if (resourceType.equals(ResourceTypeEnum.VFC.name())) { + assertThat(event.getDid()).isNull(); + } + else { + assertThat(event.getDid()).isEqualTo(DIST_ID); + } + } + else { + assertThat(event.getArtifactData()).isNull(); + assertThat(event.getDid()).isNull(); + } + if (isCommentProvided) { + assertThat(event.getComment()).isEqualTo(COMMENT); + } + else { + assertThat(event.getComment()).isEmpty(); + } + if (isDistStatusProvided) { + assertThat(event.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(event.getDprevStatus()).isEqualTo(DPREV_STATUS); + } + else { + assertThat(event.getDcurrStatus()).isNull(); + assertThat(event.getDprevStatus()).isNull(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java index 4f1f929382..7b37b0e96a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -20,7 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; import java.util.ArrayList; import java.util.HashMap; @@ -29,126 +35,120 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; +import static org.junit.Assert.assertTrue; public class CompositionBusinessLogicTest { - CompositionBusinessLogic compBl = new CompositionBusinessLogic(); - - @Test - public void testBuildSpiralPatternPositioningForComponentInstances() { - int instancesNum = 10; - Resource createVF = FactoryUtils.createVF(); - for (int i = 0; i < instancesNum; i++) { - FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); - } - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); - assertTrue(componentInstances.size() == instancesNum); - // Verify Spiral Pattern - ImmutablePair<Double, Double> key; - key = new ImmutablePair<>(0D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-2D, -1D); - assertTrue(componentInstances.containsKey(key)); - } - - @Test - public void testGetCpsConnectedToVFC() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); - - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - assertTrue(cpsConnectedToVFC.size() == 1); - assertTrue(cpsConnectedToVFC.containsKey(vfc)); - Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); - assertTrue(cps.size() == 3); - cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); - - } - - @Test - public void testBuildCirclePatternForCps() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); - componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); - compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); - assertTrue(componentInstLocations.size() == 4); - - Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); - // Verify that all cps are located at different positions - assertTrue(cpsLocations.size() == 3); - Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); - // Verify that all cps are at the same distance from center - assertTrue(distances.size() == 1); - - } - - /** - * Adds 4 instances to the vf.<br> - * vfc instance and 3 cps instances.<br> - * the cp instances are connected to the vfc instance.<br> - * - * @param allComponentInstances - * @param createVF - * @return vfc instance - */ - private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { - ComponentInstance vfc = FactoryUtils.createResourceInstance(); - vfc.setOriginType(OriginTypeEnum.VFC); - FactoryUtils.addComponentInstanceToVF(createVF, vfc); - allComponentInstances.add(vfc); - - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - return vfc; - } - - private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { - List<RequirementCapabilityRelDef> allRelations; - if (createVF.getComponentInstancesRelations() != null) { - allRelations = createVF.getComponentInstancesRelations(); - } else { - allRelations = new ArrayList<>(); - createVF.setComponentInstancesRelations(allRelations); - } - ComponentInstance cp1 = FactoryUtils.createResourceInstance(); - cp1.setOriginType(OriginTypeEnum.CP); - addVfcCpRelation(vfc, cp1, allRelations); - FactoryUtils.addComponentInstanceToVF(createVF, cp1); - allComponentInstances.add(cp1); - } - - private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { - RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); - rel.setToNode(vfc.getComponentUid()); - rel.setFromNode(cp.getComponentUid()); - allRelations.add(rel); - } + CompositionBusinessLogic compBl = new CompositionBusinessLogic(); + + @Test + public void testBuildSpiralPatternPositioningForComponentInstances() { + int instancesNum = 10; + Resource createVF = FactoryUtils.createVF(); + for (int i = 0; i < instancesNum; i++) { + FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); + } + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); + assertTrue(componentInstances.size() == instancesNum); + // Verify Spiral Pattern + ImmutablePair<Double, Double> key; + key = new ImmutablePair<>(0D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-2D, -1D); + assertTrue(componentInstances.containsKey(key)); + } + + @Test + public void testGetCpsConnectedToVFC() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); + + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + assertTrue(cpsConnectedToVFC.size() == 1); + assertTrue(cpsConnectedToVFC.containsKey(vfc)); + Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); + assertTrue(cps.size() == 3); + cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); + + } + + @Test + public void testBuildCirclePatternForCps() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); + componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); + compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); + assertTrue(componentInstLocations.size() == 4); + + Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); + // Verify that all cps are located at different positions + assertTrue(cpsLocations.size() == 3); + Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); + // Verify that all cps are at the same distance from center + assertTrue(distances.size() == 1); + + } + + /** + * Adds 4 instances to the vf.<br> + * vfc instance and 3 cps instances.<br> + * the cp instances are connected to the vfc instance.<br> + * + * @param allComponentInstances + * @param createVF + * @return vfc instance + */ + private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { + ComponentInstance vfc = FactoryUtils.createResourceInstance(); + vfc.setOriginType(OriginTypeEnum.VFC); + FactoryUtils.addComponentInstanceToVF(createVF, vfc); + allComponentInstances.add(vfc); + + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + return vfc; + } + + private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { + List<RequirementCapabilityRelDef> allRelations; + if (createVF.getComponentInstancesRelations() != null) { + allRelations = createVF.getComponentInstancesRelations(); + } else { + allRelations = new ArrayList<>(); + createVF.setComponentInstancesRelations(allRelations); + } + ComponentInstance cp1 = FactoryUtils.createResourceInstance(); + cp1.setOriginType(OriginTypeEnum.CP); + addVfcCpRelation(vfc, cp1, allRelations); + FactoryUtils.addComponentInstanceToVF(createVF, cp1); + allComponentInstances.add(cp1); + } + + private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + rel.setToNode(vfc.getComponentUid()); + rel.setFromNode(cp.getComponentUid()); + allRelations.add(rel); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java index 50ad990560..d91fa7995b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -20,18 +20,18 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Arrays; - import org.junit.Assert; import org.junit.Test; +import java.util.Arrays; + public class CsarValidationUtilsTest { - private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; - private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; + private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; + private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; - @Test - public void testIsCsarPayloadName() { - Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); - Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); - } + @Test + public void testIsCsarPayloadName() { + Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); + Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java new file mode 100644 index 0000000000..46ee852aa0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 12/7/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class ElementBLTest { + + private static final String CATAGORY_NAME = "categoryName"; + private static final String CATEGORY_UNIQUE_ID = "catUniqueId"; + private static final String SERVICE_NOT_DELETED_ID = "notDeletedId"; + private static final String DELETED_SERVICE_ID = "deletedId"; + private List<CategoryData> categories = new ArrayList<>(); + private List<ImmutablePair<ServiceMetadataData, GraphEdge>> services = new ArrayList<>(); + private List<ImmutablePair<ResourceMetadataData, GraphEdge>> resources = new ArrayList<>(); + private Service notDeletedService = new Service(); + private Resource notDeletedResource = new Resource(); + + @Mock + private TitanGenericDao titanGenericDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private TitanDao titanDao; + + @InjectMocks + private ElementBusinessLogic elementBusinessLogic; + + @Before + public void setup() { + + initCategoriesList(); + initServicesList(); + initResourceslist(); + + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void initCategoriesList() { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setUniqueId(CATEGORY_UNIQUE_ID); + categories.add(categoryData); + } + + private void initServicesList() { + ServiceMetadataData serviceNotDeleted = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition1 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition1.setIsDeleted(false); + componentMetadataDataDefinition1.setHighestVersion(true); + componentMetadataDataDefinition1.setUniqueId(SERVICE_NOT_DELETED_ID); + serviceNotDeleted.setMetadataDataDefinition(componentMetadataDataDefinition1); + services.add(new ImmutablePair<>(serviceNotDeleted, null)); + + ServiceMetadataData deletedService = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition2 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition2.setIsDeleted(true); + componentMetadataDataDefinition2.setHighestVersion(true); + componentMetadataDataDefinition2.setUniqueId(DELETED_SERVICE_ID); + deletedService.setMetadataDataDefinition(componentMetadataDataDefinition2); + services.add(new ImmutablePair<>(deletedService, null)); + } + + private void initResourceslist() { + ResourceMetadataData notDeletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition3 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition3.setIsDeleted(false); + componentMetadataDataDefinition3.setHighestVersion(true); + componentMetadataDataDefinition3.setUniqueId(SERVICE_NOT_DELETED_ID); + notDeletedResource.setMetadataDataDefinition(componentMetadataDataDefinition3); + resources.add(new ImmutablePair<>(notDeletedResource, null)); + + ResourceMetadataData deletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition4 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition4.setIsDeleted(true); + componentMetadataDataDefinition4.setHighestVersion(true); + componentMetadataDataDefinition4.setUniqueId(DELETED_SERVICE_ID); + deletedResource.setMetadataDataDefinition(componentMetadataDataDefinition4); + resources.add(new ImmutablePair<>(deletedResource, null)); + } + + @Test + public void testFetchElementsByCategoryName_filterDeleted() { + ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class); + + when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) + .thenReturn(Either.left(categories)); + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class)) + .thenReturn(Either.left(services)); + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedService)); + + Either<List<Object>, StorageOperationStatus> elementsByCategoryEither = + elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), + NodeTypeEnum.Service, false, ServiceMetadataData.class, null); + + List<Object> elementsByCategory = elementsByCategoryEither.left().value(); + assertThat(elementsByCategory.get(0)).isSameAs(notDeletedService); + assertThat(elementsByCategory.size()).isEqualTo(1); + verifyCriteriaProperties(criteriaCapture); + } + + private void verifyCriteriaProperties(ArgumentCaptor<Map> propsCapture) { + Map<String, Object> props = propsCapture.getValue(); + assertThat(props.size()).isEqualTo(1); + assertThat(props.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty())).isEqualTo(ValidationUtils.normalizeCategoryName4Uniqueness(CATAGORY_NAME)); + } + + @Test + public void testFetchResourcesBySubcategoryUid_filterDeleted() { + + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)) + .thenReturn(Either.left(resources)); + + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedResource)); + + Either<List<Object>, StorageOperationStatus> resourcesBySubCategoryUidEither = elementBusinessLogic.fetchByCategoryOrSubCategoryUid(CATEGORY_UNIQUE_ID, NodeTypeEnum.ResourceSubcategory, + GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, false, ResourceMetadataData.class, null); + List<Object> resourcesBySubCategoryUid = resourcesBySubCategoryUidEither.left().value(); + assertThat(resourcesBySubCategoryUid.size()).isEqualTo(1); + assertThat(resourcesBySubCategoryUid.get(0)).isSameAs(notDeletedResource); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 5edf448cc2..b65e77c57f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -20,21 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; @@ -46,462 +32,475 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ImportUtilsTest { - @Test - public void testStringTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 4); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof String); - String value = (String) element; - assertTrue(value.equals("stringVal" + count)); - count++; - } - } - - @Test - public void testBooleanTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Boolean); - Boolean value = (Boolean) element; - if (count == 1 || count == 3) { - assertFalse(value); - } else if (count == 2) { - assertTrue(value); - } - - count++; - } - } - - @Test - public void testListTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof List); - - if (count == 1) { - verifyListElement1(element); - } else if (count == 2) { - verifyListElement2(element); - } - - else if (count == 3) { - verifyListElement3(element); - } - count++; - } - } - - @Test - public void testAllTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 5); - int count = 1; - for (Object element : list) { - if (count == 1) { - assertTrue(element instanceof String); - assertTrue(element.equals("tosca.nodes.Root")); - } else if (count == 2) { - assertTrue(element instanceof Map); - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); - Entry<String, Object> elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("mapTestTag")); - assertTrue(elementEntry.getValue().equals("string")); - - elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("required")); - assertTrue(elementEntry.getValue() instanceof Boolean); - assertTrue((Boolean) elementEntry.getValue()); - } - - else if (count == 3) { - assertTrue(element instanceof String); - assertTrue(element.equals("1 MB")); - } - - else if (count == 4) { - assertTrue(element instanceof List); - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - assertTrue(listElement.get(0) instanceof Map); - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("greater_or_equal")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal3")); - } else if (count == 5) { - assertTrue(element instanceof Boolean); - assertFalse((Boolean) element); - } - count++; - } - } - - @Test - public void testMapTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 2); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Map); - - if (count == 1) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("stringTestTag")); - assertTrue(inerElementEntry.getValue().equals("stringVal1")); - - inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("listTestTag")); - assertTrue(inerElementEntry.getValue() instanceof List); - List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); - - assertTrue(innerValue.size() == 3); - - } else if (count == 2) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("type")); - assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); - inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("allTestTag")); - assertTrue(inerElementEntry.getValue() instanceof Boolean); - } - - count++; - } - } - - @Test - public void testCreateFullHeatParameterModuleWithString() { - - testCreateFullHeatParameterModule("string", "default value"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithNumber() { - - testCreateFullHeatParameterModule("number", "777"); - testCreateFullHeatParameterModule("number", "777.23"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithBoolean() { - - testCreateFullHeatParameterModule("boolean", "true"); - testCreateFullHeatParameterModule("boolean", "on"); - testCreateFullHeatParameterModule("boolean", "n"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithList() { - - testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); - - } - - // @Test - // public void testCreateFullHeatParameterModuleWithInvalidType(){ - // - // String name = "fullParameter"; - // String description = "description_text"; - // - // Map<String, Object> parametersMap = new HashMap<String, Object>(); - // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", - // name, description); - // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), - // firstParam); - // - // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = - // ImportUtils.getHeatParameters(parametersMap); - // assertTrue(heatParameters.isRight()); - // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, - // heatParameters.right().value()); - // - // } - - @Test - public void testCreateFullHeatParameterModuleWithMissingType() { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isRight()); - assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); + @Test + public void testStringTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 4); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof String); + String value = (String) element; + assertTrue(value.equals("stringVal" + count)); + count++; + } + } + + @Test + public void testBooleanTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Boolean); + Boolean value = (Boolean) element; + if (count == 1 || count == 3) { + assertFalse(value); + } else if (count == 2) { + assertTrue(value); + } + + count++; + } + } + + @Test + public void testListTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof List); + + if (count == 1) { + verifyListElement1(element); + } else if (count == 2) { + verifyListElement2(element); + } + + else if (count == 3) { + verifyListElement3(element); + } + count++; + } + } + + @Test + public void testAllTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 5); + int count = 1; + for (Object element : list) { + if (count == 1) { + assertTrue(element instanceof String); + assertTrue(element.equals("tosca.nodes.Root")); + } else if (count == 2) { + assertTrue(element instanceof Map); + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); + Entry<String, Object> elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("mapTestTag")); + assertTrue(elementEntry.getValue().equals("string")); + + elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("required")); + assertTrue(elementEntry.getValue() instanceof Boolean); + assertTrue((Boolean) elementEntry.getValue()); + } + + else if (count == 3) { + assertTrue(element instanceof String); + assertTrue(element.equals("1 MB")); + } + + else if (count == 4) { + assertTrue(element instanceof List); + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + assertTrue(listElement.get(0) instanceof Map); + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("greater_or_equal")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal3")); + } else if (count == 5) { + assertTrue(element instanceof Boolean); + assertFalse((Boolean) element); + } + count++; + } + } + + @Test + public void testMapTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 2); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Map); + + if (count == 1) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("stringTestTag")); + assertTrue(inerElementEntry.getValue().equals("stringVal1")); + + inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("listTestTag")); + assertTrue(inerElementEntry.getValue() instanceof List); + List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); + + assertTrue(innerValue.size() == 3); + + } else if (count == 2) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("type")); + assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); + inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("allTestTag")); + assertTrue(inerElementEntry.getValue() instanceof Boolean); + } + + count++; + } + } + + @Test + public void testCreateFullHeatParameterModuleWithString() { + + testCreateFullHeatParameterModule("string", "default value"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithNumber() { + + testCreateFullHeatParameterModule("number", "777"); + testCreateFullHeatParameterModule("number", "777.23"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithBoolean() { + + testCreateFullHeatParameterModule("boolean", "true"); + testCreateFullHeatParameterModule("boolean", "on"); + testCreateFullHeatParameterModule("boolean", "n"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithList() { + + testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); + + } + + // @Test + // public void testCreateFullHeatParameterModuleWithInvalidType(){ + // + // String name = "fullParameter"; + // String description = "description_text"; + // + // Map<String, Object> parametersMap = new HashMap<String, Object>(); + // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", + // name, description); + // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), + // firstParam); + // + // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = + // ImportUtils.getHeatParameters(parametersMap); + // assertTrue(heatParameters.isRight()); + // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, + // heatParameters.right().value()); + // + // } + + @Test + public void testCreateFullHeatParameterModuleWithMissingType() { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isRight()); + assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); - } + } - @Test - public void testCreateFullHeatParameterModuleWithMissingFields() { + @Test + public void testCreateFullHeatParameterModuleWithMissingFields() { - String name = "fullParameter"; + String name = "fullParameter"; - Map<String, Object> parametersMap = new HashMap<String, Object>(); - String type = "number"; - String defValue = "defvalue"; - // default value cannot be empty in heat in case tag exists - Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + Map<String, Object> parametersMap = new HashMap<String, Object>(); + String type = "number"; + String defValue = "defvalue"; + // default value cannot be empty in heat in case tag exists + Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - assertParameter(parameterDefinition, name, type, null, defValue); + assertParameter(parameterDefinition, name, type, null, defValue); - } + } - @Test - public void testGetAttributesFromYml() throws IOException { + @Test + public void testGetAttributesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); - assertTrue(actualAttributes.isLeft()); - Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); - compareAttributes(expectedAttributes, actualAttributes.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + assertTrue(actualAttributes.isLeft()); + Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); + compareAttributes(expectedAttributes, actualAttributes.left().value()); - } + } - @Test - public void testGetPropertiesFromYml() throws IOException { + @Test + public void testGetPropertiesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); - assertTrue(actualProperties.isLeft()); - Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); - compareProperties(expectedProperties, actualProperties.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); + assertTrue(actualProperties.isLeft()); + Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); + compareProperties(expectedProperties, actualProperties.left().value()); - } + } - private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedAttribute; - PropertyDefinition actualAttribute, expectedAttributeModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { + Map<String, Object> singleExpectedAttribute; + PropertyDefinition actualAttribute, expectedAttributeModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { - singleExpectedAttribute = expectedAttribute.getValue(); - assertNotNull(singleExpectedAttribute); - actualAttribute = actual.get(expectedAttribute.getKey()); - assertNotNull(actualAttribute); - actualAttribute.setName(expectedAttribute.getKey().toString()); - expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); - expectedAttributeModel.setName(expectedAttribute.getKey().toString()); + singleExpectedAttribute = expectedAttribute.getValue(); + assertNotNull(singleExpectedAttribute); + actualAttribute = actual.get(expectedAttribute.getKey()); + assertNotNull(actualAttribute); + actualAttribute.setName(expectedAttribute.getKey().toString()); + expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); + expectedAttributeModel.setName(expectedAttribute.getKey().toString()); - assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); - assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); - assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); - assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); - assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); + assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); + assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); + assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); + assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); - compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); + compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); - } + } - } + } - private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedProperty; - PropertyDefinition actualProperty, expectedPropertyModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { + Map<String, Object> singleExpectedProperty; + PropertyDefinition actualProperty, expectedPropertyModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { - singleExpectedProperty = expectedProperty.getValue(); - assertNotNull(singleExpectedProperty); - actualProperty = actual.get(expectedProperty.getKey()); - assertNotNull(actualProperty); - actualProperty.setName(expectedProperty.getKey().toString()); - expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); - expectedPropertyModel.setName(expectedProperty.getKey().toString()); + singleExpectedProperty = expectedProperty.getValue(); + assertNotNull(singleExpectedProperty); + actualProperty = actual.get(expectedProperty.getKey()); + assertNotNull(actualProperty); + actualProperty.setName(expectedProperty.getKey().toString()); + expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); + expectedPropertyModel.setName(expectedProperty.getKey().toString()); - assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); - assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); - assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); - assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); - assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); + assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); + assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); + assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); + assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); + assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); - compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); - } + } - } + } - private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { + private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { - if (expected == null && actual == null) { - return; - } - PropertyDataDefinition actualPropertySchema = actual.getProperty(); - PropertyDataDefinition expectedPropertySchema = expected.getProperty(); - assertNotNull(actualPropertySchema); - assertNotNull(expectedPropertySchema); - assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); - assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); - - } + if (expected == null && actual == null) { + return; + } + PropertyDataDefinition actualPropertySchema = actual.getProperty(); + PropertyDataDefinition expectedPropertySchema = expected.getProperty(); + assertNotNull(actualPropertySchema); + assertNotNull(expectedPropertySchema); + assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); + assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); + + } - private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { - - Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); - assertTrue(toscaExpectedElements.isLeft()); - - return toscaExpectedElements.left().value(); - - } - - private void testCreateFullHeatParameterModule(String type, Object defaultVal) { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - - assertParameter(parameterDefinition, name, type, description, defaultVal); - - } - - private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { - Map<String, Object> firstParam = new HashMap<String, Object>(); - Map<String, Object> valuesMap = new HashMap<String, Object>(); - - valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); - valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); - valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); - - firstParam.put(name, valuesMap); - return firstParam; - } - - private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { - assertEquals(name, parameterDefinition.getName()); - assertEquals(description, parameterDefinition.getDescription()); - assertEquals(type, parameterDefinition.getType()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); - } - - private void verifyListElement3(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("type")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - private void verifyListElement2(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue() instanceof List); - } - - private void verifyListElement1(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 3); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("2 MB")); - - innerElement = (Map<String, String>) listElement.get(2); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - public static String loadFileNameToJsonString(String fileName) throws IOException { - String sourceDir = "src/test/resources/normativeTypes"; - java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); - byte[] fileContent = Files.readAllBytes(filePath); - String content = new String(fileContent); - return content; - } - - private static Object loadJsonFromFile(String fileName) throws IOException { - String content = loadFileNameToJsonString(fileName); - Object load = new Yaml().load(content); - return load; - } + private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { + + Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); + assertTrue(toscaExpectedElements.isLeft()); + + return toscaExpectedElements.left().value(); + + } + + private void testCreateFullHeatParameterModule(String type, Object defaultVal) { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, description, defaultVal); + + } + + private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { + Map<String, Object> firstParam = new HashMap<String, Object>(); + Map<String, Object> valuesMap = new HashMap<String, Object>(); + + valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); + valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); + valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); + + firstParam.put(name, valuesMap); + return firstParam; + } + + private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { + assertEquals(name, parameterDefinition.getName()); + assertEquals(description, parameterDefinition.getDescription()); + assertEquals(type, parameterDefinition.getType()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); + } + + private void verifyListElement3(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("type")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + private void verifyListElement2(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue() instanceof List); + } + + private void verifyListElement1(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 3); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("2 MB")); + + innerElement = (Map<String, String>) listElement.get(2); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + public static String loadFileNameToJsonString(String fileName) throws IOException { + String sourceDir = "src/test/resources/normativeTypes"; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static Object loadJsonFromFile(String fileName) throws IOException { + String content = loadFileNameToJsonString(fileName); + Object load = new Yaml().load(content); + return load; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index ac4d37ef76..068f04aae2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; @@ -46,7 +39,17 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class InputsBusinessLogicTest { @@ -63,6 +66,9 @@ public class InputsBusinessLogicTest { @Mock private ToscaOperationFacade toscaOperationFacadeMock; + @Mock + private UserValidations userValidations; + @InjectMocks private InputsBusinessLogic testInstance; @@ -83,13 +89,13 @@ public class InputsBusinessLogicTest { instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput)); instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput())); service.setComponentInstancesInputs(instanceInputMap); - - Mockito.when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); } @Test public void getComponentInstanceInputs_ComponentInstanceNotExist() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, "nonExisting"); assertTrue(componentInstanceInputs.isRight()); Mockito.verify(componentsUtilsMock).getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); @@ -115,13 +121,13 @@ public class InputsBusinessLogicTest { @Test public void getComponentInstanceInputs() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals("inputId", componentInstanceInputs.left().value().get(0).getInputId()); } private void getComponents_emptyInputs(Service service) { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals(Collections.emptyList(), componentInstanceInputs.left().value()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java index 8109e36be1..e726f608f5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -42,51 +34,54 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; -public class InterfaceLifecycleTypeImportManagerTest { +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - @InjectMocks - private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); +public class InterfaceLifecycleTypeImportManagerTest { - static Logger log = Mockito.spy(Logger.class); + @InjectMocks + private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { - public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() throws IOException { + when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { + public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void importLiecycleTest() throws IOException { - String ymlContent = getYmlContent(); - Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void importLiecycleTest() throws IOException { + String ymlContent = getYmlContent(); + Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - } + } - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java new file mode 100644 index 0000000000..9aca92010e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java @@ -0,0 +1,493 @@ +package org.openecomp.sdc.be.components.impl; + + +import fj.data.Either; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyBusinessLogicTest { + + @InjectMocks + private PolicyBusinessLogic businessLogic; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private UserValidations userValidations; + @Mock + private TitanDao titanDao; + @Mock + private ApplicationDataTypeCache dataTypeCache; + @Mock + private PropertyOperation propertyOperation; + + private final static String COMPONENT_ID = "componentId"; + private final static String COMPONENT_NAME = "componentName"; + private final static String POLICY_TYPE_NAME = "policyTypeName"; + private final static String POLICY_ID = "policyId"; + private final static String INVALID_POLICY_ID = "invalidPolicyId"; + private final static String POLICY_NAME = "policyName"; + private final static String OTHER_POLICY_NAME = "otherPolicyName"; + private final static String USER_ID = "jh0003"; + private final static String UNIQUE_ID_EXSISTS = "uniqueIdExists"; + private final static String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists"; + private final static String FAKE_TYPE = "fakeType"; + private final static String COMPONENT_INSTANCE_TYPE = "component_Instances"; + private final static String GROUP_TYPE = "GROUPS"; + + + + + private final String CREATE_POLICY = "create Policy"; + + private final static User user = buildUser(); + private final static PolicyDefinition policy = buildPolicy(POLICY_NAME); + private final static PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME); + private final static Resource resource = buildResource(); + private final static PolicyTypeDefinition policyType = buildPolicyType(); + + private static Either<User, ResponseFormat> userSuccessEither; + private static Either<Component, StorageOperationStatus> componentSuccessEither; + private static Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeSuccessEither; + private static Either<PolicyDefinition, StorageOperationStatus> policySuccessEither; + private static ResponseFormat notFoundResponse; + private static ResponseFormat invalidContentResponse; + private static ResponseFormat nameExistsResponse; + + @BeforeClass + public static void setup() { + String appConfigDir = "src/test/resources/config/catalog-be"; + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + createResponses(); + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + } + + private static void createResponses() { + userSuccessEither = Either.left(user); + componentSuccessEither = Either.left(resource); + getPolicyTypeSuccessEither = Either.left(policyType); + policySuccessEither = Either.left(policy); + notFoundResponse = new ResponseFormat(); + notFoundResponse.setStatus(404); + invalidContentResponse = new ResponseFormat(); + invalidContentResponse.setStatus(400); + nameExistsResponse = new ResponseFormat(); + nameExistsResponse.setStatus(409); + } + + @Test + public void createPolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void createPolicyUserFailureTest(){ + Either<User, ResponseFormat> userNotFoundResponse = Either.right(new ResponseFormat(404)); + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userNotFoundResponse); + stubRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + private void assertNotFound(Either<PolicyDefinition, ResponseFormat> response) { + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void createPolicyComponentFailureTest(){ + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither); + Either<Component, StorageOperationStatus> componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND); + when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(ComponentTypeEnum.RESOURCE))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyPolicyTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeFailed); + when(componentsUtils.convertFromStorageResponse(eq(getPolicyTypeFailed.right().value()))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyComponentTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + Either<PolicyDefinition, StorageOperationStatus> addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes); + when(componentsUtils.convertFromStorageResponse(eq(addPolicyRes.right().value()))).thenReturn(ActionStatus.INVALID_CONTENT); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_CONTENT))).thenReturn(invalidContentResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(400)); + } + + @Test + public void updatePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyNameFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NAME_ALREADY_EXIST), eq(POLICY_NAME))).thenReturn(nameExistsResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(409)); + } + + @Test + public void getPolicySuccessTest(){ + stubValidationSuccess(CREATE_POLICY); + stubCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID); + assertTrue(response.isLeft()); + } + + @Test + public void getPolicyFailureTest(){ + stubValidationSuccess(CREATE_POLICY); + stubRollback(); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), eq(INVALID_POLICY_ID), eq(COMPONENT_ID))).thenReturn(notFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void deletePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + when(toscaOperationFacade.removePolicyFromComponent(eq(COMPONENT_ID),eq(POLICY_ID))).thenReturn(StorageOperationStatus.OK); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void deletePolicyFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true); + assertNotFound(response); + } + + private void stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), anyString(), anyString())).thenReturn(new ResponseFormat(404)); + } + + @Test + public void updatePolicyPropertiesSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + String prop1 = "Name"; + String prop2 = "Type"; + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1)); + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2)); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + PropertyDataDefinition[] properties = getProperties(prop1, prop2); + policy.setProperties(Arrays.asList(properties)); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties , USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyTargetsSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubGetToscaElementSuccess(); + stubGetTargetType(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID); + + Assert.assertTrue(result.isLeft()); + PolicyDefinition policyResult = result.left().value(); + Map<PolicyTargetType, List<String>> targets = getTargets(); + assertThat(policyResult.getTargets().values()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES)); + + } + + private void stubGetTargetType() { + } + + @Test + public void updatePolicyTargetsTargetIDFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeId(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertEquals(responseResult.getStatus().longValue(), 400L); + + } + + private void stubComponentUtilsGetResponseTargetNotFound() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST), (anyString()))).thenReturn(new ResponseFormat(400)); + } + + @Test + public void updatePolicyTargetsTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeType(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertTrue(responseResult.getStatus().equals(400)); + + } + + private void stubUpdatePolicyOfComponentSuccess() { + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy))).thenReturn(policySuccessEither); + } + + + @Test + public void updatePolicyPropertiesFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.PROPERTY_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + policy.setProperties(null); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getProperties("Name", "Type") , USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + private PropertyDataDefinition[] getProperties(String prop1, String prop2) { + PropertyDataDefinition property1 = new PropertyDataDefinition(); + property1.setName(prop1); + property1.setValue(prop1); + PropertyDataDefinition property2 = new PropertyDataDefinition(); + property2.setName(prop2); + property2.setValue(prop2); + PropertyDataDefinition[] properties = {property1, property2}; + return properties; + } + + + private void stubUnlockAndRollback() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubRollback(); + } + + private void stubCommit() { + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void stubRollback() { + when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + } + + private void stubUnlockAndCommit() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubCommit(); + } + + private void stubValidateAndLockSuccess(String methodName) { + stubValidationSuccess(methodName); + when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + } + + private void stubValidationSuccess(String methodName) { + when(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(userSuccessEither); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither); + } + + private void stubGetToscaFullElementSuccess() { + when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(buildElementEither()); + } + + private void stubGetToscaElementSuccess() { + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID))).thenReturn(componentSuccessEither); + } + + private Either<Component, StorageOperationStatus> buildElementEither() { + ResourceBuilder builder = new ResourceBuilder(); + GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build(); + ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder(); + ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build(); + return Either.left(builder.addGroups(groupDefinition).addComponentInstance(componentInstance).build()); + } + + private Map<PolicyTargetType, List<String>> getTargets() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + + + private static PolicyTypeDefinition buildPolicyType() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + policyType.setType(POLICY_TYPE_NAME); + return policyType; + } + + private static PolicyDefinition buildPolicy(String policyName) { + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + policy.setPolicyTypeName(POLICY_TYPE_NAME); + policy.setComponentName(COMPONENT_NAME); + policy.setName(policyName); + return policy; + } + + private static Resource buildResource() { + Resource resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setName(COMPONENT_NAME); + resource.setCreatorUserId(USER_ID); + resource.setLastUpdaterUserId(USER_ID); + resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setResourceType(ResourceTypeEnum.VF); + resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); + Map<String, PolicyDefinition> policies = new HashMap<>(); + policies.put(POLICY_ID, policy); + resource.setPolicies(policies); + return resource; + } + + private static User buildUser() { + User user = new User(); + user.setUserId(USER_ID); + return user; + } + private List<PolicyTargetDTO> getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType("componentInstances"); + + return Arrays.asList(target1, target2); + } + + private List<PolicyTargetDTO> getFakeIDTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target1.setType(GROUP_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target2.setType(COMPONENT_INSTANCE_TYPE); + + return Arrays.asList(target1, target2); + } + private List<PolicyTargetDTO> getFakeTypeTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType(FAKE_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType(FAKE_TYPE); + + return Arrays.asList(target1, target2); + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeType() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeId() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + return targets; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java new file mode 100644 index 0000000000..ad3e6e8974 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java @@ -0,0 +1,148 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.core.Response; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyPropertiesBusinessLogicTest { + + private static final String POLICY_ID = "policy1"; + private static final String RESOURCE_ID = "resourceId"; + private static final String USER_ID = "userId"; + public static final String NO_PROPS_POLICY = "policy2"; + @InjectMocks + private PolicyBusinessLogic testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private TitanDao titanDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private ComponentsUtils componentsUtils; + + private ComponentParametersView componentFilter; + private Resource resource; + private PropertyDefinition prop1, prop2; + + @Before + public void setUp() throws Exception { + componentFilter = new ComponentParametersView(true); + componentFilter.setIgnorePolicies(false); + componentFilter.setIgnoreUsers(false); + + prop1 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + prop2 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + + PolicyDefinition policy1 = PolicyDefinitionBuilder.create() + .setUniqueId(POLICY_ID) + .setProperties(prop1, prop2) + .build(); + + PolicyDefinition policy2 = PolicyDefinitionBuilder.create() + .setUniqueId(NO_PROPS_POLICY) + .build(); + resource = new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) + .setLastUpdaterUserId(USER_ID) + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + @After + public void tearDown() { + verify(titanDao).commit(); + } + + @Test + public void getPolicyProperties_userIdIsNull() { + String userId = null; + ResponseFormat forbiddenResponse = new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()); + when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenReturn(Either.right(forbiddenResponse)); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null); + assertThat(policyProperties.right().value()).isSameAs(forbiddenResponse); + } + + @Test + public void getPolicyProperties_componentNotFound() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.right().value()).isSameAs(notFoundResponse); + } + + @Test + public void getPolicyProperties_policyNotExist() { + doPolicyValidations(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, "nonExistingPolicy", RESOURCE_ID)).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, "nonExistingPolicy", USER_ID); + assertThat(policyProperties.right().value()).isEqualTo(notFoundResponse); + } + + @Test + public void getPolicyProperties_noPropertiesOnPolicy() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, NO_PROPS_POLICY, USER_ID); + assertThat(policyProperties.left().value()).isNull(); + } + + @Test + public void getPolicyProperties() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.left().value()) + .usingElementComparatorOnFields("uniqueId") + .containsExactly(prop1, prop2); + } + + private void doPolicyValidations() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.left(resource)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java new file mode 100644 index 0000000000..7dc12d96e6 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.impl; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTypeBusinessLogicTest { + + private static final String USER_ID = "userId"; + private static final Set<String> EXCLUDED_POLICY_TYPES = newHashSet("type1", "type2"); + private static final String COMPONENT_TYPE = "VF"; + + @InjectMocks + private PolicyTypeBusinessLogic testInstance; + @Mock + private TitanDao titanDao; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private UserValidations userValidations; + + @Before + public void setUp() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.left(new User())); + when(componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(any(StorageOperationStatus.class))).thenCallRealMethod(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES)); + } + + @BeforeClass + public static void beforeClass() { + new DummyConfigurationManager(); + } + + @Test + public void getAllPolicyTypes_userNotExist() { + ResponseFormat userNotExistResponse = new ResponseFormat(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.right(userNotExistResponse)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(userNotExistResponse); + } + + @Test + public void getAllPolicyTypes_whenExcludePolicyTypesSetIsNull_passNullExcludedTypesSet() { + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenCallRealMethod(); + when(policyTypeOperation.getAllPolicyTypes(null)).thenReturn(Either.left(emptyList())); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + } + + @Test + public void getAllPolicyTypes() { + List<PolicyTypeDefinition> policyTypes = Arrays.asList(new PolicyTypeBuilder().setUniqueId("id1").build(), + new PolicyTypeBuilder().setUniqueId("id2").build(), + new PolicyTypeBuilder().setUniqueId("id3").build()); + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.left(policyTypes)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isSameAs(policyTypes); + } + + @Test + public void getAllPolicyTypes_noPolicyTypes() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + verify(titanDao).commit(); + } + + @Test + public void getAllPolicyTypes_err() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + ResponseFormat errResponse = new ResponseFormat(); + when(componentsUtils.getResponseFormat(StorageOperationStatus.GENERAL_ERROR)).thenReturn(errResponse); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(errResponse); + verify(titanDao).commit(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index f7724aaeff..8054baf15f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -20,22 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; @@ -44,13 +29,13 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -98,1635 +83,1738 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class ResourceBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName()); - public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; - public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; - public static final String RESOURCE_SUBCATEGORY = "Router"; + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class); + public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; + public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; + public static final String RESOURCE_SUBCATEGORY = "Router"; - public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; - public static final String UPDATED_SUBCATEGORY = "Gateway"; + public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; + public static final String UPDATED_SUBCATEGORY = "Gateway"; - public static final String RESOURCE_NAME = "My-Resource_Name with space"; + public static final String RESOURCE_NAME = "My-Resource_Name with space"; private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF"; + private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR"; private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC"; private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF"; - - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - IElementOperation mockElementDao; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); - NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); - TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); - final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); - final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); - final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); - final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - ResponseFormatManager responseManager = null; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - User user = null; - Resource resourceResponse = null; - Resource genericVF = null; - Resource genericVFC = null; - Resource genericPNF = null; - ComponentsUtils componentsUtils = new ComponentsUtils(); - ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); - CsarOperation csarOperation = Mockito.mock(CsarOperation.class); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - - - public ResourceBusinessLogicTest() { - - } - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - Mockito.reset(propertyOperation); - - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - - Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); - Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); - - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); - - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - - // createResource - resourceResponse = createResourceObject(true); - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); - Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - - // BL object - artifactManager.nodeTemplateOperation = nodeTemplateOperation; - bl = new ResourceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setCapabilityTypeOperation(capabilityTypeOperation); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setLifecycleManager(lifecycleBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setArtifactsManager(artifactManager); - bl.setPropertyOperation(propertyOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setApplicationDataTypeCache(applicationDataTypeCache); - bl.setCsarOperation(csarOperation); - bl.setCacheManagerOperation(cacheManager); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); - toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); - bl.setToscaOperationFacade(toscaOperationFacade); - Resource resourceCsar = createResourceObjectCsar(true); - setCanWorkOnResource(resourceCsar); - Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); - when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); - responseManager = ResponseFormatManager.getInstance(); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource createResourceObjectCsar(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setResourceVendorModelNumber(""); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - resource.setCsarUUID("valid_vf.csar"); - resource.setCsarVersion("1"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource setCanWorkOnResource(Resource resource) { - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setLastUpdaterUserId(user.getUserId()); - return resource; - } - - @Test - public void testHappyScenario() { - Resource resource = createResourceObject(false); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEquals(createResourceObject(true), createResponse.left().value()); - } - - @Test - public void testUpdateHappyScenario() { - Resource resource = createResourceObjectCsar(true); - setCanWorkOnResource(resource); - - Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); - when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); - if (updateResponse.isRight()) { - assertEquals(new Integer(200), updateResponse.right().value().getStatus()); - } - assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); - } - - /* CREATE validations - start ***********************/ - // Resource name - start - - @Test - public void testFailedResourceValidations() { - testResourceNameExist(); - testResourceNameEmpty(); - // testResourceNameExceedsLimit(); - testResourceNameWrongFormat(); - testResourceDescExceedsLimitCreate(); - testResourceDescNotEnglish(); - testResourceDescriptionEmpty(); - testResourceDescriptionMissing(); - testResourceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - testResourceTagNotExist(); - testResourceTagEmpty(); - testTagsExceedsLimitCreate(); - testTagsNoServiceName(); - testInvalidTag(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testResourceContactIdEmpty(); - testResourceContactIdMissing(); - testVendorNameExceedsLimit(); - testVendorNameWrongFormatCreate(); - testVendorReleaseWrongFormat(); - testVendorReleaseExceedsLimitCreate(); - testResourceVendorModelNumberExceedsLimit(); - testResourceVendorNameMissing(); - testResourceVendorReleaseMissing(); - testResourceCategoryExist(); - testResourceBadCategoryCreate(); - testHappyScenarioCostLicenseType(); - testCostWrongFormatCreate(); - testLicenseTypeWrongFormatCreate(); - testResourceTemplateNotExist(); - testResourceTemplateEmpty(); - testResourceTemplateInvalid(); - } - - private void testResourceNameExist() { - String resourceName = "alreadyExists"; - Resource resourceExist = createResourceObject(false); - resourceExist.setName(resourceName); - resourceExist.getTags().add(resourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - private void testResourceNameEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceNameExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - resourceExccedsNameLimit.setName(tooLongResourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testResourceNameWrongFormat() { - Resource resource = createResourceObject(false); - // contains : - String nameWrongFormat = "ljg?fd"; - resource.setName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Resource name - end - // Resource description - start - private void testResourceDescExceedsLimitCreate() { - Resource resourceExccedsDescLimit = createResourceObject(false); - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - resourceExccedsDescLimit.setDescription(tooLongResourceDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testResourceDescNotEnglish() { - Resource notEnglish = createResourceObject(false); - // Not english - String notEnglishDesc = "\uC2B5"; - notEnglish.setDescription(notEnglishDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - // Resource description - end - // Resource icon start - - private void testResourceIconMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconInvalid() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Resource icon end - // Resource tags - start - private void testResourceTagNotExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testResourceTagEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testTagsExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resourceExccedsNameLimit.getName()); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; - String tag2 = resourceExccedsNameLimit.getName(); - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb%#%"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); - - } - - // Resource tags - stop - // Resource contact start - - private void testContactIdTooLong() { - Resource resourceContactId = createResourceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - resourceContactId.setContactId(contactIdTooLong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Resource resourceContactId = createResourceObject(false); - // 3 letters and 3 digits and special characters - String contactIdFormatWrong = "yrt134!!!"; - resourceContactId.setContactId(contactIdFormatWrong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testVendorNameExceedsLimit() { - Resource resourceExccedsVendorNameLimit = createResourceObject(false); - String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - } - - private void testResourceVendorModelNumberExceedsLimit() { - Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); - String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - } - - private void testVendorNameWrongFormatCreate() { - Resource resource = createResourceObject(false); - // contains * - String nameWrongFormat = "ljg*fd"; - resource.setVendorName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - } - - private void testVendorReleaseWrongFormat() { - Resource resource = createResourceObject(false); - // contains > - String nameWrongFormat = "1>2"; - resource.setVendorRelease(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); - - } - - private void testVendorReleaseExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - private void testResourceVendorNameMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); - } - - private void testResourceVendorReleaseMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorRelease(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); - } - - // Resource vendor name/release stop - // Category start - private void testResourceCategoryExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceBadCategoryCreate() { - - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - resourceExist.addCategory("koko", "koko"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Category stop - // Cost start - private void testHappyScenarioCostLicenseType() { - Resource createResourceObject = createResourceObject(false); - Resource createResourceObjectAfterCreate = createResourceObject(true); - // Adding cost and licenseType to basic mock - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - - String cost = "123.456"; - String licenseType = "User"; - createResourceObject.setCost(cost); - createResourceObject.setLicenseType(licenseType); - Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - createResourceObjectAfterCreate.setCost(cost); - createResourceObjectAfterCreate.setLicenseType(licenseType); - assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); - } - - private void testCostWrongFormatCreate() { - Resource resourceCost = createResourceObject(false); - // Comma instead of fullstop - String cost = "12356,464"; - resourceCost.setCost(cost); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // Cost stop - // License type start - private void testLicenseTypeWrongFormatCreate() { - Resource resourceLicenseType = createResourceObject(false); - // lowcase - String licenseType = "cpu"; - resourceLicenseType.setLicenseType(licenseType); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // License type stop - // Derived from start - private void testResourceTemplateNotExist() { - Resource resourceExist = createResourceObject(false); - List<String> list = null; - resourceExist.setDerivedFrom(list); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDerivedFrom(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateInvalid() { - Resource resourceExist = createResourceObject(false); - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - resourceExist.setDerivedFrom(derivedFrom); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - // Derived from stop - - private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - // UPDATE tests - start - // Resource name - @Test - public void testResourceNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setName(nameWrongFormat); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testResourceNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String name = "ljg"; - updatedResource.setName(name); - resource.setVersion("1.0"); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - - } - - @Ignore - public void testResourceNameExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - updatedResource.setName(tooLongResourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - @Test - public void testResourceNameAlreadyExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceName = "alreadyExists"; - updatedResource.setName(resourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - // - - @Test - public void testResourceDescExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - updatedResource.setDescription(tooLongResourceDesc); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - - } - - @Test - public void testIconWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains . - String icon = "icon.jpg"; - updatedResource.setIcon(icon); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testIconAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains - String icon = "icon"; - updatedResource.setIcon(icon); - - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - - } - - @Test - public void testTagsExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resource.getName()); - - updatedResource.setTags(tagsList); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - } - - @Test - public void testVendorNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - - } - - @Test - public void testVendorNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - - } - - @Test - public void testVendorReleaseExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // 129 chars, the limit is 128 - String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; - updatedResource.setVendorRelease(tooLongVendorRelease); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - @Ignore - public void testContactIdWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - // 3 letters and 3 digits - String contactIdTooLong = "yrt134"; - updatedResource.setContactId(contactIdTooLong); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceBadCategory_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - String badCategory = "ddfds"; - updatedResource.setCategories(null); - updatedResource.addCategory(badCategory, "fikt"); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceCategoryAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - updatedResource.setCategories(null); - updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - } - - // Derived from start - @Test - public void testResourceTemplateNotExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - String resourceId = resource.getUniqueId(); - - List<String> list = null; - updatedResource.setDerivedFrom(list); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateEmpty_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - updatedResource.setDerivedFrom(new ArrayList<String>()); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateInvalid_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - - @Test - public void testResourceTemplateCertify_UPDATE_HAPPY() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); - - Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); - when(propertyOperation.deleteAllPropertiesAssociatedToNode(Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isLeft()); - } - - @Test - public void testResourceTemplateCertify_UPDATE_SAD() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) - .thenReturn(isToscaNameExtending); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, - false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - } - // Derived from stop - - @Test - public void createOrUpdateResourceAlreadyCheckout() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - createResponse.left().value().setLastUpdaterUserId(user.getUserId()); - assertTrue(createResponse.isLeft()); - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceCertified() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - assertTrue(createResponse.isLeft()); - Resource certifiedResource = createResponse.left().value(); - certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - certifiedResource.setVersion("1.0"); - - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceNotExist() { - Resource resourceToUpdtae = createResourceObject(false); - - Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); - - Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { - Resource basic = createResourceObject(true); - - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); - when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - @Test - public void testValidatePropertiesDefaultValues_FailedWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1.5"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IElementOperation mockElementDao; + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); + NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); + TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); + final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); + final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + ResponseFormatManager responseManager = null; + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + User user = null; + Resource resourceResponse = null; + Resource genericVF = null; + Resource genericCR = null; + Resource genericVFC = null; + Resource genericPNF = null; + ComponentsUtils componentsUtils; + ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + + public ResourceBusinessLogicTest() { + + } + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); + + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); + Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); + + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); + + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount); + /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/ + + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + + // createResource + resourceResponse = createResourceObject(true); + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); + Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + artifactManager.setNodeTemplateOperation(nodeTemplateOperation); + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setCapabilityTypeOperation(capabilityTypeOperation); + bl.setComponentsUtils(componentsUtils); + bl.setLifecycleManager(lifecycleBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setArtifactsManager(artifactManager); + bl.setPropertyOperation(propertyOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setApplicationDataTypeCache(applicationDataTypeCache); + bl.setCsarOperation(csarOperation); + bl.setCacheManagerOperation(cacheManager); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); + toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setUserValidations(userValidations); + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); + when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + responseManager = ResponseFormatManager.getInstance(); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource createResourceObjectCsar(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setResourceVendorModelNumber(""); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + resource.setCsarUUID("valid_vf.csar"); + resource.setCsarVersion("1"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); + return resource; + } + + @Test + public void testHappyScenario() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createResourceObject(false); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEquals(createResourceObject(true), createResponse.left().value()); + } + + @Test + public void testUpdateHappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + if (updateResponse.isRight()) { + assertEquals(new Integer(200), updateResponse.right().value().getStatus()); + } + assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); + } + + /* CREATE validations - start ***********************/ + // Resource name - start + + @Test + public void testFailedResourceValidations() { + testResourceNameExist(); + testResourceNameEmpty(); + // testResourceNameExceedsLimit(); + testResourceNameWrongFormat(); + testResourceDescExceedsLimitCreate(); + testResourceDescNotEnglish(); + testResourceDescriptionEmpty(); + testResourceDescriptionMissing(); + testResourceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + testResourceTagNotExist(); + testResourceTagEmpty(); + testTagsExceedsLimitCreate(); + testTagsNoServiceName(); + testInvalidTag(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + testResourceVendorModelNumberExceedsLimit(); + testResourceVendorNameMissing(); + testResourceVendorReleaseMissing(); + testResourceCategoryExist(); + testResourceBadCategoryCreate(); + testHappyScenarioCostLicenseType(); + testCostWrongFormatCreate(); + testLicenseTypeWrongFormatCreate(); + testResourceTemplateNotExist(); + testResourceTemplateEmpty(); + testResourceTemplateInvalid(); + } + + private void testResourceNameExist() { + String resourceName = "alreadyExists"; + Resource resourceExist = createResourceObject(false); + resourceExist.setName(resourceName); + resourceExist.getTags().add(resourceName); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + private void testResourceNameEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceNameExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + resourceExccedsNameLimit.setName(tooLongResourceName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testResourceNameWrongFormat() { + Resource resource = createResourceObject(false); + // contains : + String nameWrongFormat = "ljg?fd"; + resource.setName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Resource name - end + // Resource description - start + private void testResourceDescExceedsLimitCreate() { + Resource resourceExccedsDescLimit = createResourceObject(false); + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + resourceExccedsDescLimit.setDescription(tooLongResourceDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testResourceDescNotEnglish() { + Resource notEnglish = createResourceObject(false); + // Not english + String notEnglishDesc = "\uC2B5"; + notEnglish.setDescription(notEnglishDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + // Resource description - end + // Resource icon start + + private void testResourceIconMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconInvalid() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Resource icon end + // Resource tags - start + private void testResourceTagNotExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testResourceTagEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testTagsExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resourceExccedsNameLimit.getName()); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; + String tag2 = resourceExccedsNameLimit.getName(); + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb%#%"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"}); + + } + + // Resource tags - stop + // Resource contact start + + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + resourceContactId.setContactId(contactIdTooLong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Resource resourceContactId = createResourceObject(false); + // 3 letters and 3 digits and special characters + String contactIdFormatWrong = "yrt134!!!"; + resourceContactId.setContactId(contactIdFormatWrong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testResourceVendorModelNumberExceedsLimit() { + Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); + String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + } + + private void testVendorReleaseWrongFormat() { + Resource resource = createResourceObject(false); + // contains > + String nameWrongFormat = "1>2"; + resource.setVendorRelease(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); + + } + + private void testVendorReleaseExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + private void testResourceVendorNameMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); + } + + private void testResourceVendorReleaseMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorRelease(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); + } + + // Resource vendor name/release stop + // Category start + private void testResourceCategoryExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceBadCategoryCreate() { + + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + resourceExist.addCategory("koko", "koko"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Category stop + // Cost start + private void testHappyScenarioCostLicenseType() { + Resource createResourceObject = createResourceObject(false); + Resource createResourceObjectAfterCreate = createResourceObject(true); + // Adding cost and licenseType to basic mock + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + createResourceObjectAfterCreate.setCost(cost); + createResourceObjectAfterCreate.setLicenseType(licenseType); + assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); + } + + private void testCostWrongFormatCreate() { + Resource resourceCost = createResourceObject(false); + // Comma instead of fullstop + String cost = "12356,464"; + resourceCost.setCost(cost); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // Cost stop + // License type start + private void testLicenseTypeWrongFormatCreate() { + Resource resourceLicenseType = createResourceObject(false); + // lowcase + String licenseType = "cpu"; + resourceLicenseType.setLicenseType(licenseType); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // License type stop + // Derived from start + private void testResourceTemplateNotExist() { + Resource resourceExist = createResourceObject(false); + List<String> list = null; + resourceExist.setDerivedFrom(list); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDerivedFrom(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateInvalid() { + Resource resourceExist = createResourceObject(false); + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + resourceExist.setDerivedFrom(derivedFrom); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + // Derived from stop + + private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + // UPDATE tests - start + // Resource name + @Test + public void testResourceNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testResourceNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + @Test + public void testResourceNameAlreadyExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + // + + @Test + public void testResourceDescExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + + } + + @Test + public void testIconWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testIconAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + + } + + @Test + public void testTagsExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resource.getName()); + + updatedResource.setTags(tagsList); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + } + + @Test + public void testVendorNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorNameWrongFormat() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorReleaseExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + @Ignore + public void testContactIdWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + updatedResource.setContactId(contactIdTooLong); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceBadCategory_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceCategoryAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + } + + // Derived from start + @Test + public void testResourceTemplateNotExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List<String> list = null; + updatedResource.setDerivedFrom(list); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateEmpty_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList<String>()); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateInvalid_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + + @Test + public void testResourceTemplateCertify_UPDATE_HAPPY() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); + + Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); + when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isLeft()); + } + + @Test + public void testResourceTemplateCertify_UPDATE_SAD() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) + .thenReturn(isToscaNameExtending); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, + false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceCertified() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + assertTrue(createResponse.isLeft()); + Resource certifiedResource = createResponse.left().value(); + certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + certifiedResource.setVersion("1.0"); + + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceNotExist() { + Resource resourceToUpdtae = createResourceObject(false); + + Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); + + Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { + Resource basic = createResourceObject(true); + + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_FailedWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1.5"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isRight()); - } - -// @Test -// public void testDeleteMarkedResourcesNoResources() { -// List<GraphVertex> ids = new ArrayList<>(); -// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + +// @Test +// public void testDeleteMarkedResourcesNoResources() { +// List<GraphVertex> ids = new ArrayList<>(); +// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); +// +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// } // -// } +// @Test +// public void testDeleteMarkedResources() { +// List<String> ids = new ArrayList<String>(); +// String resourceInUse = "123"; +// ids.add(resourceInUse); +// String resourceFree = "456"; +// ids.add(resourceFree); +// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// @Test -// public void testDeleteMarkedResources() { -// List<String> ids = new ArrayList<String>(); -// String resourceInUse = "123"; -// ids.add(resourceInUse); -// String resourceFree = "456"; -// ids.add(resourceFree); -// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); +// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); // -// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); -// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); +// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); +// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); // -// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); -// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); +// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); +// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); // -// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); -// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); +// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); +// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); // -// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); -// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); +// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); +// List<String> deletedComponents = new ArrayList<>(); +// deletedComponents.add(resourceFree); +// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); // -// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); -// List<String> deletedComponents = new ArrayList<>(); -// deletedComponents.add(resourceFree); -// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); -// -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// List<String> resourceIdList = deleteMarkedResources.left().value(); -// assertFalse(resourceIdList.isEmpty()); -// assertTrue(resourceIdList.contains(resourceFree)); -// assertFalse(resourceIdList.contains(resourceInUse)); +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// List<String> resourceIdList = deleteMarkedResources.left().value(); +// assertFalse(resourceIdList.isEmpty()); +// assertTrue(resourceIdList.contains(resourceFree)); +// assertFalse(resourceIdList.contains(resourceInUse)); // -// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); -// } - - @SuppressWarnings("unchecked") - @Test - public void testFindVfCsarArtifactsToHandle() { - - Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; - String methodName = "findVfCsarArtifactsToHandle"; - Resource resource = new Resource(); - String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; - String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; - String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; - - String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; - String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; - String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; - - byte[] oldPayloadData = "oldPayloadData".getBytes(); - byte[] newPayloadData = "newPayloadData".getBytes(); - Map<String, ArtifactDefinition> deploymentArtifacts =new HashMap<>(); - - ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); - deploymentArtifactToUpdate.setMandatory(false); - deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); - deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); - deploymentArtifactToUpdate.setPayload(oldPayloadData); - deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); - deploymentArtifactToDelete.setMandatory(false); - deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); - deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); - deploymentArtifactToDelete.setPayload(oldPayloadData); - deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); - - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); - deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); - - Map<String, ArtifactDefinition> artifacts = new HashMap<>(); - - ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); - artifactToUpdate.setMandatory(false); - artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); - artifactToUpdate.setArtifactType("SNMP_POLL"); - artifactToUpdate.setPayload(oldPayloadData); - artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToDelete = new ArtifactDefinition(); - artifactToDelete.setMandatory(false); - artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); - artifactToDelete.setArtifactType("SNMP_TRAP"); - artifactToDelete.setPayload(oldPayloadData); - artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); - - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()),artifactToUpdate); - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()),artifactToDelete); - artifacts.put("ignore",artifactToIgnore); - - resource.setDeploymentArtifacts(deploymentArtifacts); - resource.setArtifacts(artifacts); - - List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); - NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, deploymentArtifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName); - - NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactInfoToCreateFileName); - - artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); - artifactPathAndNameList.add(informationalArtifactInfoToUpdate); - artifactPathAndNameList.add(deploymentArtifactInfoToCreate); - artifactPathAndNameList.add(informationalArtifactInfoToCreate); - - Object[] argObjects = {resource, artifactPathAndNameList, user}; - Class[] argClasses = {Resource.class, List.class, User.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = - (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Update).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - - } - catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testVFGeneratedInputs() { - - Resource resource = createVF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); - } - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckout() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - // create a new generic version without properties - genericVF.setVersion("2.0"); - genericVF.setProperties(null); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - List<InputDefinition> currentInputs = resource.getInputs(); - //verify previous inputs ownerId fields exist - user may not delete generated inputs - assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update required and valid - assertTrue(upgradeToLatestGeneric.left().value()); - //verify version was upgraded - assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not deleted - assertTrue(8 == resource.getInputs().size()); - //verify inputs ownerId fields were removed - user may delete/edit inputs - assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - } - - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - - //add an input to the VF - PropertyDefinition newProp = new PropertyDefinition(); - newProp.setType("integer"); - newProp.setName("newProp"); - resource.getInputs().add(new InputDefinition(newProp)); - - //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type - genericVF.setVersion("2.0"); - newProp.setType("string"); - genericVF.setProperties(new ArrayList<PropertyDefinition>()); - genericVF.getProperties().add(newProp); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update is invalid an void - assertFalse(upgradeToLatestGeneric.left().value()); - //verify version was not upgraded - assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not removed - assertTrue(9 == resource.getInputs().size()); - //verify user defined input exists - assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); - } - - @Test - public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { - - Resource resource = createPNF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); - assertTrue(0 == resource.getArtifacts().size()); - } - - - private Resource createVF() { - - genericVF = setupGenericTypeMock(GENERIC_VF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.VF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - private Resource createPNF() { - - genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.PNF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - - +// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); +// } + + @SuppressWarnings("unchecked") + @Test + public void testFindVfCsarArtifactsToHandle() { + + Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; + String methodName = "findVfCsarArtifactsToHandle"; + Resource resource = new Resource(); + String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; + String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; + String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; + + String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; + String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; + String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml"; + String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; + + byte[] oldPayloadData = "oldPayloadData".getBytes(); + byte[] newPayloadData = "newPayloadData".getBytes(); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + + ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); + deploymentArtifactToUpdate.setMandatory(false); + deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); + deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); + deploymentArtifactToUpdate.setPayload(oldPayloadData); + deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); + deploymentArtifactToDelete.setMandatory(false); + deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); + deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); + deploymentArtifactToDelete.setPayload(oldPayloadData); + deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); + + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); + deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); + + Map<String, ArtifactDefinition> artifacts = new HashMap<>(); + + ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); + artifactToUpdate.setMandatory(false); + artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); + artifactToUpdate.setArtifactType("SNMP_POLL"); + artifactToUpdate.setPayload(oldPayloadData); + artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition artifactToDelete = new ArtifactDefinition(); + artifactToDelete.setMandatory(false); + artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); + artifactToDelete.setArtifactType("SNMP_TRAP"); + artifactToDelete.setPayload(oldPayloadData); + artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToDelete.setIsFromCsar(true); + + ArtifactDefinition artifactToNotDelete = new ArtifactDefinition(); + artifactToNotDelete.setMandatory(false); + artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName); + artifactToNotDelete.setArtifactType("SNMP_TRAP"); + artifactToNotDelete.setPayload(oldPayloadData); + artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToNotDelete.setIsFromCsar(false); + + ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); + + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete); + artifacts.put("ignore", artifactToIgnore); + + resource.setDeploymentArtifacts(deploymentArtifacts); + resource.setArtifacts(artifacts); + + List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); + NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false); + + NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactInfoToCreateFileName, false); + + artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdate); + artifactPathAndNameList.add(deploymentArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar); + artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar); + + Object[] argObjects = {resource, artifactPathAndNameList, user}; + Class[] argClasses = {Resource.class, List.class, User.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = + (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size() == 1); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testVFGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(8 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); + } + + @Test + public void testCRGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createCR(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(5 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericCR.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericCR.getVersion())); + } + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckout() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + //create a VF that is derived from generic version 1.0 + Resource resource = createVF(); + // create a new generic version without properties + genericVF.setVersion("2.0"); + genericVF.setProperties(null); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + List<InputDefinition> currentInputs = resource.getInputs(); + //verify previous inputs ownerId fields exist - user may not delete generated inputs + assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update required and valid + assertTrue(upgradeToLatestGeneric.left().value()); + //verify version was upgraded + assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not deleted + assertTrue(8 == resource.getInputs().size()); + //verify inputs ownerId fields were removed - user may delete/edit inputs + assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + } + + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { + + //create a VF that is derived from generic version 1.0 + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + + //add an input to the VF + PropertyDefinition newProp = new PropertyDefinition(); + newProp.setType("integer"); + newProp.setName("newProp"); + resource.getInputs().add(new InputDefinition(newProp)); + + //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type + genericVF.setVersion("2.0"); + newProp.setType("string"); + genericVF.setProperties(new ArrayList<PropertyDefinition>()); + genericVF.getProperties().add(newProp); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update is invalid an void + assertFalse(upgradeToLatestGeneric.left().value()); + //verify version was not upgraded + assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not removed + assertTrue(9 == resource.getInputs().size()); + //verify user defined input exists + assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); + } + + @Test + public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createPNF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(3 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); + assertTrue(0 == resource.getArtifacts().size()); + } + + + private Resource createVF() { + + genericVF = setupGenericTypeMock(GENERIC_VF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.VF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Resource createCR() { + + genericCR = setupGenericTypeMock(GENERIC_CR_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.CR); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + private Resource createPNF() { + + genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.PNF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Map<String, String> getGenericPropertiesByToscaName(String toscaName) { + HashMap<String, String> PNFProps = new HashMap<String, String>() {{ + put("nf_function", "string"); + put("nf_role", "string"); + put("nf_type", "string"); + }}; + + HashMap<String, String> CRProps = new HashMap<String, String>() {{ + putAll(PNFProps); + put("nf_naming_code", "string"); + put("nf_naming", "org.openecomp.datatypes.Naming"); + }}; + + HashMap<String, String> VFProps = new HashMap<String, String>() {{ + putAll(CRProps); + put("availability_zone_max_count", "integer"); + put("min_instances", "integer"); + put("max_instances", "integer"); + }}; + + if (toscaName.contains("PNF")) return PNFProps; + if (toscaName.contains("CR")) return CRProps; + if (toscaName.contains("VF")) return VFProps; + + return new HashMap<>(); + } + + private Resource setupGenericTypeMock(String toscaName) { - - Resource genericType = createResourceObject(true); - genericType.setVersion("1.0"); - genericType.setToscaResourceName(toscaName); - String[] propNames = {"nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count", "min_instances", "max_instances"}; - String[] propTypes = {"string", "string", "string", "string", "org.openecomp.datatypes.Naming", "integer", "integer", "integer"}; - List<PropertyDefinition> genericProps = new ArrayList<>(); - for(int i = 0; i < 8; ++i){ - PropertyDefinition prop = new PropertyDefinition(); - prop.setName(propNames[i]); - prop.setType(propTypes[i]); - genericProps.add(prop); - } - genericType.setProperties(genericProps); - return genericType; - } - - - + + Resource genericType = createResourceObject(true); + genericType.setVersion("1.0"); + genericType.setToscaResourceName(toscaName); + List<PropertyDefinition> genericProps = new ArrayList<>(); + Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName); + genericPropsMap.forEach((name, type) -> { + PropertyDefinition prop = new PropertyDefinition(); + prop.setName(name); + prop.setType(type); + genericProps.add(prop); + }); + + genericType.setProperties(genericProps); + return genericType; + } + + private void validateUserRoles(Role... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java index 581adb28df..3abf711b91 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -53,6 +44,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ConfigurationSource; @@ -61,252 +53,259 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class ResourceInstanceBusinessLogicTest { - private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; - private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; - private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; - private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; - private static final String SERVICE_ID = "MyServiceId"; - private static final String HEAT_LABEL = "myHeat"; - private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; - private static final String USER_ID = "jh0003"; - private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); - - static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); - - @InjectMocks - static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic(); - - public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); - public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); -// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); - public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // @BeforeClass - public static void setup() { - - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); - - ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); - Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); - artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); - - ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); - Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); - artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); - - ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); - Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); - artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); - - Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); - Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); - - Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); - - Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); - - Either<User, ActionStatus> eitherUser = Either.left(adminUser); - Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); - - Object lightService = new Service(); - Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); -// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); - - Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), - Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); - - Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - - Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), - Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); - - Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); - Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); - - bl.setToscaOperationFacade(toscaOperationFacade); - - StorageOperationStatus status = StorageOperationStatus.OK; - Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); - Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); - Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); - - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); -// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); - setup(); - } - - @Test - public void testAddResourceInstanceArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); + private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; + private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; + private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; + private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; + private static final String SERVICE_ID = "MyServiceId"; + private static final String HEAT_LABEL = "myHeat"; + private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; + private static final String USER_ID = "jh0003"; + private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); + + static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); + + @InjectMocks + static ComponentInstanceBusinessLogic bl = new ComponentInstanceBusinessLogic(); + + public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); + public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); +// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); + public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // @BeforeClass + public static void setup() { + + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); + + ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); + Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); + artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); + + ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); + Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); + artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); + + ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); + Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); + artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); + + Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); + Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); + + Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); + + Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); + + Either<User, ActionStatus> eitherUser = Either.left(adminUser); + Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); + + Object lightService = new Service(); + Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); + + Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.any(AuditingActionEnum.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ResourceAuditData.class)); + + Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + + Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), + Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); + + Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); + Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); + + bl.setToscaOperationFacade(toscaOperationFacade); + + StorageOperationStatus status = StorageOperationStatus.OK; + Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); + Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); + Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); + + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); +// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); + setup(); + } + + @Test + public void testAddResourceInstanceArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); // -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); // -// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); -// assertNotNull(heatParameters); +// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); +// assertNotNull(heatParameters); // -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNotNull(heatEnvParameters); +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNotNull(heatEnvParameters); // -// assertEquals(heatParameters.size(), heatEnvParameters.size()); +// assertEquals(heatParameters.size(), heatEnvParameters.size()); // -// int index = 0; -// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { -// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); -// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); -// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); -// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); -// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); -// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); -// // current of heat parameter should be the default for heat env -// // parameter -// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); +// int index = 0; +// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { +// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); +// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); +// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); +// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); +// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); +// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); +// // current of heat parameter should be the default for heat env +// // parameter +// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); // -// index++; -// } - } - - @Test - public void testAddResourceInstanceArtifactsNoParams() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); - -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); - - List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); - assertNull(heatParameters); - -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNull(heatEnvParameters); - - } - - @SuppressWarnings("unchecked") - @Test - public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); - assertTrue(deploymentArtifacts.size() == 0); - - Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); - } - - private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".yml"); - artifactInfo.setArtifactType("HEAT"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - // long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); - - if (!placeholderOnly) { - artifactInfo.setEsId(artifactInfo.getUniqueId()); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - - if (withHeatParams) { - List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactInfo.setListHeatParameters(heatParams); - } - } - - return artifactInfo; - } - - private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } +// index++; +// } + } + + @Test + public void testAddResourceInstanceArtifactsNoParams() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); + +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); + + List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); + assertNull(heatParameters); + +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNull(heatEnvParameters); + + } + + @SuppressWarnings("unchecked") + @Test + public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 0); + + Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); + } + + private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + artifactInfo.setUserIdCreator(userId); + String fullName = "Jim H"; + artifactInfo.setUpdaterFullName(fullName); + // long time = System.currentTimeMillis(); + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(userId); + artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + + if (!placeholderOnly) { + artifactInfo.setEsId(artifactInfo.getUniqueId()); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + if (withHeatParams) { + List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactInfo.setListHeatParameters(heatParams); + } + } + + return artifactInfo; + } + + private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java index 309689af45..5f4dfdc6f7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java @@ -1,12 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +14,12 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class GenericTypeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java new file mode 100644 index 0000000000..6b1b37e5bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java @@ -0,0 +1,258 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class PolicyTypeImportUtilsTest { + + private static final String UNIQUE_ID_EXSISTS = "uniqueId"; + + @Test + public void isPolicyTypesEquals_whenBothTypesAreNull_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, null)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenOneTypeIsNull_returnFalse() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(new PolicyTypeDefinition(), null)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, new PolicyTypeDefinition())).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTypesIsSameObject_returnTrue() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(policyType, policyType)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_allFieldsEquals_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(createPolicyTypeWithAllFields(), createPolicyTypeWithAllFields())).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenTypesAreDifferentInANonCompareFields_returnTrue() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setOwnerId("ownerIdNew"); + type2.setModificationTime(System.currentTimeMillis()); + type2.setCreationTime(System.currentTimeMillis()); + type2.setUniqueId("uniqueIdNew"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenTypeIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setType("newType"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDescription("newDescription"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTargetsAreDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setTargets(new ArrayList<>()); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDerivedFromIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDerivedFrom("newDerivedFrom"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenVersionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setVersion("2.0"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenMetadataIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setMetadata(ImmutableMap.of("newKey", "newVal")); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() { + PolicyTypeDefinition noProperties = new PolicyTypeDefinition(); + PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build(); + PolicyTypeDefinition oneProp = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition twoProps = new PolicyTypeBuilder().setProperties(Arrays.asList(createPropertyDefinitionWithAllFields("prop1"), + createPropertyDefinitionWithAllFields("prop2"))) + .build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(twoProps, oneProp)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesSamePropertiesList_returnTrue() { + List<PropertyDefinition> propList = Collections.singletonList(createPropertyDefinitionWithAllFields("prop1")); + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(propList).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(propList).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListFieldsEquals_returnTrue() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListDifferentInANonComparedFields_returnTrue() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffNonComparedFields = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffNonComparedFields.setOwnerId("newOwner"); + prop1DiffNonComparedFields.setValue("newVal"); + prop1DiffNonComparedFields.setConstraints(null); + prop1DiffNonComparedFields.setUniqueId("newId"); + prop1DiffNonComparedFields.setHidden(true); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffNonComparedFields)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameName_returnFalse() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop2"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOFSameType_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1TypeInteger = createPropertyDefinitionWithAllFields("prop1"); + prop1TypeInteger.setType("integer"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1TypeInteger)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameDefaultVal_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDefault = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDefault.setDefaultValue("newDefVal"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDefault)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameSchema_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffSchema = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffSchema.setSchema(null); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffSchema)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsPasswordFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsPassword = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsPassword.setPassword(!prop1.isPassword()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsPassword)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsRequiredFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsRequired = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsRequired.setRequired(!prop1.isRequired()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsRequired)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotSameDescription_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDescription = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDescription.setDescription("newDescription"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDescription)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + private PolicyTypeDefinition createPolicyTypeWithAllFields() { + return new PolicyTypeBuilder() + .setType("type1") + .setDerivedFrom("derivedFrom") + .setVersion("1.0") + .setDescription("description") + .setUniqueId("id1") + .setHighestVersion(true) + .setModificationTime(System.currentTimeMillis()) + .setCreationTime(System.currentTimeMillis()) + .setTargets(getTargets()) + .setOwner("owner") + .setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2")) + .build(); + } + + private PropertyDefinition createPropertyDefinitionWithAllFields(String name) { + return new PropertyDataDefinitionBuilder() + .setConstraints(Arrays.asList(new GreaterThanConstraint("abc"), new MinLengthConstraint(5))) + .setUniqueId("uid") + .setDefaultValue("val1") + .setType("string") + .setValue("val1") + .setName(name) + .setSchemaType("string") + .setOwnerId("owner") + .setStatus("status") + .setDescription("description") + .setIsPassword(false) + .setIsRequired(false) + .build(); + } + + private List<String> getTargets() { + + return Collections.singletonList(UNIQUE_ID_EXSISTS); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java new file mode 100644 index 0000000000..0dac6ecb2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestGenerationUtils { + + public static ComponentsUtils getComponentsUtils() { + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + return new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java new file mode 100644 index 0000000000..fe6071239e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java @@ -0,0 +1,152 @@ +package org.openecomp.sdc.be.components.impl.version; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GroupMembersUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + private static final String INSTANCE_ID_PRE_CHANGE = "inst2"; + private static final String INSTANCE_ID_POST_CHANGE = "newInst2"; + @InjectMocks + private GroupMembersUpdateOperation testInstance; + @Mock + private GroupsOperation groupsOperation; + @Mock + private ComponentsUtils componentsUtils; + + @Captor + private ArgumentCaptor<List<GroupDataDefinition>> updatedGroupsCaptor; + private GroupDefinition group1, group2, group3; + private Resource container; + private ComponentInstance prevInst2Version, currInst2Version; + private static final ComponentInstance DONT_CARE = new ComponentInstance(); + + @Before + public void setUp() throws Exception { + group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE); + group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3"); + group3 = createGroupWithMembers("group3", "inst1", "inst3"); + container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .setUniqueId(CONTAINER_ID) + .setComponentType(ComponentTypeEnum.RESOURCE) + .build(); + prevInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_PRE_CHANGE) + .build(); + currInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_POST_CHANGE) + .build(); + } + + @Test + public void whenNoGroupsOnContainer_returnOk() { + ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenEmptyListOfGroups_returnOk() { + Resource resource = new Resource(); + resource.setGroups(new ArrayList<>()); + ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupsHasNoMembers_returnOk() { + GroupDefinition group1 = new GroupDefinition(); + group1.setMembers(emptyMap()); + GroupDefinition group2 = new GroupDefinition(); + group2.setMembers(emptyMap()); + Resource container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .build(); + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() { + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() { + verifyAllGroupsHasPrevInstancesAsMembers(); + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null)); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyGroupWithPrevInstanceMemberWereReplaced(); + assertThat(updatedGroupsCaptor.getValue()) + .containsExactlyInAnyOrder(group1, group2); + } + + @Test + public void whenFailingToUpdateGroups_propagateError() { + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void verifyGroupWithPrevInstanceMemberWereReplaced() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void verifyAllGroupsHasPrevInstancesAsMembers() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_PRE_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_PRE_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void assertGroupMembersIds(GroupDefinition group, String ... expectedMembersIds) { + assertThat(group.getMembers()) + .containsValues(expectedMembersIds); + } + + private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) { + GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create(); + Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId)); + groupDefinitionBuilder.setUniqueId(groupId); + return groupDefinitionBuilder.build(); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java new file mode 100644 index 0000000000..0da59d1157 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.utils.TestGenerationUtils.getComponentsUtils; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTargetsUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + + private PolicyTargetsUpdateOperation policyTargetsUpdateOperation; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Captor + private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor; + private PolicyDefinition policy1, policy2, policy3; + private Resource container; + + @Before + public void setUp() throws Exception { + policy1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2"); + policy2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3"); + policy3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3"); + container = new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .addPolicy(policy3) + .setUniqueId(CONTAINER_ID) + .build(); + policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils()); + } + + @Test + public void whenNoPolicies_returnActionOk() { + Component container = new Resource(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoCmptInstancePolicies_returnOk() { + PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build(); + Component container = new ResourceBuilder().addPolicy(policy).build(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.OK); + List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue(); + verifyUpdatedPolicies(updatedPolicies, policy1, policy2);//policy3 does not have "inst2" as target, no update needed + verifyUpdatedPolicyTargets(policy1, "inst1", "inst2New"); + verifyUpdatedPolicyTargets(policy2, "inst1", "inst2New", "inst3"); + } + + @Test + public void whenUpdateOfPoliciesFails_propagateTheFailure() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) { + assertThat(updatedPolicy.resolveComponentInstanceTargets()) + .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds); + } + + private void verifyUpdatedPolicies(List<PolicyDefinition> updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) { + assertThat(updatedPolicies) + .usingElementComparatorOnFields("targets") + .containsExactlyInAnyOrder(expectedUpdatedPolicies); + } + + private PolicyDefinition createPolicyWithCmptInstAsTargets(String uniqueId, String ... instId) { + PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create(); + Stream.of(instId).forEach(policyDefinitionBuilder::addComponentInstanceTarget); + return policyDefinitionBuilder.setUniqueId(uniqueId).build(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java new file mode 100644 index 0000000000..ef239f9a2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PostChangeVersionOperationOrchestratorTest { + + private PostChangeVersionOperationOrchestrator testInstance; + @Mock + private PostChangeVersionOperation postChangeVersionOperation1; + @Mock + private PostChangeVersionOperation postChangeVersionOperation2; + @Mock + private PostChangeVersionOperation postChangeVersionOperation3; + + @Before + public void setUp() throws Exception { + testInstance = new PostChangeVersionOperationOrchestrator(asList(postChangeVersionOperation1, postChangeVersionOperation2, postChangeVersionOperation3)); + } + + @Test + public void whenFirstPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation2, postChangeVersionOperation3); + } + + @Test + public void whenAnyPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation3); + } + + @Test + public void whenLastPostOperationFails_returnTheFailureResult() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void whenAllOperationsSucceeds_returnOk() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java index 31c795478a..cfb5bb59e0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; @@ -35,139 +32,138 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CertificationChangeTransitionTest extends LifecycleTestBase { - private CertificationChangeTransition certifyTransitionObj = null; - private CertificationChangeTransition certificationCancelObj = null; - private CertificationChangeTransition certificationFailObj = null; - - private ComponentsUtils componentsUtils = new ComponentsUtils(); - private User owner = null; - - Resource resource; - - @SuppressWarnings("unchecked") - @Before - public void setup() { - - super.setup(); - componentsUtils.Init(); - // checkout transition object - certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certifyTransitionObj.setConfigurationManager(configurationManager); - certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationCancelObj.setConfigurationManager(configurationManager); - certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationFailObj.setConfigurationManager(configurationManager); - certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - resource = createResourceObject(); - } - - @Test - public void testVFCMTStateValidation(){ - Resource resource = createResourceVFCMTObject(); - - User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isLeft(), true); - } - - @Test - public void testStateValidationSuccess() { - - Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testStateValidationFail() { - - // checkout - Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - assertValidationStateErrorResponse(validateBeforeTransition); - - // checkin - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertValidationStateErrorResponse(validateBeforeTransition); - - // rfc - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertValidationStateErrorResponse(validateBeforeTransition); - - // certified - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertValidationStateErrorResponse(validateBeforeTransition); - - } - - @Test - public void testRolesFail() { - Either<Resource, ResponseFormat> changeStateResult; - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); - - modifier.setRole(Role.TESTER.name()); - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testRolesSuccess() { - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(true, validateBeforeTransition.isLeft()); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.ADMIN.name()); - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(true, validateBeforeTransition.isLeft()); - - } - - private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) { - assertEquals(validateBeforeTransition.isRight(), true); - ResponseFormat error = validateBeforeTransition.right().value(); - Either<Resource, ResponseFormat> changeStateResult = Either.right(error); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + private CertificationChangeTransition certifyTransitionObj = null; + private CertificationChangeTransition certificationCancelObj = null; + private CertificationChangeTransition certificationFailObj = null; + + private User owner = null; + + Resource resource; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + + super.setup(); + // checkout transition object + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certifyTransitionObj.setConfigurationManager(configurationManager); + certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationCancelObj.setConfigurationManager(configurationManager); + certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationFailObj.setConfigurationManager(configurationManager); + certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + resource = createResourceObject(); + } + + @Test + public void testVFCMTStateValidation(){ + Resource resource = createResourceVFCMTObject(); + + User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isLeft(), true); + } + + @Test + public void testStateValidationSuccess() { + + Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testStateValidationFail() { + + // checkout + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + assertValidationStateErrorResponse(validateBeforeTransition); + + // checkin + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertValidationStateErrorResponse(validateBeforeTransition); + + // rfc + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertValidationStateErrorResponse(validateBeforeTransition); + + // certified + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertValidationStateErrorResponse(validateBeforeTransition); + + } + + @Test + public void testRolesFail() { + Either<Resource, ResponseFormat> changeStateResult; + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRolesSuccess() { + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.ADMIN.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + } + + private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) { + assertEquals(validateBeforeTransition.isRight(), true); + ResponseFormat error = validateBeforeTransition.right().value(); + Either<Resource, ResponseFormat> changeStateResult = Either.right(error); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java index 5530d4c0f5..f9fb9c83c1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -38,7 +32,6 @@ import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionAr import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -55,215 +48,219 @@ import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.Silent.class) public class CertificationRequestTest extends LifecycleTestBase { - private ComponentsUtils componentsUtils = new ComponentsUtils(); - @Mock - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Mock - private ServiceBusinessLogic serviceBusinessLogic; - @Mock - private CapabilityOperation capabilityOperation; - @Mock - private ToscaExportHandler toscaExportUtils; - - private CertificationRequestTransition rfcObj; - - - @Before - public void setup() { - super.setup(); - rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); - // checkout transition object -// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); - // checkoutObj.setAuditingManager(iAuditingManager); - rfcObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - -// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation); -// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); - } - - @Test - public void testVFCMTStateValidation(){ - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceVFCMTObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - User user = new User(); - user.setUserId("cs0008"); - user.setFirstName("Carlos"); - user.setLastName("Santana"); - user.setRole(Role.TESTER.name()); - - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - @Test - public void testCheckoutStateValidation() { - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = rfcObj.changeStateOperation(resource, user, - // owner, false); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - // changeStateResult = rfcObj.changeStateOperation(resource, user, - // owner, false); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - @Test - public void testAlreadyRfc() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCertificationInProgress() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testAlreadyCertified() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { - Resource resource = new Resource(); - Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - assertTrue(validateAllResourceInstanceCertified.isLeft()); - } - - @Test - public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { - Resource resource = new Resource(); - List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); - ComponentInstance ri = new ComponentInstance(); - ri.setComponentVersion("2.0"); - riList.add(ri); - resource.setComponentInstances(riList); - - Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - assertTrue(validateAllResourceInstanceCertified.isLeft()); - } - - @Test - public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { - Resource resource = createVFWithRI("0.3"); - - simulateCertifiedVersionExistForRI(); - - Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - - assertTrue(validateAllResourceInstanceCertified.isRight()); - ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); - assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); - assertTrue(responseFormat.getMessageId().equals("SVC4559")); - - } - - @Test - public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { - Resource resource = createVFWithRI("1.3"); - - simulateCertifiedVersionExistForRI(); - - Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - - assertTrue(validateAllResourceInstanceCertified.isRight()); - ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); - assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); - assertTrue(responseFormat.getMessageId().equals("SVC4559")); - - } - - @Test - public void testDeploymentArtifactRestriction() { - Either<? extends Component, ResponseFormat> changeStateResult; - Service service = createServiceObject(false); - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either<Service, ResponseFormat> result = Either.left(service); - Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); - when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - private void simulateCertifiedVersionExistForRI() { - Component dummyResource = new Resource(); - Either<Component, StorageOperationStatus> result = Either.left(dummyResource); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); - Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result); - } - - private Resource createVFWithRI(String riVersion) { - Resource resource = new Resource(); - List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); - ComponentInstance ri = new ComponentInstance(); - - ri.setComponentVersion(riVersion); - ri.setComponentUid("someUniqueId"); - riList.add(ri); - resource.setComponentInstances(riList); - return resource; - } + @Mock + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + @Mock + private CapabilityOperation capabilityOperation; + @Mock + private ToscaExportHandler toscaExportUtils; + + private CertificationRequestTransition rfcObj; + + + @Before + public void setup() { + super.setup(); + rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); + // checkout transition object +// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); + // checkoutObj.setAuditingManager(iAuditingManager); + rfcObj.setConfigurationManager(configurationManager); + +// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation); +// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); + + } + + @Test + public void testVFCMTStateValidation(){ + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceVFCMTObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + User user = new User(); + user.setUserId("cs0008"); + user.setFirstName("Carlos"); + user.setLastName("Santana"); + user.setRole(Role.TESTER.name()); + + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testAlreadyRfc() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testAlreadyCertified() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { + Resource resource = new Resource(); + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { + Resource resource = new Resource(); + List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); + ComponentInstance ri = new ComponentInstance(); + ri.setComponentVersion("2.0"); + riList.add(ri); + resource.setComponentInstances(riList); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { + Resource resource = createVFWithRI("0.3"); + + simulateCertifiedVersionExistForRI(); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { + Resource resource = createVFWithRI("1.3"); + + simulateCertifiedVersionExistForRI(); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testDeploymentArtifactRestriction() { + Either<? extends Component, ResponseFormat> changeStateResult; + Service service = createServiceObject(); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Service, ResponseFormat> result = Either.left(service); + Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); + when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, true); + assertEquals(changeStateResult.isLeft(), true); + } + + private void simulateCertifiedVersionExistForRI() { + Component dummyResource = new Resource(); + Either<Component, StorageOperationStatus> result = Either.left(dummyResource); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); + Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result); + } + + private Resource createVFWithRI(String riVersion) { + Resource resource = new Resource(); + List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); + ComponentInstance ri = new ComponentInstance(); + + ri.setComponentVersion(riVersion); + ri.setComponentUid("someUniqueId"); + riList.add(ri); + resource.setComponentInstances(riList); + return resource; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java index 21111ef59e..e60998b177 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; @@ -35,135 +32,133 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CheckinTest extends LifecycleTestBase { - private CheckinTransition checkinObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - - @Before - public void setup() { - - super.setup(); - - // checkout transition object - checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkinObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - } - - @Test - public void testSimpleCheckin() { - Either<Boolean, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testSimpleServiceCheckin() { - Either<Boolean, ResponseFormat> changeStateResult; - Service service = createServiceObject(false); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testCheckinTwiceValidation() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(owner.isLeft()); - // changeStateResult = checkinObj.changeStateOperation(resource, user, - // owner.left().value()); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testServiceCheckinTwiceValidation() { - Either<Service, ResponseFormat> changeStateResult; - Service service = createServiceObject(false); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(owner.isLeft()); - - Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCheckoutByAnotherUserValidation() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkinObj.changeStateOperation(resource, - // modifier, owner); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testServiceCheckoutByAnotherUserValidation() { - Either<Service, ResponseFormat> changeStateResult; - Service service = createServiceObject(false); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } + private CheckinTransition checkinObj = null; + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkinObj.setConfigurationManager(configurationManager); + } + + @Test + public void testSimpleCheckin() { + Either<Boolean, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testSimpleServiceCheckin() { + Either<Boolean, ResponseFormat> changeStateResult; + Service service = createServiceObject(); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testCheckinTwiceValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(owner.isLeft()); + // changeStateResult = checkinObj.changeStateOperation(resource, user, + // owner.left().value()); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckinTwiceValidation() { + Either<Service, ResponseFormat> changeStateResult; + Service service = createServiceObject(); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(owner.isLeft()); + + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCheckoutByAnotherUserValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkinObj.changeStateOperation(resource, + // modifier, owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckoutByAnotherUserValidation() { + Either<Service, ResponseFormat> changeStateResult; + Service service = createServiceObject(); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java index 1e3f6f6ce8..0826e5d40c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java @@ -20,16 +20,13 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; @@ -37,153 +34,151 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CheckoutTest extends LifecycleTestBase { - private CheckoutTransition checkoutObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - - @Before - public void setup() { - - super.setup(); - - // checkout transition object - checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setComponentsUtils(componentsUtils); - - } - - @Test - public void testCheckoutStateValidation() { - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testAlreadyCheckout() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCertificationInProgress() { - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - - Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testReadyForCertification() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - - // if modifier = owner - Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkoutObj.changeStateOperation(resource, user, - // owner); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isLeft(), true); - - // else - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - - // admin - modifier.setRole(Role.ADMIN.name()); - // changeStateResult = checkoutObj.changeStateOperation(resource, user, - // owner); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isLeft(), true); - - // designer - modifier.setRole(Role.TESTER.name()); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testRoles() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkoutObj.changeStateOperation(resource, - // modifier, owner); - Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isLeft(), true); - - modifier.setRole(Role.TESTER.name()); - // changeStateResult = checkoutObj.changeStateOperation(resource, - // modifier, owner); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); - - } + private CheckoutTransition checkoutObj = null; + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkoutObj.setConfigurationManager(configurationManager); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setComponentsUtils(componentsUtils); + + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testAlreadyCheckout() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testReadyForCertification() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // if modifier = owner + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // else + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + + // admin + modifier.setRole(Role.ADMIN.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // designer + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRoles() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isLeft(), true); + + modifier.setRole(Role.TESTER.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java index bc131ff39a..941af0d728 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java @@ -20,20 +20,13 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.junit.BeforeClass; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.openecomp.sdc.AuditingMockManager; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -41,6 +34,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -67,173 +61,185 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.when; public class LifecycleTestBase { - private static Logger log = LoggerFactory.getLogger(LifecycleTestBase.class.getName()); - @InjectMocks - protected final ServletContext servletContext = Mockito.mock(ServletContext.class); - protected IAuditingManager iAuditingManager = null; - protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); - protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; - protected User user = null; - protected Resource resourceResponse; - protected Service serviceResponse; - protected static ConfigurationManager configurationManager = null; - protected ResponseFormatManager responseManager = null; - protected TitanDao titanDao = Mockito.mock(TitanDao.class); - protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - @BeforeClass - public static void setupClass() { - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - } - - public void setup() { - - // Auditing - iAuditingManager = new AuditingMockManager("lll"); - - // User data and management - user = new User(); - user.setUserId("jh003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); - when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); - - // Resource Operation mock methods - // getCount - - // createResource - resourceResponse = createResourceObject(); - Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); - when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - Either<User, StorageOperationStatus> getOwnerResult = Either.left(user); - when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); - - Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK); - when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); - - responseManager = ResponseFormatManager.getInstance(); - - } - - public static <T> Answer<T> createAnswer(final T value) { - Answer<T> dummy = new Answer<T>() { - @Override - public T answer(InvocationOnMock invocation) throws Throwable { - return value; - } - - }; - return dummy; - } - - protected Resource createResourceObject() { - Resource resource = new Resource(); - resource.setName("MyResourceName"); - resource.setUniqueId("uid"); - resource.addCategory("VoIP", "INfra"); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Resource createResourceVFCMTObject() { - ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); - rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); - ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; - - Resource resource = new Resource(cMetadataDataDefinition); - resource.setUniqueId("rid"); - resource.setName("MyResourceVFCMTName"); - resource.addCategory("VoIP", "INfra"); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test1"); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Service createServiceObject(boolean b) { - Service service = new Service(); - service.setName("MyServiceName"); - service.setUniqueId("sid"); - service.addCategory("VoIP", null); - service.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - service.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - service.setContactId("aa0001"); - service.setIcon("MyIcon.jpg"); - - return service; - } - - protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } + private static final Logger log = LoggerFactory.getLogger(LifecycleTestBase.class); + @InjectMocks + protected final ServletContext servletContext = Mockito.mock(ServletContext.class); + protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; + protected User user = null; + protected Resource resourceResponse; + protected Service serviceResponse; + protected static ConfigurationManager configurationManager = null; + protected ResponseFormatManager responseManager = null; + protected TitanDao titanDao = Mockito.mock(TitanDao.class); + protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + protected static ComponentsUtils componentsUtils; + + @BeforeClass + public static void setupClass() { + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } + + public void setup() { + +// ExternalConfiguration.setAppName("catalog-be"); +// +// // init Configuration +// String appConfigDir = "src/test/resources/config/catalog-be"; +// ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); +// configurationManager = new ConfigurationManager(configurationSource); + + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); + when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); + + // Resource Operation mock methods + // getCount + + // createResource + resourceResponse = createResourceObject(); + Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); + when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + Either<User, StorageOperationStatus> getOwnerResult = Either.left(user); + when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); + + Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK); + when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); + + responseManager = ResponseFormatManager.getInstance(); + + } + + public static <T> Answer<T> createAnswer(final T value) { + Answer<T> dummy = new Answer<T>() { + @Override + public T answer(InvocationOnMock invocation) throws Throwable { + return value; + } + + }; + return dummy; + } + + protected Resource createResourceObject() { + Resource resource = new Resource(); + resource.setUniqueId("uid"); + resource.setName("MyResourceName"); + resource.setUniqueId("uid"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Resource createResourceVFCMTObject() { + ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); + rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); + ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; + + Resource resource = new Resource(cMetadataDataDefinition); + resource.setUniqueId("rid"); + resource.setName("MyResourceVFCMTName"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test1"); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Service createServiceObject() { + Service service = new Service(); + service.setName("MyServiceName"); + service.setUniqueId("sid"); + service.addCategory("VoIP", null); + service.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + service.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + service.setContactId("aa0001"); + service.setIcon("MyIcon.jpg"); + + return service; + } + + protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java index 11913ad31a..d5d665809d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java @@ -20,105 +20,100 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class UndoCheckoutTest extends LifecycleTestBase { - private UndoCheckoutTransition undoCheckoutObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - - @Before - public void setup() { + private UndoCheckoutTransition undoCheckoutObj = null; - super.setup(); + @Before + public void setup() { - // checkout transition object - undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - undoCheckoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); + super.setup(); + // checkout transition object + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + undoCheckoutObj.setConfigurationManager(configurationManager); - } + } - @Test - public void testResourceNotCheckedOutValidation() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); + @Test + public void testResourceNotCheckedOutValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); + Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + } - @Test - public void testDifferentResourceOwnerValidation() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); + @Test + public void testDifferentResourceOwnerValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); - Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java index ab2e865ae0..89b82b91d2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java @@ -1,14 +1,7 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - +import com.google.common.collect.Sets; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -24,9 +17,14 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class GlobalInputsFilteringBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java index a00b0b8e8a..ec741b4953 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -18,7 +11,13 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; public class GlobalTypesMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java index 773b068cd7..d50f4859db 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; @@ -14,14 +9,23 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class RelationsComparatorTest { public static final String INSTANCE1 = "instance1"; public static final String INSTANCE2 = "instance2"; RelationsComparator testInstance; - private RequirementCapabilityRelDef relation1, relation2, relation3, relation4; - private ComponentInstance componentInstance1, componentInstance2; + private RequirementCapabilityRelDef relation1; + private RequirementCapabilityRelDef relation2; + private RequirementCapabilityRelDef relation3; + private RequirementCapabilityRelDef relation4; + private ComponentInstance componentInstance1; + private ComponentInstance componentInstance2; @Before public void setUp() { @@ -59,21 +63,21 @@ public class RelationsComparatorTest { @Test public void isRelationsChanged_notSameType() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().getRelationship().setType("someDiffType"); + relation2DifType.resolveSingleRelationship().getRelation().getRelationship().setType("someDiffType"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameCapability() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); + relation2DifType.resolveSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameReqName() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setRequirement("someDiffReq"); + relation2DifType.resolveSingleRelationship().getRelation().setRequirement("someDiffReq"); isRelationsChangedTest(relation2DifType); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java index 3b1ed52550..298a4454b3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java @@ -1,10 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +16,10 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class TopologyComparatorTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java new file mode 100644 index 0000000000..be9f426c2c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java @@ -0,0 +1,113 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import java.util.Map; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleCapabilityResolverTest { + + public static final String NEW_OWNER_ID1 = "owner1"; + public static final String NEW_OWNER_ID2 = "owner2"; + public static final String OLD_OWNER_ID1 = "oldOwner1"; + private static final String OLD_OWNER_ID2 = "oldOwner2"; + public static final String OLD_OWNER_ID3 = "oldOwner3"; + @InjectMocks + private SimpleCapabilityResolver testInstance; + @Mock + private MergeInstanceUtils MergeInstanceUtils; + + private CapabilityDefinition capName1Owner1Type1; + private CapabilityDefinition capName1Owner1Type2; + private CapabilityDefinition capName1Owner2Type1; + private CapabilityDefinition capName2Owner1Type2; + + private CapabilityDefinition prevCapName1Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type2; + private CapabilityDefinition prevCapName1Owner2Type1; + private CapabilityDefinition prevCapName2Owner1Type2; + private CapabilityDefinition prevCapName1Owner3Type1; + private CapabilityDefinition prevCapName3Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type3; + CapabilityDefinition[] prevCapabilities; + private ComponentInstance oldInstance; + private ComponentInstance currInstance; + + + @Before + public void setUp() { + capName1Owner1Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type1 = new CapabilityDefinition(capName1Owner1Type1); + prevCapName1Owner1Type1.setOwnerId(OLD_OWNER_ID1); + + capName1Owner1Type2 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName1Owner1Type2 = new CapabilityDefinition(capName1Owner1Type2); + prevCapName1Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + capName1Owner2Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID2).setType("type1").build(); + prevCapName1Owner2Type1 = new CapabilityDefinition(capName1Owner2Type1); + prevCapName1Owner2Type1.setOwnerId(OLD_OWNER_ID2); + + capName2Owner1Type2 = new CapabilityDefinitionBuilder().setName("name2").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName2Owner1Type2 = new CapabilityDefinition(capName2Owner1Type2); + prevCapName2Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + //prev capabilities that are not mapped to any new capability + prevCapName1Owner3Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID3).setType("type1").build(); + prevCapName3Owner1Type1 = new CapabilityDefinitionBuilder().setName("name3").setOwnerId(OLD_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type3 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID1).setType("type3").build(); + + currInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(capName1Owner1Type1, capName1Owner1Type2, capName1Owner2Type1, capName2Owner1Type2).build(); + prevCapabilities = new CapabilityDefinition[]{prevCapName1Owner1Type1, prevCapName1Owner1Type2, prevCapName1Owner2Type1, prevCapName2Owner1Type2, prevCapName1Owner3Type1, prevCapName3Owner1Type1, prevCapName1Owner1Type3}; + oldInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(prevCapabilities).build(); + } + + @Test + public void resolvePrevCapIdToNewCapability_resolveByTypeNameAndNewOwnerId() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } + + @Test + public void resolvePrevCapIdToNewCapability_noMatchingNewOwnerIds() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(emptyMap()); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).isEmpty(); + } + + @Test + public void mapOldToNewInstanceCapabilitiesOwnerIds() { + Resource container = new ResourceBuilder().addComponentInstance(currInstance).build(); + Resource prevInstanceOrigNode = new Resource(); + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, "inst1", asList(OLD_OWNER_ID1, OLD_OWNER_ID2, OLD_OWNER_ID3))).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapToNewCapability(container, prevInstanceOrigNode, "inst1", asList(prevCapabilities)); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java index bcdd08e95b..c75a6ccd5d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java @@ -1,12 +1,5 @@ package org.openecomp.sdc.be.components.merge.heat; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ArtifactBuilder; @@ -15,6 +8,13 @@ import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + public class HeatEnvArtifactsMergeBusinessLogicTest { private HeatEnvArtifactsMergeBusinessLogic testInstance; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java index 26b6782918..30801b0a4a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java @@ -1,14 +1,6 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.ListUtils; import org.junit.Before; import org.junit.Test; @@ -22,7 +14,14 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class ComponentInputsMergeBLTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java index b0124e4e44..98fceab7a8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java @@ -1,26 +1,24 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class InputsValuesMergingBusinessLogicTest { public static final String INPUT_DEFUALT_TYPE = "string"; @@ -133,54 +131,4 @@ public class InputsValuesMergingBusinessLogicTest { inputDef.setOwnerId("owner"); return inputDef; } - - private void addInstanceProperty(Resource resource, ComponentInstanceProperty prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesProperties(), prop, instanceId); - } - - private void addInstanceInput(Resource resource, ComponentInstanceInput prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesInputs(), prop, instanceId); - } - - private <T extends PropertyDataDefinition> void addInstancePropDefinition(Map<String, List<T>> propsDefinitions, T propDef, String instanceId) { - propsDefinitions.computeIfAbsent(instanceId, id -> new ArrayList<>()).add(propDef); - } - - private Resource createResourceWithInputs(String ... inputsIds) { - Resource resource = new Resource(); - List<InputDefinition> inputs = new ArrayList<>(); - for (String inputId : inputsIds) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setOwnerId("cs0008"); - inputDefinition.setUniqueId(inputId); - inputs.add(inputDefinition); - } - resource.setInputs(inputs); - return resource; - } - - - private ComponentInstanceProperty createGetInputComponentProperty(String ... declaredToInputId) { - ComponentInstanceProperty prevDeclaredProperty = new ComponentInstanceProperty(); - for (String inputId : declaredToInputId) { - addGetInputValueOnProp(inputId, prevDeclaredProperty); - } - - return prevDeclaredProperty; - } - - private void addGetInputValueOnProp(String declaredToInputId, PropertyDataDefinition declaredProperty) { - GetInputValueDataDefinition getInputDef = new GetInputValueDataDefinition(); - getInputDef.setInputId(declaredToInputId); - if (declaredProperty.getGetInputValues() == null) { - declaredProperty.setGetInputValues(new ArrayList<>()); - } - declaredProperty.getGetInputValues().add(getInputDef); - } - - private ComponentInstanceInput createGetInputComponentInstanceInput(String declaredToInputId) { - ComponentInstanceInput prevDeclaredProp = new ComponentInstanceInput(); - addGetInputValueOnProp(declaredToInputId, prevDeclaredProp); - return prevDeclaredProp; - } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java index be16bc3621..df3e0ddb68 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge.instance; -import static junit.framework.TestCase.assertEquals; - -import java.util.HashMap; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -14,6 +9,11 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; +import java.util.HashMap; +import java.util.Map; + +import static groovy.util.GroovyTestCase.assertEquals; + public class ComponentInstanceArtifactsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java new file mode 100644 index 0000000000..4fbb1ab5d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabiliteisPropertiesMergeTest { + + @InjectMocks + private ComponentInstanceCapabiliteisPropertiesMerge testInstance; + + @Mock + private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; + + @Mock + private ComponentsUtils componentsUtils; + + private DataForMergeHolder mergeHolder; + + private Resource origInstanceNode; + private List<CapabilityDefinition> origInstanceCapabilities; + + @Before + public void setUp() throws Exception { + origInstanceNode = new Resource(); + origInstanceCapabilities = Collections.emptyList(); + mergeHolder = new DataForMergeHolder(); + mergeHolder.setOrigInstanceNode(origInstanceNode); + mergeHolder.setOrigInstanceCapabilities(origInstanceCapabilities); + } + + @Test + public void mergeDataAfterCreate() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.OK); + Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isLeft()); + } + + @Test + public void mergeDataAfterCreate_error() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat()); + Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isRight()); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java new file mode 100644 index 0000000000..d73459c1b1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java @@ -0,0 +1,275 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.merge.capability.SimpleCapabilityResolver; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstancePropertyBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabilitiesMergeBLTest { + + private static final String INSTANCE1 = "inst1"; + private static final String INSTANCE2 = "inst2"; + + private ComponentCapabilitiesPropertiesMergeBL testInstance; + private ComponentsUtils componentsUtils; + @Mock + private SimpleCapabilityResolver capabilityResolver; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; + @Captor + private ArgumentCaptor<List<ComponentInstanceProperty>> prevCapPropertiesCaptor; + @Captor + private ArgumentCaptor<List<ComponentInstanceProperty>> currCapPropertiesCaptor; + @Captor + private ArgumentCaptor<ComponentParametersView> getCurrResourceFilterCapture; + + private CapabilityDefinition oldCap; + private CapabilityDefinition oldCap2; + private CapabilityDefinition newCap; + private CapabilityDefinition newCap2; + + private ComponentParametersView getCapabilitiesPropsFilter; + + protected static ConfigurationManager configurationManager = null; + + @Before + public void setUp() throws Exception { + oldCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .build(); + + oldCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop3").build()) + .build(); + + getCapabilitiesPropsFilter = new ComponentParametersView(); + getCapabilitiesPropsFilter.disableAll(); + getCapabilitiesPropsFilter.setIgnoreComponentInstances(false); + getCapabilitiesPropsFilter.setIgnoreCapabilities(false); + getCapabilitiesPropsFilter.setIgnoreCapabiltyProperties(false); + + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + testInstance = new ComponentCapabilitiesPropertiesMergeBL(dataDefinitionsValuesMergingBusinessLogic, toscaOperationFacade, componentsUtils, capabilityResolver); + } + + @Test + public void mergeCapabilityProperties_singleCapability() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), getCurrResourceFilterCapture.capture())).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + assertThat(getCurrResourceFilterCapture.getValue()).isEqualToComparingFieldByField(getCapabilitiesPropsFilter); + } + + @Test + public void mergeCapabilityProperties_failToGetResourceWithPropsCapabilities() { + Resource currResource = new ResourceBuilder().setUniqueId("rid").build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + ActionStatus actionStatus = testInstance.mergeComponents(new Resource(), currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + @Test + public void mergeCapabilityProperties_multipleCapabilitiesToMerge() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance prevInst2 = new ComponentInstanceBuilder().addCapability(oldCap2).setName(oldCap2.getOwnerName()).build(); + + ComponentInstance currInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + ComponentInstance currInst2 = new ComponentInstanceBuilder().addCapability(newCap2).setName(newCap2.getOwnerName()).build(); + + Resource currResource = new ResourceBuilder().addComponentInstance(currInst1).addComponentInstance(currInst2).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).addComponentInstance(prevInst2).build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(currResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, currInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst2, currInst2)).thenReturn(ImmutableMap.of(oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeCapabilityProperties_noNewCapabilitiesResolved() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().setName(oldCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_noPrevCapabilitiesToMerge() { + Resource newResource = new Resource(); + Resource prevResource = new Resource(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + verifyNoMoreInteractions(toscaOperationFacade); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_failedToUpdateComponent() { + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + Resource newResource = new Resource(); + Resource prevResource = new ResourceBuilder().addComponentInstance(inst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + //////////////////////////// + @Test + public void mergeInstanceCapabilityProperties_singleCap() { + List<CapabilityDefinition> previousInstanceCapabilities = Collections.singletonList(oldCap); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, newCap.getOwnerId())).thenReturn(StorageOperationStatus.OK); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap)); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + } + + @Test + public void mergeInstanceCapabilityProperties() { + List<CapabilityDefinition> previousInstanceCapabilities = Arrays.asList(oldCap, oldCap2); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).addCapability(newCap2).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap, oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeInstanceCapabilityProperties_emptyCapabilitiesList() { + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(new Resource(), new Resource(), "instanceId", Collections.emptyList()); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade, dataDefinitionsValuesMergingBusinessLogic, capabilityResolver); + } + + @Test + public void mergeInstanceCapabilityProperties_failedToUpdateComponent() { + Resource container = new Resource(); + Resource resource = new Resource(); + List<CapabilityDefinition> capList = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, capList)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, capList); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void mergeInstanceCapabilityProperties_noNewCapabilitiesFound() { + Resource container = new Resource(); + Resource resource = new Resource(); + List<CapabilityDefinition> prevCapabilities = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, prevCapabilities)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, prevCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java index 2101ea49ab..115825733e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -26,7 +19,13 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Mockito.when; public class ComponentInstanceHeatEnvMergeTest { @@ -67,7 +66,7 @@ public class ComponentInstanceHeatEnvMergeTest { for (ArtifactDefinition mergedArtifact : mergedArtifacts) { Map<String, Object> json = new HashMap<>(); when(artifactsBusinessLogicMock.buildJsonForUpdateArtifact(mergedArtifact, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(json); - ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update); + ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE); when(artifactsBusinessLogicMock.updateResourceInstanceArtifactNoContent(Mockito.eq(instanceId), Mockito.eq(resource), Mockito.eq(USER), Mockito.eq(json), Mockito.refEq(artifactUpdateOperation), diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java index bc3efe423d..630a43ef2d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -29,7 +22,13 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceMergeDataBusinessLogicTest { @@ -112,4 +111,6 @@ public class ComponentInstanceMergeDataBusinessLogicTest { assertFalse(value.isIgnoreArtifacts()); } + + }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java index cb3d506bfc..d946206f23 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java @@ -1,16 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyListOf; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -19,8 +9,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -37,7 +25,16 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropsAndInputsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java new file mode 100644 index 0000000000..08c8456064 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java @@ -0,0 +1,378 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceRelationMergeTest { + private ComponentInstanceRelationMerge compInstanceRelationMerge; + @Mock + private DataForMergeHolder dataHolder; + private Component containerComponent; + private Component updatedContainerComponent; + private ComponentInstance currentResourceInstance; + + private RequirementCapabilityRelDef requirementDef1; + private RequirementCapabilityRelDef requirementDef2; + private RequirementCapabilityRelDef capabilityDef1; + private RequirementCapabilityRelDef capabilityDef2; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private User user; + + @Captor + ArgumentCaptor<VfRelationsMergeInfo> argumentCaptor; + + + @Before + public void startUp() { + compInstanceRelationMerge = new ComponentInstanceRelationMerge(); + compInstanceRelationMerge.setToscaOperationFacade(toscaOperationFacade); + + MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + compInstanceRelationMerge.setMergeInstanceUtils(mergeInstanceUtils); + + containerComponent = new Service(); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + + requirementDef1 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF2.VFI_1", "SRV1.VF1.VFC_1.VFCI_1", "Requirement1"); + resourceInstancesRelations.add(requirementDef1); + requirementDef2 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF3.VFI_1", "SRV1.VF1.VFC_2.VFCI_2", "Requirement2"); + resourceInstancesRelations.add(requirementDef2); + + + capabilityDef1 = createCapabilityDef("SRV1.VF4.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_3.VFCI_3", "Capability3"); + resourceInstancesRelations.add(capabilityDef1); + capabilityDef2 = createCapabilityDef("SRV1.VF5.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_4.VFCI_1", "Capability4"); + resourceInstancesRelations.add(capabilityDef2); + + containerComponent.setComponentInstancesRelations(resourceInstancesRelations ); + + currentResourceInstance = new ComponentInstance(); + currentResourceInstance.setUniqueId("SRV1.VF1.VFI_1"); + currentResourceInstance.setComponentUid("SRV1.VF1"); + currentResourceInstance.setIsProxy(false); + + updatedContainerComponent = new Service(); + updatedContainerComponent.setUniqueId("123123123123123123"); + } + + @Test + public void testSaveDataBeforeMerge() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + compInstanceRelationMerge.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, vf); + + verify(dataHolder).setVfRelationsInfo(argumentCaptor.capture()); + VfRelationsMergeInfo relationsMergeInfo = argumentCaptor.getValue(); + List<RelationMergeInfo> fromRelationsMergeInfo = relationsMergeInfo.getFromRelationsInfo(); + List<RelationMergeInfo> toRelationsMergeInfo = relationsMergeInfo.getToRelationsInfo(); + + assertNotNull("Expected not null list of relations merge info", fromRelationsMergeInfo); + assertNotNull("Expected not null list of relations merge info", toRelationsMergeInfo); + + assertEquals("Expected 2 elements", 2, fromRelationsMergeInfo.size()); + assertEquals("Expected 1 elements", 1, toRelationsMergeInfo.size()); + } + + @Test + public void testMergeDataAfterCreate_NoSavedData() { + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertNull("Expected no relations", relations); + } + + @Test + public void testMergeDataAfterCreate() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either<Component, StorageOperationStatus> eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>(); + List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_1", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_1", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + + @Test + public void testMergeDataAfterCreate_OwnerChanged() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_2", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_2", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either<Component, StorageOperationStatus> eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>(); + List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_2", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_2", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + /** + * @param vfId + * @param vfiUniqueId + * @return + */ + private ComponentInstance createVfi(String vfId, String vfiUniqueId) { + ComponentInstance vfi = new ComponentInstance(); + vfi.setUniqueId(vfiUniqueId); + vfi.setComponentUid(vfId); + + Resource vf = new Resource(); + vf.setUniqueId(vfId); + return vfi; + } + + private ComponentInstance createVfci(String name, String uniqueId, String componentUid, boolean foundVfc) { + ComponentInstance compInst = new ComponentInstance(); + compInst.setName(name); + compInst.setUniqueId(uniqueId); + compInst.setComponentUid(componentUid); + + if(foundVfc) { + createVfc(componentUid); + } + else { + failLoadVfc(componentUid); + } + return compInst; + } + + private void failLoadVfc(String uid) { + Either<Component, StorageOperationStatus> eitherVFC = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + } + + private Component createVfc(String uid) { + Resource vfc = new Resource(); + vfc.setUniqueId(uid); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>();; + IntStream.range(0, 5).forEach(i -> { + + List<CapabilityDefinition> capList = new LinkedList<>(); + capList.add(null); + CapabilityDefinition capDef = new CapabilityDefinition(); + capDef.setName("CapabilityName" + i); + capDef.setUniqueId("Capability" + i); + capDef.setType("CapabilityType" + i); + capList.add(capDef); + capabilities.put("Key" + i, capList); + + List<RequirementDefinition> reqList = new LinkedList<>(); + reqList.add(null); + RequirementDefinition reqDef = new RequirementDefinition(); + reqDef.setName("RequirementName" + i); + reqDef.setUniqueId("Requirement" + i); + reqDef.setCapability("CapabilityType" + i); + reqList.add(reqDef); + requirements.put("Key" + i, reqList); + + }); + vfc.setCapabilities(capabilities ); + vfc.setRequirements(requirements); + + Either<Component, StorageOperationStatus> eitherVFC = Either.left(vfc); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + + return vfc; + } + + private RequirementCapabilityRelDef createRequirementCapabilityDef(String fromNode, String toNode) { + RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef(); + + reqCapDef.setFromNode(fromNode); + reqCapDef.setToNode(toNode); + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + relationships.add(capabilityRequirementRelationship); + reqCapDef.setRelationships(relationships); + + return reqCapDef; + } + + private RequirementCapabilityRelDef createRequirementDef(String fromNode, String toNode, String ownerId, String requirementUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setRequirementOwnerId(ownerId); + relationshipInfo.setRequirementUid(requirementUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + + + return reqCapDef; + } + + private RequirementCapabilityRelDef createCapabilityDef(String fromNode, String toNode, String ownerId, String capabilityUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setCapabilityOwnerId(ownerId); + relationshipInfo.setCapabilityUid(capabilityUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + return reqCapDef; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java new file mode 100644 index 0000000000..65ab3ec121 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.components.merge.path; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceForwardingPathMerge; +import org.openecomp.sdc.be.components.path.BaseForwardingPathVersionChangeTest; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Set; + +import static groovy.util.GroovyTestCase.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.when; + +public class ComponentInstanceForwardingPathMergeTest extends BaseForwardingPathVersionChangeTest { + + @InjectMocks + private ComponentInstanceForwardingPathMerge testInstance; + + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + private User user; + + @Before + public void setUpData() { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId("44"); + user.setRole(UserRoleEnum.ADMIN.getName()); + } + + @Test + public void testIgnoreMergeSinceItIsNotService() { + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, newNodeAC, "3344"); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(newNodeAC, componentResponseFormatEither.left().value()); + } + + @Test + public void mergeShouldDelete() { + Set<String> forwardingPathNamesToDeleteOnComponentInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeACI.getUniqueId()); + nodeACI.getCapabilities().clear(); + newNodeAC.getCapabilities().clear(); + when(serviceBusinessLogic.deleteForwardingPaths(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(forwardingPathNamesToDeleteOnComponentInstanceDeletion)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(0, ((Service) componentResponseFormatEither.left().value()).getForwardingPaths().size()); + } + + @Test + public void mergeShouldUpdate() { + when(serviceBusinessLogic.updateForwardingPath(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(service)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java index 0a858c9a29..bbb2dd6895 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceInputsMergeBL; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -23,7 +17,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceInputsMergeBLTest { @@ -41,7 +41,8 @@ public class ComponentInstanceInputsMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -71,22 +72,22 @@ public class ComponentInstanceInputsMergeBLTest { @Test public void mergeInstancesInputs() throws Exception { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @Test - public void mergeInstancesInputs_failure() throws Exception { + public void mergeInstancesInputs_failure() { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } @Test - public void mergeInstanceProps() throws Exception { + public void mergeInstanceProps() { List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) @@ -97,7 +98,7 @@ public class ComponentInstanceInputsMergeBLTest { } @Test - public void mergeInstanceProps_failure() throws Exception { + public void mergeInstanceProps_failure() { List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java index 7948ab8a3d..6013009106 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -21,7 +15,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropertiesMergeBLTest { @@ -40,7 +40,8 @@ public class ComponentInstancePropertiesMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -64,7 +65,7 @@ public class ComponentInstancePropertiesMergeBLTest { public void mergeInstancesPropsAndInputs_mergeInstanceProps() throws Exception { when(toscaOperationFacade.updateComponentInstancePropsToComponent(newResource.getComponentInstancesProperties(), newResource.getUniqueId())) .thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @@ -75,7 +76,7 @@ public class ComponentInstancePropertiesMergeBLTest { .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java index 8669a781b4..3b079d30d5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java @@ -1,21 +1,22 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionAbstractBuilder; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.verify; + public class DataDefinitionsValuesMergingBusinessLogicTest { private static final String DEFAULT_PROP_TYPE = "string"; @@ -110,9 +111,10 @@ public class DataDefinitionsValuesMergingBusinessLogicTest { } private PropertyDataDefinition createGetInputPropertyDataDefinition(String name, String ... inputsNames) { - PropertyDataDefinitionBuilder propertyBuilder = new PropertyDataDefinitionBuilder() + PropertyDataDefinitionAbstractBuilder propertyBuilder = new PropertyDataDefinitionBuilder() .setName(name) .setType(DEFAULT_PROP_TYPE); + for (String inputName : inputsNames) { propertyBuilder.addGetInputValue(inputName); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java index 6faee487f4..5c23ec0e8c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java @@ -1,17 +1,6 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -25,7 +14,17 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import fj.data.Either; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class PropertyDataValueMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java index 8e7949f108..0590c7e500 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java @@ -1,82 +1,63 @@ package org.openecomp.sdc.be.components.merge.resource; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; - import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) public class ResourceDataMergeBusinessLogicTest { @InjectMocks private ResourceDataMergeBusinessLogic testInstance; @Mock - private ComponentInstanceInputsMergeBL instanceInputsValueMergeBLMock; + private ComponentsMergeCommand commandA; @Mock - private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBLMock; + private ComponentsMergeCommand commandB; @Mock - private ComponentInputsMergeBL inputsValueMergeBLMock; + private ComponentsMergeCommand commandC; @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + testInstance = new ResourceDataMergeBusinessLogic(Arrays.asList(commandA, commandB, commandC)); } @Test - public void mergeResourceInputs_allMergeClassesAreCalled() throws Exception { + public void mergeResources_allMergeClassesAreCalled() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.OK); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandB.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandC.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.OK, actionStatus); } @Test - public void mergeResourceInputs_failToMergeProperties_dontCallOtherMergeMethods() throws Exception { + public void mergeResources_mergeCommandFailed_dontCallOtherMergeMethods() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(instanceInputsValueMergeBLMock, inputsValueMergeBLMock); + verify(commandA).description(); + verifyZeroInteractions(commandB, commandC); } - @Test - public void mergeResourceInputs_failToMergeInstanceInputs_dontCallOtherMergeMethods() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(inputsValueMergeBLMock); - } - - @Test - public void mergeResourceInputs_failedToMergeInputs() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java new file mode 100644 index 0000000000..3131c4987c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java @@ -0,0 +1,328 @@ +package org.openecomp.sdc.be.components.merge.utils; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class MergeInstanceUtilsTest { + private MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Before + public void startUp() { + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent() { + Component container = new Service(); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci1 = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci1); + List<ComponentInstance> vfciList = Arrays.asList(vfci1); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfi1 = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + container.setComponentInstances(Arrays.asList(vfi1)); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + List<ComponentInstance> vfciList2 = Arrays.asList(vfci1); + vfNew.setComponentInstances(vfciList2); + + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfi1.getComponentUid())).thenReturn(eitherComponent); + + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, vfOld, "SRV1.VF2.VFI_1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + assertEquals("SRV1.VF1.VFI_1.VFC1.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent_Proxy() { + Resource container = new Resource(); + container.setComponentType(ComponentTypeEnum.RESOURCE); + container.setResourceType(ResourceTypeEnum.VF); + + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List<ComponentInstance> vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + container.setComponentInstances(Arrays.asList(proxyVfciNew)); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, serviceOld, "SRV1.PROXY_VFC_NEW.VFCI1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstanceComponentInstance() { + ComponentInstance oldInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(oldInstance); + + ComponentInstance newInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC2.VFCI_1" ,"SRV1.VF1.VFI_1.VFC2", false); + createVfc(newInstance); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, newInstance); + assertEquals("SRV1.VF1.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstComponentInst_Proxy() { + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List<ComponentInstance> vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + ComponentInstance proxyVfciOld = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + proxyVfciOld.setSourceModelUid("SRV_PROXY"); + Resource proxyVfcOld = new Resource(); + proxyVfcOld.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcOld.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent2 = Either.left(serviceOld); + when(toscaOperationFacade.getToscaElement(proxyVfciOld.getSourceModelUid())).thenReturn(eitherComponent2); + + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(proxyVfciOld, proxyVfciNew); + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + + @Test + public void testConvertToVfciNameMap() { + ComponentInstance componentInstance1 = new ComponentInstance(); + componentInstance1.setName("ComponentInstance1"); + + ComponentInstance componentInstance2 = new ComponentInstance(); + componentInstance2.setName("ComponentInstance2"); + + List<ComponentInstance> componentInstances = Arrays.asList(componentInstance1, componentInstance2); + Map<String, ComponentInstance> mapResult = mergeInstanceUtils.convertToVfciNameMap(componentInstances); + + assertEquals(2, mapResult.size()); + assertEquals(componentInstance1, mapResult.get("ComponentInstance1")); + assertEquals(componentInstance2, mapResult.get("ComponentInstance2")); + } + + @Test + public void testGetVfcInstances_NullComponentInstance() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadActualComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + componentInstance.setSourceModelUid("SRV_PROXY"); + + Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getSourceModelUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + + @Test + public void testGetVfcInstancesAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + + createVfc(componentInstance); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(1, vfcInstances.size()); + assertEquals(componentInstance, vfcInstances.get(0)); + } + + + @Test + public void testGetVfcInstancesNonAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Resource vf = new Resource(); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vf); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci); + List<ComponentInstance> vfciList = Arrays.asList(vfci); + + vf.setComponentInstances(vfciList); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(vfciList, vfcInstances); + } + + @Test + public void testGetVfcInstances_ComponentNullI_nstanceComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, new Resource()); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstance_NullComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(new ComponentInstance(), null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_NullComponentInstance_NullComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, null); + + assertTrue(vfcInstances.isEmpty()); + } + + + /** + * @param uniqueId + * @param componentUid + * @param isProxy + * @return + */ + private ComponentInstance createComponentInstance(String uniqueId, String componentUid, boolean isProxy) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setUniqueId(uniqueId); + componentInstance.setComponentUid(componentUid); + componentInstance.setIsProxy(isProxy); + return componentInstance; + } + + /** + * @param componentInstance + */ + private void createVfc(ComponentInstance componentInstance) { + Resource vfc = new Resource(); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfc); + vfc.setComponentType(ComponentTypeEnum.RESOURCE); + vfc.setResourceType(ResourceTypeEnum.VFC); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java new file mode 100644 index 0000000000..44f87bb352 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java @@ -0,0 +1,208 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import fj.data.Either; +import org.junit.Before; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.path.beans.TitanGraphTestSetup; +import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class BaseForwardingPathTest extends BeConfDependentTest implements ForwardingPathTestUtils { + + protected User user; + protected ForwardingPathDataDefinition forwardingPathDataDefinition; + + @Autowired + protected TitanGraphClient titanGraphClient; + + @Autowired + protected CapabiltyRequirementConvertor capabiltyRequirementConvertor; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @Autowired + protected ServiceBusinessLogic bl; + + @Autowired + protected IElementOperation elementDao; + + @Autowired + protected ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @javax.annotation.Resource + protected TitanDao titanDao; + + @Before + public void initTitan() { + TitanGraphTestSetup.createGraph(titanGraphClient.getGraph().left().value()); + categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(CATEGORY_NAME); + } + + @Before + public void initUser() { + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + } + + + protected CategoryDefinition categoryDefinition; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static final String CATEGORY_NAME = "cat_name"; + protected static final String FORWARDING_PATH_ID = "forwarding_pathId"; + protected static final String HTTP_PROTOCOL = "http"; + + + protected Resource setupGenericServiceMock() { + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected void initGraph() { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.abstract.nodes.service"); + + GraphTestUtils.createServiceVertex(titanDao, props); + + GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.PNF); + resourceVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "0.1"); + Either<GraphVertex, TitanOperationStatus> vertexTitanOperationStatusEither = titanDao.updateVertex(resourceVertex); + assertTrue(vertexTitanOperationStatusEither.isLeft()); + } + + protected Service createTestService() { + createCategory(); + createServiceCategory(CATEGORY_NAME); + initGraph(); + Service service = new Service(); + service.setName("ForwardingPathTestingService"); + service.setDescription("Just a comment."); + service.setTags(Lists.newArrayList(service.getName(), service.getComponentType().getValue() + service.getName() + "2")); + service.setContactId("as123y"); + service.setIcon("MyIcon"); + service.setProjectCode("414155"); + ArrayList<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition cd = new CategoryDefinition(); + cd.setName(CATEGORY_NAME); + cd.setNormalizedName("abcde"); + categories.add(cd); + service.setCategories(categories); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_APPROVED); + return service; + } + + protected void createCategory() { + Either<CategoryDefinition, ActionStatus> category = elementDao.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory); + assertTrue("Failed to create category", category.isLeft()); + } + + protected void createServiceCategory(String categoryName) { + GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); + + assertTrue(catRes.isLeft()); + } + + protected Service initForwardPath() { + ForwardingPathDataDefinition forwardingPathDataDefinition = createMockPath(); + Service service = new Service(); + service.setUniqueId(FORWARDING_PATH_ID); + assertEquals(null, service.addForwardingPath(forwardingPathDataDefinition)); + return service; + } + + protected ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null) { + return forwardingPathDataDefinition; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol(HTTP_PROTOCOL); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode", "toNode", "333", "444", "2222", "5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode", "toNode2", "4444", "44444", "4", "44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } + + protected Service createService() { + Either<Service, ResponseFormat> serviceCreateResult = bl.createService(createTestService(), user); + assertTrue("Failed to create service", serviceCreateResult.isLeft()); + Service service = serviceCreateResult.left().value(); +// ComponentInstance componentInstance = new ComponentInstance(); +// componentInstance.setName("Test1"); +// componentInstance.setNormalizedName("Test1"); +// componentInstance.setUniqueId("Test1"); +// componentInstance.setInputValueCounter(1); +// componentInstance.setAttributeValueCounter(1); +// componentInstance.setIcon("network"); +// componentInstance.setComponentVersion("1.0"); +// componentInstance.setIsProxy(true); +// componentInstance.setComponentUid(service.getUniqueId()); +// componentInstance.setPropertyValueCounter(1); +// componentInstance.setPosX("333"); +// componentInstance.setPosY("333"); +// componentInstance.setOriginType(OriginTypeEnum.VF); +// +// Either<ComponentInstance, ResponseFormat> instanceResult = serviceComponentInstanceBusinessLogic.createComponentInstance("services", service.getUniqueId(), user.getUserId(), componentInstance); +// assertTrue("Failed to create instance", instanceResult.isLeft()); + return service; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java new file mode 100644 index 0000000000..0e56680728 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import org.junit.Before; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class BaseForwardingPathVersionChangeTest { + protected Service service; + protected ComponentInstance nodeACI; + protected ComponentInstance newNodeACI; + protected Component newNodeAC; + protected Component newNodeWithoutCapability; + protected DataForMergeHolder dataHolder; + protected static final String nodeA = "nodeA"; + protected static final String NODE_A_FORWARDER_CAPABILITY = "nodeA_FORWARDER_CAPABILITY"; + protected static final String nodeB = "nodeB"; + protected static final String newNodeA = "newNodeA"; + protected static final String fpName = "fpName"; + protected static final String FPId = "1122"; + + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, NODE_A_FORWARDER_CAPABILITY, "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put(FPId, forwardingPath); + service.setForwardingPaths(forwardingPaths); + nodeACI = new ComponentInstance(); + initComponentInstance(nodeACI, nodeA); + newNodeACI = new ComponentInstance(); + initComponentInstance(newNodeACI, newNodeA); + newNodeAC = new Resource(); + newNodeWithoutCapability=new Resource(); + initComponent(newNodeAC, newNodeA); + service.setComponentInstances(Lists.newArrayList(newNodeACI)); + initComponentWithoutForwarder(newNodeWithoutCapability,"newNodeC"); + service.setComponentInstances(Lists.newArrayList(nodeACI)); + + dataHolder = new DataForMergeHolder(); + dataHolder.setOrigComponentInstId(nodeA); + } + + private void initComponent(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + + private void initComponentWithoutForwarder(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilitesWithoutForwarder(); + component.setCapabilities(capabilities); + } + + private HashMap<String, List<CapabilityDefinition>> initCapabilites() { + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition forwarder = new CapabilityDefinition(); + forwarder.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + forwarder.setUniqueId(NODE_A_FORWARDER_CAPABILITY); + capabilities.put("bla bla", Arrays.asList(forwarder)); + return capabilities; + } + + private HashMap<String, List<CapabilityDefinition>> initCapabilitesWithoutForwarder() { + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setType("tosca.capabilities.Node"); + capabilityDefinition.setUniqueId("tosca capability"); + capabilities.put("bla bla", Arrays.asList(capabilityDefinition)); + return capabilities; + } + + private void initComponentInstance(ComponentInstance component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java new file mode 100644 index 0000000000..03bbc31aef --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java @@ -0,0 +1,107 @@ + +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathBussinessLogicTest extends BaseForwardingPathTest { + + + @Test + public void shouldFailToUpdateForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either<Service, ResponseFormat> serviceResponseFormatEither = bl.updateForwardingPath(FORWARDING_PATH_ID, service, user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldFailToDeleteForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either<Set<String>, ResponseFormat> serviceResponseFormatEither = bl.deleteForwardingPaths("delete_forward_test", Sets.newHashSet(FORWARDING_PATH_ID), user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldSucceedCreateAndDeleteForwardingPath() { + Service createdService = createService(); + Service service = initForwardPath(); + assertNotNull(service); + Either<Service, ResponseFormat> serviceResponseFormatEither = bl.createForwardingPath(createdService.getUniqueId(), service, user, true); + assertEquals(true, serviceResponseFormatEither.isLeft()); + Map<String, ForwardingPathDataDefinition> forwardingPathsMap = serviceResponseFormatEither.left().value().getForwardingPaths(); + Set<String> pathIds = forwardingPathsMap.keySet(); + assertEquals(1, pathIds.size()); + String toscaResourceName = forwardingPathsMap.values().iterator().next().getToscaResourceName(); + + // should return the created path + Either<UiComponentDataTransfer, ResponseFormat> uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map<String, ForwardingPathDataDefinition> forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths.keySet().equals(pathIds)); + Map<String, ForwardingPathDataDefinition> updatedForwardingPaths = new HashMap<>(forwardingPaths); + String newProtocol = "https"; + ForwardingPathDataDefinition forwardingPathDataDefinition = updatedForwardingPaths.values().stream().findAny().get(); + assertEquals(forwardingPathDataDefinition.getProtocol(), HTTP_PROTOCOL); + assertEquals(toscaResourceName, forwardingPathDataDefinition.getToscaResourceName()); + ForwardingPathDataDefinition forwardingPathDataDefinitionUpdate = updatedForwardingPaths.values().iterator().next(); + // updated values + forwardingPathDataDefinitionUpdate.setProtocol(newProtocol); + forwardingPathDataDefinitionUpdate.setPathElements(new ListDataDefinition<>()); + + // should update value + service.getForwardingPaths().clear(); + service.getForwardingPaths().put(forwardingPathDataDefinitionUpdate.getUniqueId(), forwardingPathDataDefinitionUpdate); + serviceResponseFormatEither = bl.updateForwardingPath(createdService.getUniqueId(), service, user, true); + assertTrue(serviceResponseFormatEither.isLeft()); + + // make sure changes were applied + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map<String, ForwardingPathDataDefinition> forwardingPathsUpdated = uiServiceDataTransfer.getForwardingPaths(); + ForwardingPathDataDefinition updatedData = forwardingPathsUpdated.values().iterator().next(); + assertEquals(newProtocol, updatedData.getProtocol()); + assertTrue(updatedData.getPathElements().isEmpty()); + + Service createdData = serviceResponseFormatEither.left().value(); + Set<String> paths = createdData.getForwardingPaths().keySet(); + Either<Set<String>, ResponseFormat> setResponseFormatEither = bl.deleteForwardingPaths(createdService.getUniqueId(), paths, user, true); + assertEquals(true, setResponseFormatEither.isLeft()); + + // nothing to return now + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.COMPONENT_INSTANCES.getValue(),ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths == null || forwardingPaths.isEmpty()); + + } + + + + +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java new file mode 100644 index 0000000000..5af94d7938 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.components.path; + +import org.javatuples.Pair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +public class ForwardingPathChangeVersionTest extends BaseForwardingPathVersionChangeTest { + + + @Test + public void updateForwardingPath() { + Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map<String, ForwardingPathDataDefinition> updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(1, updated.size()); + assertEquals(newNodeA, updated.values().iterator().next().getPathElements().getListToscaDataDefinition().get(0).getFromNode()); + Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(0, deleted.size()); + } + + @Test + public void deleteForwardingPath(){ + newNodeAC.setCapabilities(new HashMap<>()); + Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map<String, ForwardingPathDataDefinition> updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(0, updated.size()); + + Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(1, deleted.size()); + assertEquals(FPId, deleted.keySet().stream().findAny().get()); + } + + @Test + public void fetchPathsToBeDeletedZeroPaths(){ + Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeAC); + assertEquals(0,data.size()); + } + + @Test + public void fetchPathsToBeDeleted(){ + Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeWithoutCapability); + assertEquals(1,data.size()); + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java new file mode 100644 index 0000000000..e5de493cb1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ForwardingPathDeleteCITest { + + private Service service; + private static final String nodeA = "nodeA"; + private static final String nodeB = "nodeB"; + private static final String fpName = "fpName"; + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, "nodeAcpType", "nodeBcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeB, "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + } + + + @Test + public void getListToDelete() { + + Set<String> forwardingPathNamesToDeleteOnComponenetInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeA); + assertEquals(1, forwardingPathNamesToDeleteOnComponenetInstanceDeletion.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + Set<String> forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeB); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(1, forwardingPathNamesToDeleteOnCIDelete.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, "Does not exist"); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(0, forwardingPathNamesToDeleteOnCIDelete.size()); + assertFalse(forwardingPathNamesToDeleteOnCIDelete.contains(fpName)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java new file mode 100644 index 0000000000..9ab9ffd788 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.components.path; + +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; + +public interface ForwardingPathTestUtils { + + default ForwardingPathDataDefinition createPath(String pathName, String protocol, String ports, String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber(ports); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java new file mode 100644 index 0000000000..e7100a4a7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java @@ -0,0 +1,186 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDER; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PORTS_RANGE; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PROTOCOL; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.addForwardingPaths; + +/** + * @author KATYR, ORENK + * @since November 19, 2017 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathToscaUtilTest extends BaseForwardingPathTest { + + private static final String NODE_NAME_1 = "nodeA-name"; + private static final String NODE_NAME_2 = "nodeB-name"; + private static final String PATH_1_PROTOCOL = "protocol-path1"; + private static final String PATH_1_DESC = "path1-desc"; + private static final String PATH_1_PORTS = "8585"; + private static final String PATH_1_NAME = "pathName1"; + private Service service; + private Map<String, Component> originComponents = new HashMap<>(); + private static final String NODE_ID_1 = "nodeA-id"; + private static final String NODE_ID_2 = "nodeB-id"; + private static final String FORWARDING_PATH_TOSCA_TYPE = "org.openecomp.nodes.ForwardingPath"; + + + @Before + public void setUpForwardingPath() { + service = initForwardPath(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(generateComponentInstance(NODE_NAME_1, NODE_ID_1)); + componentInstances.add(generateComponentInstance(NODE_NAME_2, NODE_ID_2)); + service.setComponentInstances(componentInstances); + } + + private ComponentInstance generateComponentInstance(String name, String uuid) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setName(name); + componentInstance.setUniqueId(uuid); + componentInstance.setComponentUid(uuid); + Map<String, List<CapabilityDefinition>> capabiltiesMap = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setMinOccurrences(Integer.toString(1)); + capabilityDefinition.setMaxOccurrences(Integer.toString(100)); + capabilityDefinition.setType(ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME); + capabilityDefinition.setName(name); + capabilityDefinition.setUniqueId(name); + capabilityDefinition.setPath(Arrays.asList("Just", "something", "to", "read")); + capabiltiesMap.put(capabilityDefinition.getName(), + Collections.singletonList(capabilityDefinition)); + componentInstance.setCapabilities(capabiltiesMap); + Resource resource = new Resource(); + resource.setToscaResourceName("test"); + originComponents.put(uuid, resource); + return componentInstance; + } + + + @Test + public void singleElementPath() { + createPathSingleElement(); + Map<String, ToscaNodeTemplate> nodeTemplatesRes = new HashMap<>(); + + Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes = new HashMap<>(); + ToscaNodeTemplate pathEntry = new ToscaNodeTemplate(); + pathEntry.setType(FORWARDING_PATH_TOSCA_TYPE); + Map<String, Object> expectedProps = new HashMap<>(); + expectedProps.put(PORTS_RANGE, Collections.singletonList(PATH_1_PORTS)); + expectedProps.put(PROTOCOL, PATH_1_PROTOCOL); + pathEntry.setProperties(expectedProps); + List<Map<String, ToscaTemplateRequirement>> requirements = new ArrayList<>(); + ToscaTemplateRequirement firstEntryReq = new ToscaTemplateRequirement(); + ToscaTemplateRequirement secondEntryReq = new ToscaTemplateRequirement(); + + firstEntryReq.setCapability("null." + NODE_NAME_1); + secondEntryReq.setCapability("null." + NODE_NAME_2); + + firstEntryReq.setNode(NODE_NAME_1); + secondEntryReq.setNode(NODE_NAME_2); + + firstEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + secondEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + + Map<String, ToscaTemplateRequirement> entryMap1 = new HashMap<>(); + Map<String, ToscaTemplateRequirement> entryMap2 = new HashMap<>(); + + entryMap1.put(FORWARDER, firstEntryReq); + entryMap2.put(FORWARDER, secondEntryReq); + + requirements.add(entryMap1); + requirements.add(entryMap2); + + pathEntry.setRequirements(requirements); + expectedNodeTemplatesRes.put(PATH_1_NAME, pathEntry); + addForwardingPaths(service, nodeTemplatesRes, capabiltyRequirementConvertor, originComponents, + toscaOperationFacade); + + assertEquals(2, nodeTemplatesRes.get(PATH_1_NAME).getRequirements().size()); + compareToscaPathEntry(expectedNodeTemplatesRes, nodeTemplatesRes); + } + + private void compareToscaPathEntry(Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes, + Map<String, ToscaNodeTemplate> nodeTemplatesRes) { + final ToscaNodeTemplate expectedTemplate = expectedNodeTemplatesRes.get(PATH_1_NAME); + final ToscaNodeTemplate actualTemplate = nodeTemplatesRes.get(PATH_1_NAME); + assertEquals(expectedTemplate.getProperties(), actualTemplate.getProperties()); + final int size = expectedTemplate.getRequirements().size(); + assertEquals(size, + actualTemplate.getRequirements().size()); + for (int i = 0; i < size; i++) { + compareToscaRequirement(expectedTemplate, actualTemplate, i); + } + } + + private void compareToscaRequirement(ToscaNodeTemplate expectedTemplate, + ToscaNodeTemplate actualTemplate, + int i) { + final ToscaTemplateRequirement actualRequirement = + actualTemplate.getRequirements().get(i).get(FORWARDER); + final ToscaTemplateRequirement expectedToscaRequirement = expectedTemplate + .getRequirements() + .get(i).get(FORWARDER); + assertEquals(actualRequirement.getCapability(), expectedToscaRequirement.getCapability()); + assertEquals(actualRequirement.getNode(), expectedToscaRequirement.getNode()); + } + + private void createPathSingleElement() { + ForwardingPathElementDataDefinition element1 = initElement(NODE_ID_1, NODE_ID_2, NODE_NAME_1, + NODE_NAME_2); + + ListDataDefinition<ForwardingPathElementDataDefinition> list = new ListDataDefinition<>(); + list.add(element1); + + + ForwardingPathDataDefinition path = new ForwardingPathDataDefinition(); + path.setDescription(PATH_1_DESC); + path.setProtocol(PATH_1_PROTOCOL); + path.setDestinationPortNumber(PATH_1_PORTS); + path.setToscaResourceName(FORWARDING_PATH_TOSCA_TYPE); + path.setPathElements(list); + path.setName(PATH_1_NAME); + + Map<String, ForwardingPathDataDefinition> paths = new HashMap<>(); + paths.put(PATH_1_NAME, path); + + service.setForwardingPaths(paths); + } + + private ForwardingPathElementDataDefinition initElement(String fromId, String toId, String + fromCP, String toCP) { + ForwardingPathElementDataDefinition element = new ForwardingPathElementDataDefinition(); + element.setFromCP(fromCP); + element.setFromNode(fromId); + element.setToCP(toCP); + element.setToNode(toId); + return element; + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java new file mode 100644 index 0000000000..fd9e25f475 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java @@ -0,0 +1,151 @@ +package org.openecomp.sdc.be.components.path; + + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; +import java.util.Set; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +public class ForwardingPathValidatorTest implements ForwardingPathTestUtils { + + ResponseFormatManager mock; + + private Service service = (Service) getToscaFullElement().left().value(); + + + @Mock + ToscaOperationFacade toscaOperationFacade; + @InjectMocks + ForwardingPathValidationUtilTest test = new ForwardingPathValidationUtilTest(); + + private static final String SERVICE_ID = "serviceid1"; + + + + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + mock = Mockito.mock(ResponseFormatManager.class); + when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(mock.getResponseFormat(any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any(), any())).thenReturn(new ResponseFormat()); + + } + + @Test + public void testValidForwardingPathName(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName", "http", "8285", "pathName"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isLeft()); + } + + @Test + public void testEmptyForwardingPathName(){ + Collection<ForwardingPathDataDefinition> paths = createData("", "protocol", "8285", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + } + + @Test + public void testLongForwardingPathName(){ + String pathName = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData(pathName, + "http", "port", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testUniqueForwardingPathNameUpdateName(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName4", "httpfd", "82df85", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testUniqueForwardingPathNameUpdatePort(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName3", "httpfd", "82df85", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testLongForwardingPathPortNumber(){ + String port = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData("pathName", + "http", port, "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testLongForwardingPathProtocol(){ + String protocol = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData("pathName", + protocol, "port", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + private Set<ForwardingPathDataDefinition> createData(String pathName, String protocol, String ports, String uniqueId) { + + return Sets.newHashSet(createPath(pathName, protocol, ports, uniqueId)); + } + + + private <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement() { + + return Either.left((T) setUpServiceMcok()); + } + + private Service setUpServiceMcok(){ + Service service = new Service(); + service.addForwardingPath(createPath("pathName3", "http", "8285", "name1")); + return service; + } + + private class ForwardingPathValidationUtilTest extends ForwardingPathValidator { + + protected ResponseFormatManager getResponseFormatManager() { + return mock; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java new file mode 100644 index 0000000000..290ba07883 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("artifact-cassandra-dao") +public class ArtifactCassandraDaoMock extends ArtifactCassandraDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java new file mode 100644 index 0000000000..c4885e1f07 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("audit-cassandra-dao") +public class AuditCassandraDaoMock extends AuditCassandraDao{ + + @PostConstruct + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java new file mode 100644 index 0000000000..0d4b2f1e7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.cassandra.CassandraClient; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.springframework.stereotype.Component; + +@Component("cassandra-client") +public class CassandraClientMock extends CassandraClient{ + public CassandraClientMock() { + + } + + @Override + public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) { + return null; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java new file mode 100644 index 0000000000..6a9731e86d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.ComponentCacheAccessor; +import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao; +import org.openecomp.sdc.be.resources.data.ComponentCacheData; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component("component-cassandra-dao") +public class ComponentCassandraDaoMock extends ComponentCassandraDao { + + public static Integer DEFAULT_FETCH_SIZE = 500; + private ComponentCacheAccessor componentCacheAccessor; + + public ComponentCassandraDaoMock() { + super(); + } + + @PostConstruct + public void init() { + + } + + public Either<List<ComponentCacheData>, ActionStatus> getComponents(List<String> ids) { + + return null; + } + + public Either<List<ComponentCacheData>, ActionStatus> getAllComponentIdTimeAndType() { + return null; + } + + + public Either<ComponentCacheData, ActionStatus> getComponent(String id) { + + return null; + } + + public CassandraOperationStatus saveComponent(ComponentCacheData componentCacheData) { + return null; + } + + + public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) { + return null; + } + + + public Either<ImmutablePair<List<ComponentCacheData>, Set<String>>, ActionStatus> getComponents( + Map<String, Long> idToTimestampMap) { + + return null; + } + + public CassandraOperationStatus deleteComponent(String id) { + return null; + } + + } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java new file mode 100644 index 0000000000..748ae56bd7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java @@ -0,0 +1,61 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +public class DistributionEngineMock implements IDistributionEngine { + @Override + public boolean isActive() { + return false; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + return null; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable(String envName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable() { + return null; + } + + @Override + public void disableEnvironment(String envName) { + + } + + @Override + public StorageOperationStatus isReadyForDistribution(Service service, String envName) { + return null; + } + + @Override + public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) { + return null; + } + + @Override + public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) { + return null; + } + + @Override + public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) { + return null; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java new file mode 100644 index 0000000000..2d7b1ad287 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("operational-environment-dao") +public class EnvironmentCassandraDaoMock extends OperationalEnvironmentDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java new file mode 100644 index 0000000000..09e1a72b44 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +@org.springframework.stereotype.Component("tosca-operation-facade") +public class ForwardingPathToscaOperationFacade extends ToscaOperationFacade { + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + @Override + public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return Either.left(setupGenericServiceMock()); + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + @Override + public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { + if(resourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || resourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByName(resourceName); + } + + @Override + public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { + if(toscaResourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || toscaResourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByToscaResourceName(toscaResourceName); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java new file mode 100644 index 0000000000..1aa3ab8102 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; + +public class ForwardingPathValidatorMock extends ForwardingPathValidator { + @Override + public Either<Boolean, ResponseFormat> validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths, String serviceId, + boolean isUpdate) { + return Either.left(Boolean.TRUE); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java new file mode 100644 index 0000000000..4e3923d2ea --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java @@ -0,0 +1,218 @@ +package org.openecomp.sdc.be.components.path.beans; + + +import com.thinkaurelius.titan.core.InvalidElementException; +import com.thinkaurelius.titan.core.InvalidIDException; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.QueryException; +import com.thinkaurelius.titan.core.SchemaViolationException; +import com.thinkaurelius.titan.core.TitanConfigurationException; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import com.thinkaurelius.titan.core.util.TitanCleanup; +import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; +import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; +import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; + +@Component("titan-client") +public class InMemoryTitanGraphClient extends TitanGraphClient { + + + private static final Logger logger = LoggerFactory.getLogger(InMemoryTitanGraphClient.class); + + private static final String OK = "GOOD"; + + public InMemoryTitanGraphClient() { + } + + + private TitanGraph graph; + TitanClientStrategy titanClientStrategy; + + public InMemoryTitanGraphClient(TitanClientStrategy titanClientStrategy) { + super(); + this.titanClientStrategy = titanClientStrategy; + logger.info("** TitanGraphClient created"); + } + + @PostConstruct + public TitanOperationStatus createGraph() { + + logger.info("** createGraph started **"); + graph = TitanFactory.build().set("storage.backend", "inmemory").open(); + createTitanSchema(); + + logger.info("** in memory graph created"); + return TitanOperationStatus.OK; + + } + + + public void cleanupGraph() { + if (graph != null) { + // graph.shutdown(); + graph.close(); + TitanCleanup.clear(graph); + } + } + + public TitanOperationStatus createGraph(String titanCfgFile) { + logger.info("** open graph with {} started", titanCfgFile); + try { + logger.info("openGraph : try to load file {}", titanCfgFile); + graph = TitanFactory.open(titanCfgFile); + if (graph.isClosed()) { + logger.error("titan graph was not initialized"); + return TitanOperationStatus.NOT_CREATED; + } + + } catch (Exception e) { + this.graph = null; + logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); + return TitanOperationStatus.NOT_CONNECTED; + } + + logger.info("** Titan graph created "); + + return TitanOperationStatus.OK; + } + + + public Either<TitanGraph, TitanOperationStatus> getGraph() { + if (graph != null) { + return Either.left(graph); + } else { + return Either.right(TitanOperationStatus.NOT_CREATED); + } + } + + public TitanOperationStatus commit() { + if (graph != null) { + try { + graph.tx().commit(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public TitanOperationStatus rollback() { + if (graph != null) { + try { + // graph.rollback(); + graph.tx().rollback(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public static TitanOperationStatus handleTitanException(Exception e) { + if (e instanceof TitanConfigurationException) { + return TitanOperationStatus.TITAN_CONFIGURATION; + } + if (e instanceof SchemaViolationException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof PermanentLockingException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof IDPoolExhaustedException) { + return TitanOperationStatus.GENERAL_ERROR; + } + if (e instanceof InvalidElementException) { + return TitanOperationStatus.INVALID_ELEMENT; + } + if (e instanceof InvalidIDException) { + return TitanOperationStatus.INVALID_ID; + } + if (e instanceof QueryException) { + return TitanOperationStatus.INVALID_QUERY; + } + if (e instanceof ResourceUnavailableException) { + return TitanOperationStatus.RESOURCE_UNAVAILABLE; + } + if (e instanceof IllegalArgumentException) { + // TODO check the error message?? + return TitanOperationStatus.ILLEGAL_ARGUMENT; + } + + return TitanOperationStatus.GENERAL_ERROR; + } + + public boolean getHealth() { + return true; + } + + private boolean isGraphOpen() { + return true; + } + + + private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; + + + private void createTitanSchema() { + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class<?> clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java new file mode 100644 index 0000000000..4e0105f067 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("sdc-schema-files-cassandra-dao") +public class SdcSchemaFilesCassandraDaoMock extends SdcSchemaFilesCassandraDao { + + @PostConstruct + @Override + public void init() { + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java new file mode 100644 index 0000000000..7a7eff879a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java @@ -0,0 +1,166 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanGraphQuery; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class TitanGraphTestSetup { + + + private static final Logger logger = LoggerFactory.getLogger(TitanGraphTestSetup.class); + + private static TitanGraph graph; + + public static boolean createGraph( TitanGraph graph) { + TitanGraphTestSetup.graph = graph; + createIndexesAndDefaults(); + + logger.info("** Titan graph created "); + + return true; + } + + private static boolean isVertexExist(Map<String, Object> properties) { + TitanGraphQuery query = graph.query(); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry<String, Object> entry : properties.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable<Vertex> vertecies = query.vertices(); + java.util.Iterator<Vertex> iterator = vertecies.iterator(); + if (iterator.hasNext()) { + return true; + } + return false; + } + + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); + graph.tx().commit(); + + } + + private static void createUser(UserData user) { + Map<String, Object> checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map<String, Object> properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry<String, Object> entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private static UserData getDefaultUserAdmin() { + UserData userData = new UserData(); + userData.setAction(ActionEnum.Create); + userData.setElementType(GraphElementTypeEnum.Node); + userData.setUserId("jh0003"); + userData.setEmail("admin@sdc.com"); + userData.setFirstName("Jimmy"); + userData.setLastName("Hendrix"); + userData.setRole("ADMIN"); + userData.setStatus(UserStatusEnum.ACTIVE.name()); + userData.setLastLoginTime(0L); + return userData; + } + + + private static void createVertexIndixes() { + logger.info("** createVertexIndixes started"); + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class<?> clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + logger.info("** createVertexIndixes ended"); + + } + + private static void createEdgeIndixes() { + logger.info("** createEdgeIndixes started"); + TitanManagement graphMgt = graph.openManagement(); + for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); + + } + } + graphMgt.commit(); + logger.info("** createEdgeIndixes ended"); + } + + private static void createIndexesAndDefaults() { + createVertexIndixes(); + createEdgeIndixes(); + createDefaultAdminUser(); + createRootCatalogVertex(); + } + private static void createRootCatalogVertex(){ + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); + vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()); + graph.tx().commit(); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java new file mode 100644 index 0000000000..79a1dab517 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 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.openecomp.sdc.be.components.path.utils; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +public final class GraphTestUtils { + + public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) { + GraphVertex vertex = new GraphVertex(); + if (type == ResourceTypeEnum.VF) { + vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + } else { + vertex.setLabel(VertexTypeEnum.NODE_TYPE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); + } + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); + vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); + for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static GraphVertex createServiceVertex(TitanDao titanDao, Map<GraphPropertyEnum, Object> metadataProps){ + GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + String uuid = UUID.randomUUID().toString(); + + vertex.setUniqueId(uuid); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static void clearGraph(TitanDao titanDao) { + Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } + + public static String exportGraphMl(TitanGraph graph, String outputDirectory) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + graph.tx().commit(); + } catch (Exception e) { + graph.tx().rollback(); + e.printStackTrace(); + } + return result; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java new file mode 100644 index 0000000000..9bd04d6da3 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java @@ -0,0 +1,238 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstancePropertyDeceleratorTest extends PropertyDeceleratorTestBase { + + private static final String INSTANCE_ID = "inst1"; + private static final String RESOURCE_ID = "resource1"; + + @InjectMocks + private ComponentInstancePropertyDecelerator testInstance; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Captor + private ArgumentCaptor<Map<String, List<ComponentInstanceProperty>>> instancePropertiesCaptor; + private Resource resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithInstance(); + } + + @Test + public void declarePropertiesAsInputs_componentInstanceNotExist() { + Component cmpt = new Resource(); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(cmpt, "someCmptInstId", Collections.emptyList()); + assertThat(createdInputs.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void declarePropertiesAsInputs_singleNonComplexProperty() { + List<PropertyDataDefinition> properties = Collections.singletonList(prop1); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_multipleNonComplexProperty() { + List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_singleComplexProperty() { + PropertyDefinition innerProp1 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP1) + .setValue("true") + .setType("boolean") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + PropertyDefinition innerProp2 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP2) + .setValue("abc") + .setType("string") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + List<ComponentInstancePropInput> propsToDeclare = createComplexPropInputList(innerProp1, innerProp2); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + + verifyCreatedInputsFromComplexProperty(propsToDeclare, capturedInstanceProperties, inputs); + verifyUpdatedComplexProperty(capturedInstanceProperties, inputs); + } + + private void verifyUpdatedProperties(List<PropertyDataDefinition> properties, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(capturedInstanceProperties).hasSize(properties.size()); + Map<String, ComponentInstanceProperty> updatedPropertiesByName = MapUtil.toMap(capturedInstanceProperties, ComponentInstanceProperty::getName); + properties.forEach(prop -> verifyUpdatedInstanceProperty(prop, updatedPropertiesByName.get(prop.getName()), inputs)); + } + + private void verifyUpdatedComplexProperty(List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(capturedInstanceProperties).hasSize(1); + verifyUpdatedInstanceComplexProperty(capturedInstanceProperties.get(0), inputs); + } + + private void verifyCreatedInputs(List<PropertyDataDefinition> originalPropsToDeclare, List<ComponentInstanceProperty> capturedUpdatedProperties, List<InputDefinition> inputs) { + assertThat(inputs).hasSize(originalPropsToDeclare.size()); + Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(inputs, InputDefinition::getPropertyId); + originalPropsToDeclare.forEach(propToDeclare -> verifyCreatedInput(propToDeclare, propertyIdToCreatedInput.get(propToDeclare.getUniqueId()))); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyCreatedInputsFromComplexProperty(List<ComponentInstancePropInput> propsToDeclare, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(inputs).hasSize(propsToDeclare.size()); + Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + propsToDeclare.forEach(propToDeclare -> verifyCreatedInputFromComplexProperty(propToDeclare, inputsByName)); + Map<String, List<InputDefinition>> propertyIdToCreatedInput = MapUtil.groupListBy(inputs, InputDefinition::getPropertyId); + capturedInstanceProperties.forEach(updatedProperty -> verifyInputPropertiesListFromComplexProperty(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyInputPropertiesListFromComplexProperty(ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) { + inputs.forEach(input -> verifyInputPropertiesList(updatedProperty, input)); + } + + private void verifyCreatedInputFromComplexProperty(ComponentInstancePropInput parentProperty, Map<String, InputDefinition> inputsByName) { + PropertyDefinition innerProperty = parentProperty.getInput(); + String expectedInputName = generateExpectedInputName(parentProperty, innerProperty); + InputDefinition input = inputsByName.get(expectedInputName); + assertThat(input.getType()).isEqualTo(innerProperty.getType()); + assertThat(input.getValue()).isEqualTo(innerProperty.getValue()); +// assertThat(input.getDefaultValue()).isEqualTo(innerProperty.getValue());//bug + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(parentProperty.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + + } + + private void verifyInputPropertiesList(ComponentInstanceProperty updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(updatedProperty).isEqualTo(input.getProperties().get(0)); + } + + + private List<ComponentInstancePropInput> createComplexPropInputList(PropertyDefinition ... innerProperties) { + return Stream.of(innerProperties).map(this::createComplexPropInput).collect(Collectors.toList()); + } + + private ComponentInstancePropInput createComplexPropInput(PropertyDefinition innerProp) { + ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput(new ComponentInstanceProperty(complexProperty)); + componentInstancePropInput.setInput(innerProp); + componentInstancePropInput.setPropertiesName(complexProperty.getName() + "#" + innerProp.getName()); + return componentInstancePropInput; + } + + private void verifyUpdatedInstanceProperty(PropertyDataDefinition originalProperty, ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) { + assertThat(updatedProperty.getValue()).isEqualTo(generateGetInputValue(generateExpectedInputName(originalProperty))); + assertThat(updatedProperty.isGetInputProperty()).isTrue(); + assertThat(updatedProperty.getName()).isEqualTo(originalProperty.getName()); + List<GetInputValueDataDefinition> getInputValues = updatedProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyUpdatedInstanceComplexProperty(ComponentInstanceProperty updatedComplexProperty, List<InputDefinition> inputs) { + assertThat(updatedComplexProperty.getValue()).isEqualTo(generateComplexGetInputValue(inputs)); + assertThat(updatedComplexProperty.isGetInputProperty()).isTrue(); + assertThat(updatedComplexProperty.getName()).isEqualTo(complexProperty.getName()); + List<GetInputValueDataDefinition> getInputValues = updatedComplexProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyGetInputValues(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs) { + Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + getInputValues.forEach(getInputVal -> { + InputDefinition input = inputsByName.get(getInputVal.getInputName()); + assertThat(input.getUniqueId()).isEqualTo(getInputVal.getInputId()); + }); + } + + private String generateComplexGetInputValue(List<InputDefinition> createdInputs) { + return String.format("{\"%s\":%s,\"%s\":%s}", INNER_PROP1, generateGetInputValue(createdInputs.get(0).getName()), INNER_PROP2, generateGetInputValue(createdInputs.get(1).getName())); + } + + private String generateExpectedInputName(PropertyDataDefinition prop) { + return INSTANCE_ID + "_" + prop.getName(); + } + + private String generateExpectedInputName(PropertyDefinition parentProp, PropertyDefinition innerProperty) { + return INSTANCE_ID + "_" + parentProp.getName()+ "_" + innerProperty.getName(); + } + + private void verifyCreatedInput(PropertyDataDefinition property, InputDefinition input) { + assertThat(input.getType()).isEqualTo(property.getType()); + assertThat(input.getName()).isEqualTo(generateExpectedInputName(property)); + assertThat(input.getValue()).isEqualTo(property.getValue()); + assertThat(input.getDefaultValue()).isEqualTo(property.getValue()); + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(property.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + } + + private Resource createResourceWithInstance() { + ComponentInstance inst1 = new ComponentInstanceBuilder() + .setId(INSTANCE_ID) + .setNormalizedName(INSTANCE_ID) + .build(); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .addComponentInstance(inst1) + .build(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java new file mode 100644 index 0000000000..cd454d5a84 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java @@ -0,0 +1,172 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +//note that testing for most of the common logic is under the ComponentInstancePropertyDeceleratorTest +public class PolicyPropertyDeceleratorTest extends PropertyDeceleratorTestBase{ + + private static final String POLICY_ID = "policyId"; + private static final String RESOURCE_ID = "resourceId"; + private static final String INPUT_ID = "inputId"; + @InjectMocks + private PolicyPropertyDecelerator policyPropertyDecelerator; + @Mock + private PolicyOperation policyOperation; + @Mock + private PropertyOperation propertyOperation; + @Captor + private ArgumentCaptor<List<PropertyDataDefinition>> updatedPropsCapture; + private Resource resource; + private InputDefinition input; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithPolicy(); + input = new InputDefinition(); + input.setUniqueId(INPUT_ID); + input.setName(INPUT_ID); + input.setValue("value"); + } + + @Test + public void testDeclarePropertiesAsInputs_policyNotExist() { + Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, "nonExistingPolicy", Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testDeclarePropertiesAsInputs_failedToUpdateProperties() { + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testDeclarePropertiesAsInputs() { + List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, propsToDeclare); + List<InputDefinition> inputs = createdInputs.left().value(); + assertThat(inputs).hasSize(2); + verifyInputPropertiesList(inputs, updatedPropsCapture.getValue()); + //creation of inputs values is part of the DefaultPropertyDecelerator and is tested in the ComponentInstancePropertyDeceleratorTest class + } + + @Test + public void testUnDeclareProperties_whenComponentHasNoPolicies_returnOk() { + Resource resource = new Resource(); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testUnDeclareProperties_whenNoPropertiesFromPolicyMatchInputId_returnOk() { + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(createResourceWithPolicy(), input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void whenFailingToUpdateDeclaredProperties_returnErrorStatus() { + Resource resource = createResourceWithPolicies(POLICY_ID); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + policyDefinition.setProperties(Collections.singletonList(getInputPropForInput)); + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testUnDeclareProperties_propertiesUpdatedCorrectly() { + Resource resource = createResourceWithPolicies(POLICY_ID, "policyId2"); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + PropertyDataDefinition someOtherProperty = new PropertyDataDefinitionBuilder().build(); + policyDefinition.setProperties(Arrays.asList(getInputPropForInput, someOtherProperty)); + + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + List<PropertyDataDefinition> updatedProperties = updatedPropsCapture.getValue(); + assertThat(updatedProperties).hasSize(1); + PropertyDataDefinition updatedProperty = updatedProperties.get(0); + assertThat(updatedProperty.isGetInputProperty()).isFalse(); + assertThat(updatedProperty.getValue()).isEmpty(); + assertThat(updatedProperty.getDefaultValue()).isEqualTo(getInputPropForInput.getDefaultValue()); + assertThat(updatedProperty.getUniqueId()).isEqualTo(getInputPropForInput.getUniqueId()); + } + + private Resource createResourceWithPolicy() { + return createResourceWithPolicies(POLICY_ID); + } + + private Resource createResourceWithPolicies(String ... policies) { + List<PolicyDefinition> policiesDef = Stream.of(policies) + .map(this::buildPolicy) + .collect(Collectors.toList()); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setPolicies(policiesDef) + .build(); + } + + private PolicyDefinition buildPolicy(String policyId) { + return PolicyDefinitionBuilder.create() + .setUniqueId(policyId) + .setName(policyId) + .build(); + } + + private PropertyDataDefinition buildGetInputProperty(String inputId) { + return new PropertyDataDefinitionBuilder() + .addGetInputValue(inputId) + .setUniqueId(POLICY_ID + "_" + inputId) + .setDefaultValue("defaultValue") + .setValue(generateGetInputValue(inputId)) + .build(); + } + + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java new file mode 100644 index 0000000000..0c761a948d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java @@ -0,0 +1,69 @@ +package org.openecomp.sdc.be.components.property; + +import org.junit.Before; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; + +public class PropertyDeceleratorTestBase { + + static final String INNER_PROP1 = "ecomp_generated_naming"; + static final String INNER_PROP2 = "naming_policy"; + PropertyDataDefinition prop1, prop2, complexProperty; + + @Before + public void setUp() throws Exception { + prop1 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop1") + .setType("string") + .setName("prop1") + .setValue("value1") + .build(); + + prop2 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop2") + .setType("string") + .setSchemaType("string") + .setName("prop2") + .setValue("[\"a\", \"b\"]") + .build(); + + complexProperty = new PropertyDataDefinitionBuilder() + .setUniqueId("prop3") + .setType("org.openecomp.type1") + .setName("prop3") + .setValue("{\"ecomp_generated_naming\":true\",\"naming_policy\":\"abc\"}") + .build(); + + } + + List<ComponentInstancePropInput> createInstancePropInputList(List<PropertyDataDefinition> properties) { + return properties.stream().map(prop -> new ComponentInstancePropInput(new ComponentInstanceProperty(prop))) + .collect(Collectors.toList()); + } + + void verifyInputPropertiesList(List<InputDefinition> createdInputs, List<PropertyDataDefinition> capturedUpdatedProperties) { + Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(createdInputs, InputDefinition::getPropertyId); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + String generateGetInputValue(String value) { + return String.format("{\"%s\":\"%s\"}", GET_INPUT, value); + } + + private void verifyInputPropertiesList(PropertyDataDefinition updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(new ComponentInstanceProperty(updatedProperty)).isEqualTo(input.getProperties().get(0)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java new file mode 100644 index 0000000000..56aef5d923 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java @@ -0,0 +1,138 @@ +package org.openecomp.sdc.be.components.scheduledtasks; + +import fj.data.Either; +import org.apache.commons.lang.math.NumberUtils; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; +import org.openecomp.sdc.be.components.scheduledtasks.RecoveryThreadManager.FixEnvironmentTask; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.datastructure.Wrapper; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class RecoveryThreadManagerTest extends BeConfDependentTest { + + @InjectMocks + RecoveryThreadManager recoveryThreadManager = new RecoveryThreadManager(); + + private OperationalEnvironmentDao operationalEnvironmentDao = mock(OperationalEnvironmentDao.class); + private EnvironmentsEngine environmentsEngine = mock(EnvironmentsEngine.class); + private ScheduledExecutorService scheduledService = mock(ScheduledExecutorService.class); + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + reset(operationalEnvironmentDao, environmentsEngine, scheduledService); + recoveryThreadManager.init(); + } + + @Test + public void testInit() { + verify(scheduledService, Mockito.times(1)).scheduleAtFixedRate(recoveryThreadManager.task, + NumberUtils.LONG_ZERO, 180L, TimeUnit.SECONDS); + + } + @SuppressWarnings("unchecked") + @Test + public void testTaskNoRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskCassandraCrash() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherResult = Either.right(CassandraOperationStatus.GENERAL_ERROR); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(eitherResult); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskMultipleFailedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockEntry = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> nonEmptyList = Either.left(Arrays.asList(mockEntry, mockEntry, mockEntry)); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(nonEmptyList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskStaleRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockFailedEntryFirst = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockFailedEntrySecond = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> failedRecordsList = Either.left(Arrays.asList(mockFailedEntryFirst, mockFailedEntrySecond)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(failedRecordsList); + + OperationalEnvironmentEntry mockInProgressNonStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockInProgressStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 /2)).when(mockInProgressNonStaleEntry).getLastModified(); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 * 2)).when(mockInProgressStaleEntry).getLastModified(); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> inProgressList = Either.left(Arrays.asList(mockInProgressNonStaleEntry, mockInProgressStaleEntry)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(inProgressList); + fixEnvironmentTask.run(); + + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntryFirst)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntrySecond)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressStaleEntry)); + verify(environmentsEngine, times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressNonStaleEntry)); + + verify(environmentsEngine, times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + + + @Test + public void testUnconnectedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockCompleteConnected = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockCompleteUnconnected = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> completeRecordsList = Either.left(Arrays.asList(mockCompleteConnected, mockCompleteUnconnected)); + when(environmentsEngine.isInMap(mockCompleteConnected)).thenReturn(true); + when(environmentsEngine.isInMap(mockCompleteUnconnected)).thenReturn(false); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(completeRecordsList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(Either.left(Arrays.asList())); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(Either.left(Arrays.asList())); + fixEnvironmentTask.run(); + + verify(environmentsEngine).createUebTopicsForEnvironment(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).createUebTopicsForEnvironment(mockCompleteConnected); + verify(environmentsEngine).addToMap(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).addToMap(mockCompleteConnected); + verify(environmentsEngine, times(1)).createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java index 55a119e078..32e3f9c10a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.ArrayList; + public class ArtifactBuilder { private ArtifactDefinition artifactDefinition; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java new file mode 100644 index 0000000000..4c137551dc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java @@ -0,0 +1,51 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +import java.util.ArrayList; + +public class CapabilityDefinitionBuilder { + + private CapabilityDefinition capabilityDefinition; + + public CapabilityDefinitionBuilder() { + capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setProperties(new ArrayList<>()); + } + + public CapabilityDefinitionBuilder addProperty(ComponentInstanceProperty property) { + capabilityDefinition.getProperties().add(property); + return this; + } + + public CapabilityDefinitionBuilder setOwnerId(String ownerId) { + capabilityDefinition.setOwnerId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setOwnerName(String ownerName) { + capabilityDefinition.setOwnerName(ownerName); + return this; + } + + public CapabilityDefinitionBuilder setType(String type) { + capabilityDefinition.setType(type); + return this; + } + + public CapabilityDefinitionBuilder setId(String ownerId) { + capabilityDefinition.setUniqueId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setName(String name) { + capabilityDefinition.setName(name); + return this; + } + + + public CapabilityDefinition build() { + return capabilityDefinition; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java new file mode 100644 index 0000000000..490140dac0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java @@ -0,0 +1,155 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public abstract class ComponentBuilder<T extends Component, B extends ComponentBuilder<T, B>> { + + private T component; + + protected abstract T component(); + + protected abstract ComponentBuilder<T, B> self(); + + public ComponentBuilder() { + this.component = component(); + } + + public ComponentBuilder(T component) { + this.component = component; + } + + public ComponentBuilder<T, B> setUniqueId(String id) { + component.setUniqueId(id); + return self(); + } + + public ComponentBuilder<T, B> setLifeCycleState(LifecycleStateEnum lifeCycleState) { + component.setLifecycleState(lifeCycleState); + return self(); + } + + public ComponentBuilder<T, B> setLastUpdaterUserId(String lastUpdater) { + component.setLastUpdaterUserId(lastUpdater); + return self(); + } + + public ComponentBuilder<T, B> setInvariantUUid(String invariantUUid) { + component.setInvariantUUID(invariantUUid); + return self(); + } + + public ComponentBuilder<T, B> setName(String name) { + component.setName(name); + return self(); + } + + public ComponentBuilder<T, B> setComponentType(ComponentTypeEnum type) { + component.setComponentType(type); + return self(); + } + + public ComponentBuilder<T, B> setSystemName(String systemName) { + component.setSystemName(systemName); + return self(); + } + + public ComponentBuilder<T, B> addComponentInstance(ComponentInstance componentInstance) { + if (component.getComponentInstances() == null) { + component.setComponentInstances(new ArrayList<>()); + } + component.getComponentInstances().add(componentInstance); + return self(); + } + + public ComponentBuilder<T, B> addInput(InputDefinition input) { + if (component.getInputs() == null) { + component.setInputs(new ArrayList<>()); + } + component.getInputs().add(input); + return self(); + } + + public ComponentBuilder<T, B> addInput(String inputName) { + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setName(inputName); + inputDefinition.setUniqueId(inputName); + this.addInput(inputDefinition); + return self(); + } + + public ComponentBuilder<T, B> addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { + if (component.getComponentInstancesProperties() == null) { + component.setComponentInstancesProperties(new HashMap<>()); + } + component.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder<T, B> addInstanceProperty(String instanceId, String propName) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); + componentInstanceProperty.setName(propName); + this.addInstanceProperty(instanceId, componentInstanceProperty); + return self(); + } + + public ComponentBuilder<T, B> addInstanceInput(String instanceId, ComponentInstanceInput prop) { + if (component.getComponentInstancesInputs() == null) { + component.setComponentInstancesInputs(new HashMap<>()); + } + component.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder<T, B> addInstanceInput(String instanceId, String propName) { + ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); + componentInstanceInput.setName(propName); + this.addInstanceInput(instanceId, componentInstanceInput); + return self(); + } + + public ComponentBuilder<T, B> addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { + if (component.getComponentInstancesRelations() == null) { + component.setComponentInstancesRelations(new ArrayList<>()); + } + component.getComponentInstancesRelations().add(requirementCapabilityRelDef); + return self(); + } + + public ComponentBuilder<T, B> addPolicy(PolicyDefinition policyDefinition) { + if (component.getPolicies() == null) { + component.setPolicies(new HashMap<>()); + } + component.getPolicies().put(policyDefinition.getUniqueId(), policyDefinition); + return self(); + } + public ComponentBuilder<T, B> addGroups(GroupDefinition groupDefinition){ + if(component.getGroups() == null){ + component.setGroups(new ArrayList<>()); + } + component.getGroups().add(groupDefinition); + return self(); + } + + public ComponentBuilder<T, B> setPolicies(List<PolicyDefinition> policies) { + component.setPolicies(MapUtil.toMap(policies, PolicyDefinition::getUniqueId)); + return self(); + } + + public T build() { + return component; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java index a99f08c20d..f461806010 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java @@ -1,17 +1,25 @@ package org.openecomp.sdc.be.components.utils; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.stream.Stream; + public class ComponentInstanceBuilder { private ComponentInstance componentInstance; public ComponentInstanceBuilder() { componentInstance = new ComponentInstance(); + componentInstance.setCapabilities(new HashMap<>()); + componentInstance.setDeploymentArtifacts(new HashMap<>()); + } + + public ComponentInstanceBuilder(ComponentInstance componentInstance) { + this.componentInstance = componentInstance; } public ComponentInstanceBuilder setName(String name) { @@ -19,6 +27,16 @@ public class ComponentInstanceBuilder { return this; } + public ComponentInstanceBuilder setNormalizedName(String name) { + componentInstance.setNormalizedName(name); + return this; + } + + public ComponentInstanceBuilder setUniqueId(String uniqueId) { + componentInstance.setUniqueId(uniqueId); + return this; + } + public ComponentInstanceBuilder setComponentUid(String componentUid) { componentInstance.setComponentUid(componentUid); return this; @@ -35,14 +53,20 @@ public class ComponentInstanceBuilder { } public ComponentInstanceBuilder addDeploymentArtifact(ArtifactDefinition artifactDefinition) { - Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (deploymentArtifacts == null) { - componentInstance.setDeploymentArtifacts(new HashMap<>()); - } componentInstance.getDeploymentArtifacts().put(artifactDefinition.getArtifactName(), artifactDefinition); return this; } + public ComponentInstanceBuilder addCapability(CapabilityDefinition capabilityDefinition) { + componentInstance.getCapabilities().computeIfAbsent(capabilityDefinition.getType(), key -> new ArrayList<>()).add(capabilityDefinition); + return this; + } + + public ComponentInstanceBuilder addCapabilities(CapabilityDefinition ... capabilities) { + Stream.of(capabilities).forEach(this::addCapability); + return this; + } + public ComponentInstance build() { return componentInstance; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java new file mode 100644 index 0000000000..d8cfa2cb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +public class ComponentInstancePropertyBuilder extends PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> { + + @Override + protected PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> self() { + return this; + } + + @Override + ComponentInstanceProperty propertyDefinition() { + return new ComponentInstanceProperty(); + } + + @Override + public ComponentInstanceProperty build() { + return propertyDefinition; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java new file mode 100644 index 0000000000..d7deaa423a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupDefinition; + +import java.util.HashMap; +import java.util.Map; + +public class GroupDefinitionBuilder { + private GroupDefinition groupDefinition; + + private GroupDefinitionBuilder() { + this.groupDefinition = new GroupDefinition(); + } + + public static GroupDefinitionBuilder create() { + return new GroupDefinitionBuilder(); + } + + public GroupDefinitionBuilder setUniqueId(String uid) { + groupDefinition.setUniqueId(uid); + return this; + } + + public GroupDefinition build() { + return groupDefinition; + } + + public GroupDefinitionBuilder addMember(String memberName, String memberId) { + Map<String, String> members = groupDefinition.getMembers(); + if (members == null) { + members = new HashMap<>(); + groupDefinition.setMembers(members); + } + members.put(memberId, memberId); + return this; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java new file mode 100644 index 0000000000..719967fd6b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupTypeDefinition; + +public class GroupTypeBuilder { + + private GroupTypeDefinition groupTypeDataDefinition; + + public static GroupTypeBuilder create() { + return new GroupTypeBuilder(); + } + + private GroupTypeBuilder() { + this.groupTypeDataDefinition = new GroupTypeDefinition(); + } + + public GroupTypeBuilder setType(String type) { + groupTypeDataDefinition.setType(type); + return this; + } + + public GroupTypeBuilder setUniqueId(String uid) { + groupTypeDataDefinition.setUniqueId(uid); + return this; + } + + public GroupTypeBuilder setVersion(String version) { + groupTypeDataDefinition.setVersion(version); + return this; + } + + public GroupTypeBuilder setDerivedFrom(String derivedFrom) { + groupTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public GroupTypeDefinition build() { + return groupTypeDataDefinition; + } + + + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java index 3a99d54ffa..249cf69112 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java @@ -1,11 +1,5 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -15,6 +9,12 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + public class ObjectGenerator { public static Resource buildResourceWithInputs(String ... inputNames) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java new file mode 100644 index 0000000000..b6aa96e7d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.Set; + +public class OperationalEnvironmentBuilder { + + private OperationalEnvironmentEntry operationalEnvironmentEntry; + + public OperationalEnvironmentBuilder() { + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + } + + public OperationalEnvironmentBuilder setEnvId(String envId) { + operationalEnvironmentEntry.setEnvironmentId(envId); + return this; + } + + public OperationalEnvironmentBuilder setDmaapUebAddress(Set<String> addresses) { + operationalEnvironmentEntry.setDmaapUebAddress(addresses); + return this; + } + + public OperationalEnvironmentBuilder setStatus(EnvironmentStatusEnum status) { + operationalEnvironmentEntry.setStatus(status); + return this; + } + + public OperationalEnvironmentEntry build() { + return operationalEnvironmentEntry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java new file mode 100644 index 0000000000..f818c04ccd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PolicyDefinitionBuilder { + + private PolicyDefinition policyDefinition; + + private PolicyDefinitionBuilder() { + this.policyDefinition = new PolicyDefinition(); + } + + public static PolicyDefinitionBuilder create() { + return new PolicyDefinitionBuilder(); + } + + public PolicyDefinitionBuilder setName(String name) { + policyDefinition.setName(name); + return this; + } + + public PolicyDefinitionBuilder setUniqueId(String uid) { + policyDefinition.setUniqueId(uid); + return this; + } + + public PolicyDefinitionBuilder setProperties(PropertyDataDefinition ... props) { + policyDefinition.setProperties(Arrays.asList(props)); + return this; + } + + public PolicyDefinitionBuilder setTargets(Map<PolicyTargetType, List<String>> targets ){ + policyDefinition.setTargets(targets); + return this; + } + + public PolicyDefinitionBuilder addComponentInstanceTarget(String instId) { + Map<PolicyTargetType, List<String>> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.COMPONENT_INSTANCES, k -> new ArrayList<>()) + .add(instId); + return this; + } + + public PolicyDefinitionBuilder addGroupTarget(String groupId) { + Map<PolicyTargetType, List<String>> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.GROUPS, k -> new ArrayList<>()).add(groupId); + return this; + } + + public PolicyDefinition build() { + return policyDefinition; + } + + private Map<PolicyTargetType, List<String>> getTargets() { + Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets(); + if (targets == null) { + targets = new HashMap<>(); + policyDefinition.setTargets(targets); + } + return targets; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java new file mode 100644 index 0000000000..8c2b54f27e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.components.utils; + + +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +import java.util.List; +import java.util.Map; + +public class PolicyTypeBuilder { + + private PolicyTypeDefinition policyTypeDataDefinition; + + public PolicyTypeBuilder() { + this.policyTypeDataDefinition = new PolicyTypeDefinition(); + } + + public PolicyTypeBuilder setType(String type) { + policyTypeDataDefinition.setType(type); + return this; + } + + public PolicyTypeBuilder setUniqueId(String uid) { + policyTypeDataDefinition.setUniqueId(uid); + return this; + } + + public PolicyTypeBuilder setDerivedFrom(String derivedFrom) { + policyTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public PolicyTypeBuilder setVersion(String version) { + policyTypeDataDefinition.setVersion(version); + return this; + } + + public PolicyTypeBuilder setDescription(String version) { + policyTypeDataDefinition.setDescription(version); + return this; + } + + public PolicyTypeBuilder setTargets(List<String> targets) { + policyTypeDataDefinition.setTargets(targets); + return this; + } + + public PolicyTypeBuilder setMetadata(Map<String, String> metadata) { + policyTypeDataDefinition.setMetadata(metadata); + return this; + } + + public PolicyTypeBuilder setModificationTime(long modificationTime) { + policyTypeDataDefinition.setModificationTime(modificationTime); + return this; + } + + public PolicyTypeBuilder setCreationTime(long creationTime) { + policyTypeDataDefinition.setModificationTime(creationTime); + return this; + } + + public PolicyTypeBuilder setOwner(String owner) { + policyTypeDataDefinition.setOwnerId(owner); + return this; + } + + public PolicyTypeBuilder setHighestVersion(boolean isHighestVersion) { + policyTypeDataDefinition.setHighestVersion(isHighestVersion); + return this; + } + + public PolicyTypeBuilder setProperties(List<PropertyDefinition> properties) { + policyTypeDataDefinition.setProperties(properties); + return this; + } + + public PolicyTypeDefinition build() { + return policyTypeDataDefinition; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java new file mode 100644 index 0000000000..9d5d71d67c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java @@ -0,0 +1,94 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; + +import java.util.ArrayList; + +public abstract class PropertyDataDefinitionAbstractBuilder<B extends PropertyDataDefinition, T extends PropertyDataDefinitionAbstractBuilder<B, T>> { + + B propertyDefinition; + + protected abstract PropertyDataDefinitionAbstractBuilder<B, T> self(); + + abstract B propertyDefinition(); + + PropertyDataDefinitionAbstractBuilder() { + propertyDefinition = propertyDefinition(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setUniqueId(String id) { + this.propertyDefinition.setUniqueId(id); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setName(String name) { + this.propertyDefinition.setName(name); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setValue(String value) { + this.propertyDefinition.setValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setDefaultValue(String value) { + this.propertyDefinition.setDefaultValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setType(String type) { + this.propertyDefinition.setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setOwnerId(String ownerId) { + this.propertyDefinition.setOwnerId(ownerId); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setSchemaType(String type) { + if (propertyDefinition.getSchema() == null) { + propertyDefinition.setSchema(new SchemaDefinition()); + } + if (propertyDefinition.getSchema().getProperty() == null) { + propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); + } + propertyDefinition.getSchema().getProperty().setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> addGetInputValue(String inputName) { + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputName(inputName); + getInputValueDataDefinition.setInputId(inputName); + if (propertyDefinition.getGetInputValues() == null) { + propertyDefinition.setGetInputValues(new ArrayList<>()); + } + propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setIsRequired(boolean required) { + this.propertyDefinition.setRequired(required); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setDescription(String description) { + this.propertyDefinition.setDescription(description); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setIsPassword(boolean isPassword) { + this.propertyDefinition.setRequired(isPassword); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setStatus(String status) { + this.propertyDefinition.setStatus(status); + return self(); + } + + public abstract B build(); +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java index e7ed170414..85b2228933 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java @@ -1,68 +1,29 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; -public class PropertyDataDefinitionBuilder { - - private PropertyDefinition propertyDefinition; - - public PropertyDataDefinitionBuilder() { - propertyDefinition = new PropertyDefinition(); - } - - public PropertyDataDefinitionBuilder setUniqueId(String id) { - this.propertyDefinition.setUniqueId(id); - return this; - } - - public PropertyDataDefinitionBuilder setName(String name) { - this.propertyDefinition.setName(name); - return this; - } +import java.util.List; - public PropertyDataDefinitionBuilder setValue(String value) { - this.propertyDefinition.setValue(value); - return this; - } +public class PropertyDataDefinitionBuilder extends PropertyDataDefinitionAbstractBuilder<PropertyDefinition, PropertyDataDefinitionBuilder> { - public PropertyDataDefinitionBuilder setDefaultValue(String value) { - this.propertyDefinition.setDefaultValue(value); + protected PropertyDataDefinitionBuilder self() { return this; } - public PropertyDataDefinitionBuilder setType(String type) { - this.propertyDefinition.setType(type); - return this; + @Override + PropertyDefinition propertyDefinition() { + return new PropertyDefinition(); } - public PropertyDataDefinitionBuilder setSchemaType(String type) { - if (propertyDefinition.getSchema() == null) { - propertyDefinition.setSchema(new SchemaDefinition()); - } - if (propertyDefinition.getSchema().getProperty() == null) { - propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); - } - propertyDefinition.getSchema().getProperty().setType(type); - return this; + @Override + public PropertyDefinition build() { + return propertyDefinition; } - public PropertyDataDefinitionBuilder addGetInputValue(String inputName) { - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputName(inputName); - getInputValueDataDefinition.setInputId(inputName); - if (propertyDefinition.getGetInputValues() == null) { - propertyDefinition.setGetInputValues(new ArrayList<>()); - } - propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); - return this; + public PropertyDataDefinitionBuilder setConstraints(List<PropertyConstraint> constraints) { + propertyDefinition.setConstraints(constraints); + return self(); } - public PropertyDefinition build() { - return propertyDefinition; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java index 8c457f153f..e0d35c6b6a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.components.utils; -import java.util.Collections; - import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; import org.openecomp.sdc.be.model.RelationshipImpl; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import java.util.Collections; + public class RelationsBuilder { private RequirementCapabilityRelDef relation; @@ -16,8 +16,8 @@ public class RelationsBuilder { RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(); RelationshipImpl relationship = new RelationshipImpl(); requirementAndRelationshipPair.setRelationships(relationship); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(requirementAndRelationshipPair); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(requirementAndRelationshipPair); relation.setRelationships(Collections.singletonList(capReqRel)); } @@ -27,17 +27,17 @@ public class RelationsBuilder { } public RelationsBuilder setRequirementName(String reqName) { - relation.getSingleRelationship().getRelation().setRequirement(reqName); + relation.resolveSingleRelationship().getRelation().setRequirement(reqName); return this; } public RelationsBuilder setRelationType(String type) { - relation.getSingleRelationship().getRelation().getRelationship().setType(type); + relation.resolveSingleRelationship().getRelation().getRelationship().setType(type); return this; } public RelationsBuilder setCapabilityUID(String uid) { - relation.getSingleRelationship().getRelation().setCapabilityUid(uid); + relation.resolveSingleRelationship().getRelation().setCapabilityUid(uid); return this; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java index 3d4a29da71..25468af3c9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java @@ -1,79 +1,26 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.HashMap; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; -public class ResourceBuilder { - - private Resource resource; - - public ResourceBuilder() { - this.resource = new Resource(); - } - - public ResourceBuilder(Resource resource) { - this.resource = resource; - } - - public ResourceBuilder setUniqueId(String id) { - resource.setUniqueId(id); - return this; - } - - public ResourceBuilder setInvariantUUid(String invariantUUid) { - resource.setInvariantUUID(invariantUUid); - return this; - } - - public ResourceBuilder setName(String name) { - resource.setName(name); - return this; - } - - public ResourceBuilder setComponentType(ComponentTypeEnum type) { - resource.setComponentType(type); - return this; - } +import java.util.ArrayList; - public ResourceBuilder setSystemName(String systemName) { - resource.setSystemName(systemName); - return this; - } +public class ResourceBuilder extends ComponentBuilder<Resource, ResourceBuilder> { - public ResourceBuilder addComponentInstance(ComponentInstance componentInstance) { - if (resource.getComponentInstances() == null) { - resource.setComponentInstances(new ArrayList<>()); - } - resource.getComponentInstances().add(componentInstance); - return this; - } + private Resource resource; - public ResourceBuilder addInput(InputDefinition input) { - if (resource.getInputs() == null) { - resource.setInputs(new ArrayList<>()); - } - resource.getInputs().add(input); - return this; + @Override + protected Resource component() { + resource = new Resource(); + return resource; } - public ResourceBuilder addInput(String inputName) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setName(inputName); - inputDefinition.setUniqueId(inputName); - this.addInput(inputDefinition); + @Override + protected ComponentBuilder<Resource, ResourceBuilder> self() { return this; } - public ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { + ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { if (resource.getProperties() == null) { resource.setProperties(new ArrayList<>()); } @@ -81,46 +28,14 @@ public class ResourceBuilder { return this; } - public ResourceBuilder addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { - if (resource.getComponentInstancesProperties() == null) { - resource.setComponentInstancesProperties(new HashMap<>()); - } - resource.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - - public ResourceBuilder addInstanceProperty(String instanceId, String propName) { - ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); - componentInstanceProperty.setName(propName); - this.addInstanceProperty(instanceId, componentInstanceProperty); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, ComponentInstanceInput prop) { - if (resource.getComponentInstancesInputs() == null) { - resource.setComponentInstancesInputs(new HashMap<>()); - } - resource.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, String propName) { - ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); - componentInstanceInput.setName(propName); - this.addInstanceInput(instanceId, componentInstanceInput); - return this; + public ResourceBuilder() { + super(); } - public ResourceBuilder addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { - if (resource.getComponentInstancesRelations() == null) { - resource.setComponentInstancesRelations(new ArrayList<>()); - } - resource.getComponentInstancesRelations().add(requirementCapabilityRelDef); - return this; + public ResourceBuilder(Resource resource) { + super(resource); } - - public Resource build() { - return resource; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java new file mode 100644 index 0000000000..d85ad9bcc2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.Service; + +public class ServiceBuilder extends ComponentBuilder<Service, ServiceBuilder> { + + private Service service; + + public ServiceBuilder(Service component) { + super(component); + } + + public ServiceBuilder() { + super(); + } + + @Override + protected Service component() { + service = new Service(); + return service; + } + + @Override + protected ComponentBuilder<Service, ServiceBuilder> self() { + return this; + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java new file mode 100644 index 0000000000..be19e8b795 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.be.components.utils; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UtilsTest { + + @Test + public void testThatEmptyListReturns0() { + List<String> existingResourceNames = new ArrayList<>(); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isZero(); + } + + @Test + public void testListWithValidValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithInvalidSingleValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithValidValues() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..2"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } + + @Test + public void testListWithInvalidValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java new file mode 100644 index 0000000000..df48a538a5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java @@ -0,0 +1,153 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class ServiceDistributionValidationTest { + + private static final String USER_ID = "userId"; + private static final String SERVICE_ID = "serviceId"; + private static final String ENV_ID = "envId"; + + @InjectMocks + private ServiceDistributionValidation testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + + @Mock + private IDistributionEngine distributionEngine; + + @Mock + private ComponentsUtils componentsUtils; + + private User user; + private Service service; + private OperationalEnvironmentEntry operationalEnvironmentEntry; + private ResponseFormat errResponse; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId(USER_ID); + errResponse = new ResponseFormat(); + service = new Service(); + service.setUniqueId(SERVICE_ID); + service.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.COMPLETED); + } + + @Test + public void validateActivateServiceRequest_userNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.right(errResponse)); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(toscaOperationFacade, operationalEnvironmentDao, componentsUtils); + } + + @Test + public void validateActivateServiceRequest_ServiceNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR, ComponentTypeEnum.SERVICE)).thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_ServiceLifeCycleStateNotReadyForDistribution() { + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_operationalEnvNotExist() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(null); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_operationalEnvStatusNotComplete() { + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_couldNotParseDistributionData() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo()); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_distributionDataHasNoWorkloadContext() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_requestValid() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("context")); + assertEquals(service, activateServiceReq.left().value().getServiceToActivate()); + assertEquals("context", activateServiceReq.left().value().getWorkloadContext()); + } +}
\ No newline at end of file |