diff options
author | Julien Bertozzi <julien.bertozzi@intl.att.com> | 2021-01-07 12:19:52 +0100 |
---|---|---|
committer | Vasyl Razinkov <vasyl.razinkov@est.tech> | 2021-01-12 23:45:13 +0000 |
commit | b7015a8154af46dc6be7643256d95d961ab6c040 (patch) | |
tree | c933485f9b1b3d0b62c35b1c4c017ba3e987baae | |
parent | 69779180f8f4e020606634f9bd8cac728daed2a2 (diff) |
Improve test coverage
Issue-ID: SDC-3428
Signed-off-by: JulienBe <julien.bertozzi@intl.att.com>
Change-Id: I48b6991fbbea31279246d92692760fc6375c7eb5
Signed-off-by: JulienBe <julien.bertozzi@intl.att.com>
7 files changed, 355 insertions, 557 deletions
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/SdcResourceIconMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/SdcResourceIconMigrationTest.java index 172b8a63f2..f54592da08 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/SdcResourceIconMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/SdcResourceIconMigrationTest.java @@ -145,21 +145,20 @@ public class SdcResourceIconMigrationTest { verify(janusGraphDao, times(2)).commit(); } - // A temp remark for this test - following Commit hash: 08595ad21b0c409c69e3902232f5575963199e3e [ASDC-641] – Migration workaround for deployment artifact timeout. Reviewer: Lior. -// @Test -// public void migrationFailedWhenInstanceVertexUpdateFailed() { -// mockInstancesFoundFlow(); -// when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.TOPOLOGY_TEMPLATE), eq(null), anyMap(), eq(JsonParseFlagEnum.ParseAll))) -// .thenReturn(Either.left(Lists.newArrayList(topologyTemplateVertex))); -// when(compositionDataDefinition.getComponentInstances()).thenReturn(Maps.newHashMap("a", componentInstanceDataDefinition)); -// doReturn(Maps.newHashMap(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition)).when(topologyTemplateVertex).getJson(); -// when(janusGraphDao.updateVertex(any(GraphVertex.class))).thenReturn(Either.left(graphVertex)) -// .thenReturn(Either.left(graphVertex)) -// .thenReturn(Either.right(JanusGraphOperationStatus.GENERAL_ERROR)); -// -// assertEquals(MigrationResult.MigrationStatus.FAILED, iconMigration.migrate().getMigrationStatus()); -// verify(janusGraphDao, times(2)).commit(); -// } + @Test + public void migrationFailedWhenInstanceVertexUpdateFailed() { + mockInstancesFoundFlow(); + when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.TOPOLOGY_TEMPLATE), eq(null), anyMap(), eq(JsonParseFlagEnum.ParseAll))) + .thenReturn(Either.left(Lists.newArrayList(topologyTemplateVertex))); + when(compositionDataDefinition.getComponentInstances()).thenReturn(Maps.newHashMap("a", componentInstanceDataDefinition)); + doReturn(Maps.newHashMap(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition)).when(topologyTemplateVertex).getJson(); + when(janusGraphDao.updateVertex(any(GraphVertex.class))).thenReturn(Either.left(graphVertex)) + .thenReturn(Either.left(graphVertex)) + .thenReturn(Either.right(JanusGraphOperationStatus.GENERAL_ERROR)); + + assertEquals(MigrationResult.MigrationStatus.COMPLETED, iconMigration.migrate().getMigrationStatus()); + verify(janusGraphDao, times(2)).commit(); + } @Test public void migrationCompletedWhenVertexJsonIsEmpty() { 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 4d773a54da..55a73c6f3b 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 @@ -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. @@ -45,6 +45,7 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.servlet.ServletContext; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Assert; import org.junit.Before; @@ -89,16 +90,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.facade.operations.CatalogOperation; 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.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -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.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; @@ -127,30 +119,22 @@ 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.ArtifactTypeEnum; -import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; public class ResourceBusinessLogicTest { private final ConfigurationManager configurationManager = new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be")); - private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class); private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; private static final String RESOURCE_SUBCATEGORY = "Router"; private static final String UPDATED_SUBCATEGORY = "Gateway"; - private String resourceId = "resourceId1"; - private String operationId = "uniqueId1"; - Resource resourceUpdate; - private static final String RESOURCE_NAME = "My-Resource_Name with space"; private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name"; private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root"; @@ -160,7 +144,7 @@ public class ResourceBusinessLogicTest { final ServletContext servletContext = Mockito.mock(ServletContext.class); IElementOperation mockElementDao; - JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); + JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); @@ -174,8 +158,8 @@ public class ResourceBusinessLogicTest { WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); UserValidations userValidations = Mockito.mock(UserValidations.class); WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); + IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); IElementOperation elementDao = new ElementOperationMock(); CsarUtils csarUtils = Mockito.mock(CsarUtils.class); @@ -228,7 +212,7 @@ public class ResourceBusinessLogicTest { protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils); protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade); private ComponentValidator componentValidator = createComponentValidator(); - private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class); + private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class); private ComponentValidator createComponentValidator() { List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator, @@ -239,8 +223,6 @@ public class ResourceBusinessLogicTest { } ResourceBusinessLogic bl; - public ResourceBusinessLogicTest() { - } @Before public void setup() { @@ -280,18 +262,6 @@ public class ResourceBusinessLogicTest { 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, - when(interfaceOperation.updateInterface(anyString(), anyObject())).thenReturn(Either.left(InterfaceOperationTestUtils.mockInterfaceDefinitionToReturn(RESOURCE_NAME))); - * 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("tosca.nodes.Root")).thenReturn(validateDerivedExists); @@ -309,7 +279,7 @@ public class ResourceBusinessLogicTest { when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK); Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>(); when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); // BL object artifactManager.setNodeTemplateOperation(nodeTemplateOperation); @@ -325,18 +295,19 @@ public class ResourceBusinessLogicTest { bl.setCapabilityTypeOperation(capabilityTypeOperation); bl.setComponentsUtils(componentsUtils); bl.setLifecycleManager(lifecycleBl); - bl.setGraphLockOperation(graphLockOperation); bl.setArtifactsManager(artifactManager); + bl.setGraphLockOperation(graphLockOperation); bl.setPropertyOperation(propertyOperation); - bl.setJanusGraphDao(mockJanusGraphDao); + bl.setJanusGraphDao(mockJanusGraphDao); bl.setApplicationDataTypeCache(applicationDataTypeCache); bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); bl.setCatalogOperations(catalogOperation); toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); + csarBusinessLogic.setComponentsUtils(componentsUtils); toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); bl.setToscaOperationFacade(toscaOperationFacade); bl.setUserValidations(userValidations); - bl.setInterfaceTypeOperation(interfaceTypeOperation); + bl.setInterfaceTypeOperation(interfaceTypeOperation); csarBusinessLogic.setCsarOperation(csarOperation); Resource resourceCsar = createResourceObjectCsar(true); @@ -351,18 +322,62 @@ public class ResourceBusinessLogicTest { bl.setComponentContactIdValidator(componentContactIdValidator); bl.setComponentProjectCodeValidator(componentProjectCodeValidator); bl.setComponentValidator(componentValidator); - reslist = new ArrayList<Resource>(); - reslist.add(resourceResponse); - reslist.add(genericVF); - reslist.add(genericCR); - reslist.add(genericVFC); - reslist.add(genericPNF); - Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist); - when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval); - when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true)); - Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST); - when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception); + reslist = new ArrayList<>(); + reslist.add(resourceResponse); + reslist.add(genericVF); + reslist.add(genericCR); + reslist.add(genericVFC); + reslist.add(genericPNF); + Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist); + when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval); + when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true)); + Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST); + when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception); + } + + @Test(expected = ComponentException.class) + public void createResourcesFromYamlNodeTypesList() throws IOException { + Map<String, Object> mappedToscaTemplate = new HashMap<>(); + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>(); + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>(); + Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>(); + bl.createResourcesFromYamlNodeTypesList( + "", + resourceResponse, + mappedToscaTemplate, + false, + nodeTypesArtifactsToHandle, + nodeTypesNewCreatedArtifacts, + nodeTypesInfo, + new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"),true)); + } + + @Test + public void handleNodeTypeArtifactsTest() { + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>(); + List<ArtifactDefinition> defs = new ArrayList<>(); + defs.add(new ArtifactDefinition()); + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs); + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs); + assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight()); + } + + @Test + public void getUiComponentDataTransferByComponentIdTest() { + when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR)); + assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft()); + when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.OK)); + assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight()); + } + @Test + public void shouldUpgradeToLatestDerivedTest() { + createCR(); + createVF(); + when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR)); + when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK)); + assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft()); + assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft()); } private Resource createResourceObject(boolean afterCreate) { @@ -454,24 +469,48 @@ public class ResourceBusinessLogicTest { 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); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists); - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Resource createdResource = null; try { - createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); - assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId()); + assertThat(resource.getUniqueId()).isEqualTo(bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId()); } catch (ComponentException e) { - assertThat(new Integer(200)).isEqualTo(e.getResponseFormat() - .getStatus()); + assertThat(e.getResponseFormat().getStatus()).isEqualTo(200); } } + @Test + public void testUpdateUnhappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource)); + when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource))); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource)); + + when(csarOperation.getCsar("valid_vf.csar", user)).thenReturn(Either.left(new HashMap<>())); + + + try { + Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId()); + assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId()); + } catch (ComponentException e) { + assertThat(e.getResponseFormat().getStatus()).isEqualTo(400); + } + try { + resource.setCsarVersion("2"); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource)); + bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + } catch (ComponentException e) { + assertThat(e.getResponseFormat().getStatus()).isEqualTo(400); + } + } /* CREATE validations - start ***********************/ // Resource name - start @@ -867,19 +906,19 @@ public class ResourceBusinessLogicTest { try { bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); } catch (ComponentException e) { - assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); + assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); } } private void testVendorReleaseWrongFormat() { Resource resource = createResourceObject(false); // contains > - String vendorReleaseWrongFormat = "1>2"; - resource.setVendorRelease(vendorReleaseWrongFormat); + String vendorReleaseWrongFormat = "1>2"; + resource.setVendorRelease(vendorReleaseWrongFormat); try { bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); } catch (ComponentException e) { - assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat); + assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat); } } @@ -1040,17 +1079,17 @@ public class ResourceBusinessLogicTest { } private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, - String... variables) { + String... variables) { assertResponse(createResponse.right() .value(), expectedStatus, variables); } - // UPDATE tests - start - // Resource name - @Test - public void testResourceNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); + // 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)); @@ -1068,10 +1107,10 @@ public class ResourceBusinessLogicTest { } } - @Test - public void testResourceNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); + @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)); @@ -1091,10 +1130,10 @@ public class ResourceBusinessLogicTest { } } - @Test - public void testResourceNameAlreadyExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); + @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)); @@ -1271,7 +1310,7 @@ public class ResourceBusinessLogicTest { try { bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); } catch (ComponentException e) { - assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); + assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); } } @@ -1294,7 +1333,7 @@ public class ResourceBusinessLogicTest { try { bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); } catch (ComponentException e) { - assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); + assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat); } } @@ -1341,6 +1380,11 @@ public class ResourceBusinessLogicTest { } } + @Test(expected = ComponentException.class) + public void createResourceFromCsarTest() { + bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), ""); + } + @Test public void testResourceCategoryAfterCertify_UPDATE() { Resource resource = createResourceObject(true); @@ -1543,7 +1587,7 @@ public class ResourceBusinessLogicTest { when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())) - .thenReturn(Either.left(createdResource)); + .thenReturn(Either.left(createdResource)); Resource resourceToUpdtae = createResourceObject(false); @@ -1588,7 +1632,7 @@ public class ResourceBusinessLogicTest { @Test public void testIfNodeTypeNameHasValidPrefix() { final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDefinedResourceNamespace(); + .getConfiguration().getDefinedResourceNamespace(); definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> { final String nodeName = validNodeTypePrefix + "." + "abc"; @@ -1697,68 +1741,50 @@ public class ResourceBusinessLogicTest { bl.validatePropertiesDefaultValues(basic); } - // @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()); - // - // 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); - // - // 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); - // - // 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); - // - // 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)); - // - // Mockito.verify(artifactManager, - // Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); - // } + @Test + public void testDeleteMarkedResourcesNoResources() { + Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>()); + + when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + + Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + assertTrue(deleteMarkedResources.left().value().isEmpty()); + } + + @Test + public void testDeleteMarkedResources() { + List<String> ids = new ArrayList<>(); + String resourceInUse = "123"; + String resourceFree = "456"; + ids.add(resourceInUse); + 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<>(); + + 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); + + 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)); + } @SuppressWarnings("unchecked") @Test @@ -2204,32 +2230,32 @@ public class ResourceBusinessLogicTest { } - @Test - public void testgetAllCertifiedResources() throws Exception { - List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER"); - Assert.assertEquals(reslist,list); - } + @Test + public void testgetAllCertifiedResources() throws Exception { + List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER"); + Assert.assertEquals(reslist,list); + } - @Test(expected = StorageException.class) - public void testgetAllCertifiedResources_exception() throws Exception { - List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER"); - Assert.assertEquals(reslist,list); - } + @Test(expected = StorageException.class) + public void testgetAllCertifiedResources_exception() throws Exception { + List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER"); + Assert.assertEquals(reslist,list); + } - @Test - public void testvalidateResourceNameExists() throws Exception { - Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003"); - Assert.assertEquals(true,res.isLeft()); - } + @Test + public void testvalidateResourceNameExists() throws Exception { + Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003"); + Assert.assertEquals(true,res.isLeft()); + } - @Test + @Test public void rollbackWithEitherAlwaysReturnARuntimeException() { JanusGraphDao janusGraphDao = mockJanusGraphDao; ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND; String params = "testName"; Either<Object, RuntimeException> result = - ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params); + ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params); assertTrue(result.isRight()); assertTrue(result.right().value() instanceof ByActionStatusComponentException); @@ -2242,9 +2268,9 @@ public class ResourceBusinessLogicTest { String params = "testName"; Either<Object, RuntimeException> result = - ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params); + ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params); assertTrue(result.isRight()); assertTrue(result.right().value() instanceof ByActionStatusComponentException); } -} +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java index d31d3b1ef6..3e221528ba 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java @@ -108,10 +108,10 @@ public class UserBusinessLogicTest { verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString()); } -// @Test(expected = ComponentException.class) -// public void testGetUserContextNull() { -// testSubject.getUser("userId"); -// } + @Test(expected = ComponentException.class) + public void testGetUserContextNull() { + testSubject.getUser("userId"); + } @Test(expected = ComponentException.class) public void testGetUserContextIdEmpty() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java index 5c5bf8939a..87f01cd97e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java @@ -123,21 +123,16 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } private Either<InterfaceData, JanusGraphOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { - InterfaceData interfaceData = new InterfaceData(interfaceInfo); - ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resourceId); String interfaceNameSplitted = getShortInterfaceName(interfaceInfo); - interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); Either<InterfaceData, JanusGraphOperationStatus> existInterface = janusGraphGenericDao .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); - if (existInterface.isRight()) { - return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, resourceData); } else { log.debug("Interface {} already exist", interfaceData.getUniqueId()); @@ -205,7 +200,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) { - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null; Map<String, InterfaceDefinition> interfaces = new HashMap<>(); try { @@ -242,7 +236,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } private JanusGraphOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> interfaceNodes = janusGraphGenericDao .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); @@ -286,7 +279,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } public JanusGraphOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { - JanusGraphOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); if (!findAllInterfacesNotRecursively.equals(JanusGraphOperationStatus.OK)) { @@ -307,10 +299,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return parentNodesStatus; } } - ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - JanusGraphOperationStatus - addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); + ImmutablePair<ResourceMetadataData, GraphEdge> parentNodePair = parentNodes.left().value(); + String parentUniqueId = parentNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + JanusGraphOperationStatus addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); if (addParentIntStatus != JanusGraphOperationStatus.OK) { log.error("Failed to fetch all interfaces of resource {}", parentUniqueId); @@ -642,9 +633,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { - Either<InterfaceData, JanusGraphOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId); - if (status.isRight()) { janusGraphGenericDao.rollback(); log.error("Failed to add interface {} to resource {}", interfaceName, resourceId); @@ -711,7 +700,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation janusGraphGenericDao.commit(); } - Operation opDefResult = status.left().value();// convertOperationDataToOperation(operationData); + Operation opDefResult = status.left().value(); log.debug("The returned Operation is {}", opDefResult); return Either.left(opDefResult); } @@ -916,9 +905,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return interfaceName.toLowerCase(); } - /** - * - */ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf) { return createInterfaceType(interf, false); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java index 7c8dc3c805..d6414c5f25 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java @@ -32,14 +32,10 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; import org.openecomp.sdc.be.resources.data.*; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -59,35 +55,28 @@ public class ArtifactOperationTest extends ModelTestBase { @javax.annotation.Resource(name = "janusgraph-generic-dao") private JanusGraphGenericDao janusGraphDao; - @javax.annotation.Resource(name = "tosca-operation-facade") - private ToscaOperationFacade toscaOperationFacade; - @javax.annotation.Resource private ArtifactOperation artifactOperation; - private static final Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class); - - private static String RESOURCE_ID = "resourceId"; - private static String RESOURCE_ID_2 = "resourceId2"; + private static final String RESOURCE_ID = "resourceId"; + private static final String RESOURCE_ID_2 = "resourceId2"; - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; + private static final String USER_ID = "muUserId"; @BeforeClass public static void setupBeforeClass() { - ModelTestBase.init(); } @Before public void createUserAndCategory() { + String CATEGORY_NAME = "category/mycategory"; deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); + deleteAndCreateUser(); } @Test public void testCreateDeleteArtifactWithHeatParams() { - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); @@ -113,7 +102,6 @@ public class ArtifactOperationTest extends ModelTestBase { @Test public void testUpdateArtifactWithHeatParams() { - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); @@ -125,7 +113,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertTrue(parameterNode.isLeft()); // update to artifact without params - ArtifactDefinition artifactNoParams = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + ArtifactDefinition artifactNoParams = createArtifactDefinition(); artifactNoParams.setUniqueId(artifactWithHeat.getUniqueId()); artifactNoParams.setArtifactType("HEAT"); artifactNoParams.setArtifactVersion("2"); @@ -180,11 +168,10 @@ public class ArtifactOperationTest extends ModelTestBase { Either<HeatParameterData, JanusGraphOperationStatus> parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isLeft()); - Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); - removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + artifactOperation.removeArifactFromResource(RESOURCE_ID_2, artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); + artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); - } @Test @@ -240,13 +227,13 @@ public class ArtifactOperationTest extends ModelTestBase { ArtifactData updatedArtifactData = updatedArtifact.left().value(); assertEquals(atifactToUpdate.getArtifactVersion(), updatedArtifactData.getArtifactDataDefinition() .getArtifactVersion()); - assertFalse(((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId())); + assertFalse(updatedArtifactData.getUniqueId().equalsIgnoreCase(origArtifactData.getUniqueId())); List<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters(); assertNotNull(heatParametersAfterUpdate); assertEquals(1, heatParametersAfterUpdate.size()); HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); - assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); + assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase(parameterData.getUniqueId())); Either<HeatParameterData, JanusGraphOperationStatus> parameterNodeAfterUpdate = janusGraphDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterUpdate.isLeft()); @@ -277,8 +264,8 @@ public class ArtifactOperationTest extends ModelTestBase { } private ArtifactDefinition createResourceWithHeat() { - ResourceMetadataData resource = createResource(RESOURCE_ID); - ArtifactDefinition artifactDefinition = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + createResource(RESOURCE_ID); + ArtifactDefinition artifactDefinition = createArtifactDefinition(); artifactDefinition.setArtifactType("HEAT"); artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); @@ -297,97 +284,43 @@ public class ArtifactOperationTest extends ModelTestBase { return artifact.left().value(); } - private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { - ArtifactDefinition artifactInfo = createArtifactDefinition(userId, serviceId, artifactName); - - Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); - assertTrue(artifact.isLeft()); - return artifact.left().value(); - } - - private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { + private ArtifactDefinition createArtifactDefinition() { ArtifactDefinition artifactInfo = new ArtifactDefinition(); - artifactInfo.setArtifactName(artifactName + ".sh"); + artifactInfo.setArtifactName(ArtifactOperationTest.ARTIFACT_NAME + ".sh"); artifactInfo.setArtifactType("SHELL"); artifactInfo.setDescription("hdkfhskdfgh"); artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - artifactInfo.setUserIdCreator(userId); + artifactInfo.setUserIdCreator(ArtifactOperationTest.USER_ID); 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(artifactName); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); + artifactInfo.setUserIdLastUpdater(ArtifactOperationTest.USER_ID); + artifactInfo.setArtifactLabel(ArtifactOperationTest.ARTIFACT_NAME); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(ArtifactOperationTest.RESOURCE_ID, artifactInfo.getArtifactLabel())); return artifactInfo; } - public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion, boolean isHighestVersion) { - - Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); - - service.setHighestVersion(isHighestVersion); - - Either<Service, StorageOperationStatus> result = toscaOperationFacade.createToscaComponent(service); - - log.info(result.toString()); - assertTrue(result.isLeft()); - Service resultService = result.left().value(); - - // assertEquals("check resource unique id", - // UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion), - // resultService.getUniqueId()); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState()); - - return resultService; - } - - private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName, String serviceVersion) { - - Service service = new Service(); - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setDescription("description 1"); - - service.setCreatorUserId(userId); - service.setContactId("contactId@sdc.com"); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setIcon("images/my.png"); - List<String> tags = new ArrayList<>(); - tags.add("TAG1"); - tags.add("TAG2"); - service.setTags(tags); - return service; - } - private void deleteAndCreateCategory(String category) { String[] names = category.split("/"); OperationTestsUtil.deleteAndCreateServiceCategory(category, janusGraphDao); OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], janusGraphDao); } - private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + private void deleteAndCreateUser() { UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - if (role != null && !role.isEmpty()) { - userData.setRole(role); - } else { - userData.setRole("ADMIN"); - } - - janusGraphDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + userData.setUserId(ArtifactOperationTest.USER_ID); + userData.setFirstName("first_muUserId"); + userData.setLastName("last_muUserId"); + userData.setRole("ADMIN"); + + janusGraphDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), ArtifactOperationTest.USER_ID, UserData.class); janusGraphDao.createNode(userData, UserData.class); janusGraphDao.commit(); - - return userData; } public ResourceMetadataData createResource(String resourceName) { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java index 975181d471..8262d54bc4 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java @@ -20,10 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -32,42 +31,38 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.InterfaceData; import org.openecomp.sdc.be.resources.data.OperationData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import org.junit.Assert; - -import static org.junit.Assert.assertNotNull; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class InterfaceLifecycleOperationTest { - private static final Logger log = LoggerFactory.getLogger(InterfaceLifecycleOperationTest.class); - private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); private static String USER_ID = "muUserId"; private static String CATEGORY_NAME = "category/mycategory"; @@ -75,16 +70,9 @@ public class InterfaceLifecycleOperationTest { @InjectMocks private InterfaceLifecycleOperation interfaceLifecycleOperation = new InterfaceLifecycleOperation(); - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - // @Resource(name = "artifact-operation") - // private ArtifactOperation artifactOperation; - @Before public void createUserAndCategory() { MockitoAnnotations.initMocks(this); - final String UNIQUE_ID = "UNIQUE_ID"; CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceCategory); when(janusGraphGenericDao.createNode(any(),any())).thenReturn(Either.left(categoryData)); deleteAndCreateCategory(CATEGORY_NAME); @@ -93,167 +81,25 @@ public class InterfaceLifecycleOperationTest { @BeforeClass public static void setupBeforeClass() { - // ExternalConfiguration.setAppName("catalog-model"); - // String appConfigDir = "src/test/resources/config/catalog-model"; - // ConfigurationSource configurationSource = new - // FSConfigurationSource(ExternalConfiguration.getChangeListener(), - // appConfigDir); - ModelTestBase.init(); - } @Test public void testDummy() { - assertNotNull(interfaceLifecycleOperation); - - } - -/* @Test - public void addInterfaceToResourceTest() { - - String capabilityTypeName = "mycapability1"; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute1"; - String rootName = "Root100"; - String softwareCompName = "tosca.nodes.SoftwareComponent"; - String computeNodeName = "tosca.nodes.Compute"; - String myResourceVersion = "300.0"; - String reqRelationship = "myrelationship"; - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(janusGraphDao, resourceOperation, propertyOperation); - - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, true, true); - - String interfaceName = "standard"; - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - - Operation op = buildOperationDefinition(); - Map<String, Operation> operations = new HashMap<String, Operation>(); - operations.put("Create", op); - interfaceDefinition.setOperations(operations); - - Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - - assertTrue(result.isLeft()); - log.debug("{}", result.left().value()); - - Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(rootResource.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); - - } - - @Test - public void updateInterfaceToResourceTest() { - - String reqName = "host"; - String rootName = "Root200"; - String softwareCompName = "tosca.nodes.SoftwareComponent"; - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(janusGraphDao, resourceOperation, propertyOperation); - - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, true, true); - - String interfaceName = "standard"; - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - - Operation op = buildOperationDefinition(); - Map<String, Operation> operations = new HashMap<String, Operation>(); - operations.put("create", op); - interfaceDefinition.setOperations(operations); - - Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either<ResourceMetadataData, JanusGraphOperationStatus> updateNode = janusGraphDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); - - assertTrue(fetchRootResource.isLeft()); - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "400.0", rootResource.getName(), true, true); - - assertTrue(result.isLeft()); - log.debug("{}", result.left().value()); - - addImplementationToOperation(op); - // String resourceId, String interfaceName, String - // operationName,Operation interf - - Either<Operation, StorageOperationStatus> opResult = interfaceOperation.updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op); - // PrintGraph pg = new PrintGraph(); - // System.out.println(pg.buildGraphForWebgraphWiz(janusGraphDao.getGraph().left().value())); - assertTrue(opResult.isLeft()); - log.debug("{}", opResult.left().value()); - - Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); - Operation operation = interfaceDefinition2.getOperations().get("create"); - assertNotNull(operation); - assertNotNull(operation.getImplementation()); - } -*/ - private void addImplementationToOperation(Operation op) { - ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); - artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); - artifactDataDef.setArtifactName("create_myRoot.sh"); - artifactDataDef.setArtifactLabel("create_myRoot"); - artifactDataDef.setArtifactType("SHELL"); - artifactDataDef.setDescription("good description"); - artifactDataDef.setEsId("esId"); - artifactDataDef.setUniqueId(op.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); - ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); - op.setImplementation(artifactDef); } private InterfaceDefinition buildInterfaceDefinition() { InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); interfaceDefinition.setType("tosca.interfaces.standard"); - interfaceDefinition.setCreationDate(new Long(101232)); + interfaceDefinition.setCreationDate(101232L); return interfaceDefinition; } - private Operation buildOperationDefinition() { - Operation op = new Operation(); - op.setCreationDate(new Long(101232)); - op.setDescription("asda"); - - return op; - } - private void deleteAndCreateCategory(String category) { String[] names = category.split("/"); OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], janusGraphGenericDao); - - /* - * CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * janusGraphDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, JanusGraphOperationStatus> createNode = janusGraphDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); - */ - } private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { @@ -271,6 +117,39 @@ public class InterfaceLifecycleOperationTest { } @Test + public void createInterfaceOnResourceTest() { + when(janusGraphGenericDao.getChildrenNodes(any(), any(), any(), any(), eq(InterfaceData.class))).thenReturn(Either.right(JanusGraphOperationStatus.GRAPH_IS_NOT_AVAILABLE)); + when(janusGraphGenericDao.getChild(any(), any(), any(), eq(NodeTypeEnum.Resource), eq(ResourceMetadataData.class))).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + when(janusGraphGenericDao.getNode(any(), any(), eq(InterfaceData.class))).thenReturn(Either.right(JanusGraphOperationStatus.ALREADY_EXIST)); + when(janusGraphGenericDao.createNode(any(), eq(InterfaceData.class))).thenReturn(Either.right(JanusGraphOperationStatus.ALREADY_EXIST)); + when(janusGraphGenericDao.createRelation(any(), any(), eq(GraphEdgeLabels.INTERFACE), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK)); + Assert.assertTrue(interfaceLifecycleOperation.createInterfaceOnResource(buildInterfaceDefinition(), "", "", false, false).isRight()); + when(janusGraphGenericDao.createRelation(any(), any(), eq(GraphEdgeLabels.INTERFACE), any())).thenReturn(Either.left(Mockito.mock(GraphRelation.class))); + Assert.assertTrue(interfaceLifecycleOperation.createInterfaceOnResource(buildInterfaceDefinition(), "", "", false, false).isRight()); + } + + @Test + public void getAllInterfacesOfResourceTest() { + assertTrue(interfaceLifecycleOperation.getAllInterfacesOfResource(null, true).isRight()); + when(janusGraphGenericDao.getChildrenNodes(any(), any(), any(), any(), eq(InterfaceData.class))).thenReturn(Either.right(JanusGraphOperationStatus.GRAPH_IS_NOT_AVAILABLE)); + when(janusGraphGenericDao.getChild(any(), any(), any(), eq(NodeTypeEnum.Resource), eq(ResourceMetadataData.class))).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + assertTrue(interfaceLifecycleOperation.getAllInterfacesOfResource("null", true).isLeft()); + + when(janusGraphGenericDao.getChild(any(), any(), any(), eq(NodeTypeEnum.Resource), eq(ResourceMetadataData.class))).thenReturn(Either.right(JanusGraphOperationStatus.ALREADY_EXIST)); + assertTrue(interfaceLifecycleOperation.getAllInterfacesOfResource("null", true).isRight()); + + ResourceMetadataData key = Mockito.mock(ResourceMetadataData.class); + ComponentMetadataDataDefinition def = Mockito.mock(ComponentMetadataDataDefinition.class); + when(def.getUniqueId()).thenReturn("UNIIIIIIQUE IDDDD"); + when(key.getMetadataDataDefinition()).thenReturn(def); + ImmutablePair<ResourceMetadataData, GraphEdge> pair = new ImmutablePair<>(key, Mockito.mock(GraphEdge.class)); + when(janusGraphGenericDao.getChild(any(), any(), any(), eq(NodeTypeEnum.Resource), eq(ResourceMetadataData.class))) + .thenReturn(Either.left(pair)) + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + assertTrue(interfaceLifecycleOperation.getAllInterfacesOfResource("null", true).isLeft()); + } + + @Test public void testGetAllInterfaceLifecycleTypes_TypesNotFound() { when(janusGraphGenericDao.getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImplTest.java index a7da29d5c4..274af8ff40 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImplTest.java @@ -56,39 +56,40 @@ public class CompositionEntityDataManagerImplTest { private static final String COMPONENT1 = "component1"; private static final String NIC1 = "nic1"; private static final String SIMPLE_SCHEMA = "{\n" + - " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + - " \"type\": \"object\",\n" + - " \"properties\": {\n" + - " \"a\": {\n" + - " \"type\": \"number\"\n" + - " }\n" + - " }\n" + - "}"; + " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + + " \"type\": \"object\",\n" + + " \"properties\": {\n" + + " \"a\": {\n" + + " \"type\": \"number\"\n" + + " }\n" + + " }\n" + + "}"; private static final String NETWORK_COMPOSITION_SCHEMA = "{\n" + - " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + - " \"type\": \"object\",\n" + - " \"properties\": {\n" + - " \"name\": {\n" + - " \"type\": \"string\",\n" + - " \"enum\": [\n" + - " \"network1 name\"\n" + - " ],\n" + - " \"default\": \"network1 name\"\n" + - " },\n" + - " \"dhcp\": {\n" + - " \"type\": \"boolean\",\n" + - " \"enum\": [\n" + - " true\n" + - " ],\n" + - " \"default\": true\n" + - " }\n" + - " },\n" + - " \"additionalProperties\": false,\n" + - " \"required\": [\n" + - " \"name\",\n" + - " \"dhcp\"\n" + - " ]\n" + - "}"; + " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + + " \"type\": \"object\",\n" + + " \"properties\": {\n" + + " \"name\": {\n" + + " \"type\": \"string\",\n" + + " \"enum\": [\n" + + " \"network1 name\"\n" + + " ],\n" + + " \"default\": \"network1 name\"\n" + + " },\n" + + " \"dhcp\": {\n" + + " \"type\": \"boolean\",\n" + + " \"enum\": [\n" + + " true\n" + + " ],\n" + + " \"default\": true\n" + + " }\n" + + " },\n" + + " \"additionalProperties\": false,\n" + + " \"required\": [\n" + + " \"name\",\n" + + " \"dhcp\"\n" + + " ]\n" + + "}"; + String invalidQuestionnaireData = "{\"a\": \"b\"}"; private Map<CompositionEntityId, Collection<String>> errorsById; @InjectMocks @@ -98,19 +99,11 @@ public class CompositionEntityDataManagerImplTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - } - - @Test(expected = CoreException.class) - public void testAddNullEntity_negative() { - compositionEntityDataManager.addEntity(null, null); - } + compositionEntityDataManager.addEntity(new VspQuestionnaireEntity(VSP1, VERSION), null); - @Test - public void testAddEntity() { - compositionEntityDataManager - .addEntity(new VspQuestionnaireEntity(VSP1, VERSION), null); - - String invalidQuestionnaireData = "{\"a\": \"b\"}"; + doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager).generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, null); + doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager).generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, null); + doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager).generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null); ComponentEntity component = new ComponentEntity(VSP1, VERSION, COMPONENT1); component.setQuestionnaireData(invalidQuestionnaireData); @@ -121,56 +114,38 @@ public class CompositionEntityDataManagerImplTest { compositionEntityDataManager.addEntity(nic, null); } - // TODO: 3/15/2017 fix and enable - //@Test(dependsOnMethods = "testAddEntity") - public void testValidateEntitiesQuestionnaire() { - doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, null); - doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, null); - doReturn(SIMPLE_SCHEMA).when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null); + @Test(expected = CoreException.class) + public void testAddNullEntity_negative() { + compositionEntityDataManager.addEntity(null, null); + } + @Test + public void testValidateEntitiesQuestionnaire() { errorsById = compositionEntityDataManager.validateEntitiesQuestionnaire(); Assert.assertNotNull(errorsById); - Assert.assertEquals(errorsById.size(), 2); // both component and nic data don't mach schemas - CompositionEntityId nicId = - new NicEntity(VSP1, VERSION, COMPONENT1, NIC1).getCompositionEntityId(); + Assert.assertEquals(3, errorsById.size()); + CompositionEntityId nicId = new NicEntity(VSP1, VERSION, COMPONENT1, NIC1).getCompositionEntityId(); Assert.assertTrue(errorsById.containsKey(nicId)); Assert.assertTrue(errorsById.containsKey(nicId.getParentId())); } @Test - public void testBuildTrees() { - testAddEntity(); + public void testGetTrees() { + errorsById = compositionEntityDataManager.validateEntitiesQuestionnaire(); compositionEntityDataManager.buildTrees(); - } - - // TODO: 3/15/2017 fix and enable - //@Test(dependsOnMethods = "testBuildTrees") - public void testAddErrorsToTrees() { compositionEntityDataManager.addErrorsToTrees(errorsById); - } - - // TODO: 3/15/2017 fix and enable - //@Test(dependsOnMethods = "testAddErrorsToTrees") - public void testGetTrees() { Collection<CompositionEntityValidationData> trees = compositionEntityDataManager.getTrees(); Assert.assertNotNull(trees); - Assert.assertEquals(trees.size(), 1); + Assert.assertEquals(1, trees.size()); CompositionEntityValidationData vspValidationData = trees.iterator().next(); - assertValidationData(vspValidationData, VSP1, CompositionEntityType.vsp, false); - Assert.assertEquals(vspValidationData.getSubEntitiesValidationData().size(), 1); + Assert.assertEquals(1, vspValidationData.getSubEntitiesValidationData().size()); - CompositionEntityValidationData componentValidationData = - vspValidationData.getSubEntitiesValidationData().iterator().next(); - assertValidationData(componentValidationData, COMPONENT1, CompositionEntityType.component, - true); - Assert.assertEquals(componentValidationData.getSubEntitiesValidationData().size(), 1); + CompositionEntityValidationData componentValidationData = vspValidationData.getSubEntitiesValidationData().iterator().next(); + assertValidationData(componentValidationData, COMPONENT1, CompositionEntityType.component,true); + Assert.assertEquals(1, componentValidationData.getSubEntitiesValidationData().size()); - CompositionEntityValidationData nicValidationData = - componentValidationData.getSubEntitiesValidationData().iterator().next(); + CompositionEntityValidationData nicValidationData = componentValidationData.getSubEntitiesValidationData().iterator().next(); assertValidationData(nicValidationData, NIC1, CompositionEntityType.nic, true); Assert.assertNull(nicValidationData.getSubEntitiesValidationData()); } @@ -188,11 +163,11 @@ public class CompositionEntityDataManagerImplTest { schemaTemplateInput.setNetwork(network); doReturn(NETWORK_COMPOSITION_SCHEMA).when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.composition, CompositionEntityType.network, - schemaTemplateInput); + .generateSchema(SchemaTemplateContext.composition, CompositionEntityType.network, + schemaTemplateInput); CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(networkEntity, SchemaTemplateContext.composition, schemaTemplateInput); + .validateEntity(networkEntity, SchemaTemplateContext.composition, schemaTemplateInput); assertValidationData(validationData, "network1", CompositionEntityType.network, false); } @@ -212,11 +187,11 @@ public class CompositionEntityDataManagerImplTest { schemaTemplateInput.setNetwork(origNetwork); doReturn(NETWORK_COMPOSITION_SCHEMA).when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.composition, CompositionEntityType.network, - schemaTemplateInput); + .generateSchema(SchemaTemplateContext.composition, CompositionEntityType.network, + schemaTemplateInput); CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(networkEntity, SchemaTemplateContext.composition, schemaTemplateInput); + .validateEntity(networkEntity, SchemaTemplateContext.composition, schemaTemplateInput); assertValidationData(validationData, "network1", CompositionEntityType.network, true); Assert.assertEquals(validationData.getErrors().size(), 2); } @@ -224,7 +199,7 @@ public class CompositionEntityDataManagerImplTest { @Test public void testNicAndComponentValidQuestionnaire() { compositionEntityDataManager - .addEntity(new VspQuestionnaireEntity(VSP1, VERSION), null); + .addEntity(new VspQuestionnaireEntity(VSP1, VERSION), null); ComponentEntity componentEntity = new ComponentEntity(VSP1, VERSION, COMPONENT1); componentEntity.setQuestionnaireData(loadFileToString("quesionnaire/validComponent.json")); @@ -235,19 +210,19 @@ public class CompositionEntityDataManagerImplTest { compositionEntityDataManager.addEntity(nicEntity, null); doReturn(SIMPLE_SCHEMA) - .when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, null); + .when(compositionEntityDataManager) + .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, null); doReturn(loadFileToString("quesionnaire/schema/componentQuestionnaire.json")) - .when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, null); + .when(compositionEntityDataManager) + .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, null); doReturn(loadFileToString("quesionnaire/schema/nicQuestionnaire.json")) - .when(compositionEntityDataManager) - .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null); + .when(compositionEntityDataManager) + .generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null); Map<CompositionEntityId, Collection<String>> errorsById = - compositionEntityDataManager.validateEntitiesQuestionnaire(); + compositionEntityDataManager.validateEntitiesQuestionnaire(); Assert.assertEquals(errorsById.size(), 1); } @@ -260,14 +235,14 @@ public class CompositionEntityDataManagerImplTest { compositionEntityDataManager.addEntity(componentEntity, null); Map<CompositionEntityId, Collection<String>> errorsById = - compositionEntityDataManager.validateEntitiesQuestionnaire(); + compositionEntityDataManager.validateEntitiesQuestionnaire(); Assert.assertEquals(errorsById.size(), 2); CompositionEntityId component = new ArrayList<>(errorsById.keySet()).get(1); List<String> errors = (List<String>) errorsById.get(component); Assert.assertEquals(errors.size(), 1); Assert.assertEquals(errors.get(0), - "#/general/recovery/pointObjective: 20.0 is not lower or equal to 15"); + "#/general/recovery/pointObjective: 20.0 is not lower or equal to 15"); } private static void assertValidationData(CompositionEntityValidationData validationData, @@ -292,4 +267,4 @@ public class CompositionEntityDataManagerImplTest { compositionEntityDataManager.validateEntity(null, SchemaTemplateContext.composition, schemaTemplateInput); } -} +}
\ No newline at end of file |