From 68eed7997aab4aa4f785085303aab61cf8e16a31 Mon Sep 17 00:00:00 2001 From: "andre.schmid" Date: Wed, 13 Oct 2021 16:01:51 +0100 Subject: Make Service base type optional Issue-ID: SDC-3759 Change-Id: I8adf112966ee9303fc965a74cec7203274acd735 Signed-off-by: andre.schmid --- .../templates/default/BE-configuration.yaml.erb | 11 +- .../be/components/impl/ElementBusinessLogic.java | 12 +- .../be/components/impl/ServiceBusinessLogic.java | 8 +- .../sdc/be/exception/ToscaExportException.java | 12 + .../openecomp/sdc/be/servlets/ElementServlet.java | 1 + .../be/tosca/CapabilityRequirementConverter.java | 19 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 33 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 133 +++++-- .../sdc/be/tosca/model/ToscaTopolgyTemplate.java | 11 + .../org/openecomp/sdc/ElementOperationMock.java | 11 +- .../components/BaseServiceBusinessLogicTest.java | 4 - .../components/impl/ElementBusinessLogicTest.java | 137 +++---- .../impl/ServiceBusinessLogicBaseTestSetup.java | 397 +++++++++++++++++++ .../components/impl/ServiceBusinessLogicTest.java | 122 +++--- .../impl/ServiceBussinessLogicBaseTestSetup.java | 441 --------------------- .../be/components/impl/ServiceValidationsTest.java | 48 ++- .../org/openecomp/sdc/be/tosca/CsarUtilsTest.java | 153 ++++--- .../sdc/be/tosca/ToscaExportHandlerTest.java | 378 +++++++++--------- .../java/org/openecomp/sdc/be/model/BaseType.java | 2 +- .../java/org/openecomp/sdc/be/model/Component.java | 5 + .../java/org/openecomp/sdc/be/model/Service.java | 36 +- .../be/model/operations/api/IElementOperation.java | 10 +- .../be/model/operations/impl/ElementOperation.java | 66 ++- .../org/openecomp/sdc/be/model/ModelTestBase.java | 8 +- .../org/openecomp/sdc/be/model/ResourceTest.java | 4 +- .../org/openecomp/sdc/be/model/ServiceTest.java | 14 +- .../operations/impl/ElementOperationTest.java | 82 +++- .../src/test/resources/config/configuration.yaml | 13 +- catalog-ui/src/app/models/base-types.ts | 5 +- catalog-ui/src/app/models/components/service.ts | 4 + .../panel/composition-panel.component.spec.ts | 44 +- .../panel/composition-panel.component.ts | 13 +- .../properties-assignment.page.component.html | 2 +- .../properties-assignment.page.component.ts | 9 +- catalog-ui/src/app/ng2/services/element.service.ts | 5 +- .../workspace/tabs/general/general-view-model.ts | 78 ++-- .../workspace/tabs/general/general-view.html | 28 +- .../sdc/be/config/CategoryBaseTypeConfig.java | 37 ++ .../org/openecomp/sdc/be/config/Configuration.java | 2 +- .../components/ServiceMetadataDataDefinition.java | 9 - .../ServiceMetadataDataDefinitionTest.java | 9 - .../ci/tests/datatypes/ServiceReqDetails.java | 13 +- .../utils/general/OnboardingUtillViaApis.java | 5 +- 43 files changed, 1363 insertions(+), 1071 deletions(-) create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicBaseTestSetup.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBussinessLogicBaseTestSetup.java create mode 100644 common-app-api/src/main/java/org/openecomp/sdc/be/config/CategoryBaseTypeConfig.java diff --git a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb index 69fd11da97..3b9d437ba6 100644 --- a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb +++ b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb @@ -1017,9 +1017,16 @@ genericAssetNodeTypes: Service: org.openecomp.resource.abstract.nodes.service ETSI NFV Network Service: tosca.nodes.nfv.NS -serviceNodeTypes: +# Defines the base types for Services +# : +# required: //if the base type is mandatory or not +# baseTypes: //the base types. Required if the base type is required. +# If not provided, the category will have no base type. +serviceBaseNodeTypes: ETSI NFV Network Service: - - tosca.nodes.nfv.NS + required: true + baseTypes: + - tosca.nodes.nfv.NS workloadContext: Production diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 42fa95e642..caea46aae8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -1291,6 +1291,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { if (ActionStatus.OK != status) { return Either.right(status); } - return Either.left(elementOperation.getBaseTypes(categoryName, modelName)); + return Either.left(elementOperation.getServiceBaseTypes(categoryName, modelName)); + } + + /** + * Checks if a category requires a base type. + * + * @param categoryName the category name + * @return {@code true} if a base type is required, {@code false} otherwise. + */ + public boolean isBaseTypeRequired(final String categoryName) { + return elementOperation.isBaseTypeRequired(categoryName); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 50cf5d8c65..e51aeefa55 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -701,9 +701,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { createMandatoryArtifactsData(service, user); createServiceApiArtifactsData(service, user); setToscaArtifactsPlaceHolders(service, user); - final Resource genericType = fetchAndSetDerivedFromGenericType(service); - generatePropertiesFromGenericType(service, genericType); - generateAndAddInputsFromGenericTypeProperties(service, genericType); + if (service.isSubstituteCandidate()) { + final Resource genericType = fetchAndSetDerivedFromGenericType(service); + generatePropertiesFromGenericType(service, genericType); + generateAndAddInputsFromGenericTypeProperties(service, genericType); + } beforeCreate(service); Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); if (dataModelResponse.isLeft()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java index d38f08f376..aec931a02a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java @@ -18,9 +18,21 @@ */ package org.openecomp.sdc.be.exception; +import lombok.Getter; +import org.openecomp.sdc.be.tosca.ToscaError; + public class ToscaExportException extends Exception { + @Getter + private final ToscaError toscaError; + public ToscaExportException(String message) { super(message); + toscaError = null; + } + + public ToscaExportException(final String message, final ToscaError toscaError) { + super(message); + this.toscaError = toscaError; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java index 45f99a931e..f11bd8187a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java @@ -216,6 +216,7 @@ public class ElementServlet extends BeGenericServlet { } else { final Map baseTypesMap = new HashMap<>(); baseTypesMap.put("baseTypes", either.left().value()); + baseTypesMap.put("required", elementBL.isBaseTypeRequired(categoryName)); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), baseTypesMap); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java index bf42af8322..a074eb8145 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java @@ -56,7 +56,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.utils.ComponentUtilities; import org.openecomp.sdc.be.tosca.ToscaUtils.SubstitutionEntry; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; import org.openecomp.sdc.be.tosca.model.ToscaNodeType; @@ -198,24 +197,22 @@ public class CapabilityRequirementConverter { /** * Allows to convert component requirements to the tosca template substitution mappings requirements * - * @param componentsCache * @param component - * @param substitutionMappings + * @param componentsCache * @return */ - public Either convertSubstitutionMappingRequirements(Map componentsCache, Component component, - SubstitutionMapping substitutionMappings) { - Either result = Either.left(substitutionMappings); + public Either, ToscaError> convertSubstitutionMappingRequirements(final Component component, + final Map componentsCache) { Either, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); if (toscaRequirementsRes.isRight()) { - result = Either.right(toscaRequirementsRes.right().value()); logger.debug("Failed convert requirements for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { - substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); - result = Either.left(substitutionMappings); + return Either.right(toscaRequirementsRes.right().value()); + } + if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { logger.debug("Finish convert requirements for the component {}. ", component.getName()); + return Either.left(toscaRequirementsRes.left().value()); } - return result; + return Either.left(Collections.emptyMap()); } /** diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index 1f17a6fdc5..f9662cc96e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -431,9 +431,9 @@ public class CsarUtils { LifecycleStateEnum lifecycleState = component.getLifecycleState(); addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml); //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)) { + if (hasToWriteComponentSubstitutionType(component)) { log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - dependencies.addAll(writeComponentInterface(component, zip, fileName, false)); + dependencies.addAll(writeComponentInterface(component, zip, fileName)); } //UID Either zipOutputStreamOrResponseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies); @@ -648,13 +648,20 @@ public class CsarUtils { zip.putNextEntry(value._2); zip.write(value._1); // add component interface to zip - if (!ModelConverter.isAtomicComponent(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName, true); + if (hasToWriteComponentSubstitutionType(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); } } return null; } + private boolean hasToWriteComponentSubstitutionType(final Component component) { + if (component instanceof Service) { + return !ModelConverter.isAtomicComponent(component) && ((Service) component).isSubstituteCandidate(); + } + return !ModelConverter.isAtomicComponent(component); + } + private Either, ResponseFormat> toZipEntry(ImmutableTriple cachedEntry) { String cassandraId = cachedEntry.getLeft(); String fileName = cachedEntry.getMiddle(); @@ -767,22 +774,18 @@ public class CsarUtils { return componentRI; } - private List> writeComponentInterface(Component component, - ZipOutputStream zip, - String fileName, - boolean isAssociatedComponent - ){ + private List> writeComponentInterface(final Component component, final ZipOutputStream zip, + final String fileName) { final Either interfaceRepresentation = toscaExportUtils.exportComponentInterface(component, false); - writeComponentInterface(interfaceRepresentation, zip, fileName, false); + writeComponentInterface(interfaceRepresentation, zip, fileName); return interfaceRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>()); } - private Either writeComponentInterface( - Either interfaceRepresentation, ZipOutputStream zip, String fileName, - boolean isAssociatedComponent) { + private Either writeComponentInterface(Either interfaceRepresentation, + ZipOutputStream zip, String fileName) { // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable - return writeComponentInterface(interfaceRepresentation, fileName, isAssociatedComponent, ZipWriter.live(zip)) + return writeComponentInterface(interfaceRepresentation, fileName, ZipWriter.live(zip)) .map(void0 -> Either.left(zip)).recover(th -> { log.error("#writeComponentInterface - zip writing failed with error: ", th); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -790,7 +793,7 @@ public class CsarUtils { } private Try writeComponentInterface( - Either interfaceRepresentation, String fileName, boolean isAssociatedComponent, ZipWriter zw) { + Either interfaceRepresentation, String fileName, ZipWriter zw) { Either yml = interfaceRepresentation.left() .map(ToscaRepresentation::getMainYaml); return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName))); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 3c44c4fec9..d228db5f4b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -385,8 +385,6 @@ public class ToscaExportHandler { if (!relationshipTemplatesMap.isEmpty()) { topologyTemplate.setRelationshipTemplates(relationshipTemplatesMap); } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - convertSubstitutionMappingFilter(component, substitutionMapping); addGroupsToTopologyTemplate(component, topologyTemplate); try { addPoliciesToTopologyTemplate(component, topologyTemplate); @@ -394,48 +392,86 @@ public class ToscaExportHandler { log.debug("Fail to add policies to topology template:", e); return Either.right(ToscaError.GENERAL_ERROR); } - String toscaResourceName; + try { + createSubstitutionMapping(component, componentCache).ifPresent(topologyTemplate::setSubstitution_mappings); + } catch (final ToscaExportException e) { + log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ToscaExportHandler.class.getName(), e.getMessage()); + return Either.right(e.getToscaError()); + } + if (!topologyTemplate.isEmpty()) { + toscaNode.setTopology_template(topologyTemplate); + } + return Either.left(toscaNode); + } + + private Either createComponentToscaName(final Component component) { switch (component.getComponentType()) { case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) - .getToscaResourceName(); - break; + final ResourceMetadataDataDefinition resourceMetadata = + (ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition(); + return Either.left(resourceMetadata.getToscaResourceName()); case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; + return Either.left(SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName()); default: log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); } + } + + private Optional createSubstitutionMapping(final Component component, + final Map componentCache) throws ToscaExportException { + if (component instanceof Service && !((Service) component).isSubstituteCandidate()) { + return Optional.empty(); + } + + final Either toscaResourceNameEither = createComponentToscaName(component); + if (toscaResourceNameEither.isRight()) { + throw new ToscaExportException("Could not create component TOSCA name", toscaResourceNameEither.right().value()); + } + final String toscaResourceName = toscaResourceNameEither.left().value(); + + final SubstitutionMapping substitutionMapping = new SubstitutionMapping(); substitutionMapping.setNode_type(toscaResourceName); - Either capabilities = convertCapabilities(component, substitutionMapping, componentCache); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); + convertSubstitutionMappingFilter(component).ifPresent(substitutionMapping::setSubstitution_filter); + + final Either, ToscaError> capabilitiesEither = convertSubstitutionMappingCapabilities(component, componentCache); + if (capabilitiesEither.isRight()) { + throw new ToscaExportException("Could not convert substitution mapping capabilities", capabilitiesEither.right().value()); } - substitutionMapping = capabilities.left().value(); - Either requirements = capabilityRequirementConverter - .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping); + final Map capabilityMap = capabilitiesEither.left().value(); + if (!capabilityMap.isEmpty()) { + substitutionMapping.setCapabilities(capabilityMap); + } + + final Either, ToscaError> requirements = + capabilityRequirementConverter.convertSubstitutionMappingRequirements(component, componentCache); if (requirements.isRight()) { - return Either.right(requirements.right().value()); + throw new ToscaExportException("Could not convert substitution mapping requirements", requirements.right().value()); + } + final Map requirementMap = requirements.left().value(); + if (!requirementMap.isEmpty()) { + substitutionMapping.setRequirements(requirementMap); } - substitutionMapping = requirements.left().value(); + final Map propertyMappingMap = buildSubstitutionMappingPropertyMapping(component); if (!propertyMappingMap.isEmpty()) { substitutionMapping.setProperties(propertyMappingMap); } + final Map attributesMappingMap = buildSubstitutionMappingAttributesMapping(component); if (!attributesMappingMap.isEmpty()) { substitutionMapping.setAttributes(attributesMappingMap); } - topologyTemplate.setSubstitution_mappings(substitutionMapping); - toscaNode.setTopology_template(topologyTemplate); - return Either.left(toscaNode); + + return Optional.of(substitutionMapping); } - private void convertSubstitutionMappingFilter(final Component component, final SubstitutionMapping substitutionMapping) { - if (component.getSubstitutionFilter() != null && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) { - substitutionMapping.setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); + private Optional convertSubstitutionMappingFilter(final Component component) { + if (component.getSubstitutionFilter() == null || (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() == null) { + return Optional.empty(); } + + return Optional.ofNullable(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); } private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) { @@ -544,18 +580,9 @@ public class ToscaExportHandler { toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig) : new ArrayList<>(toscaTemplate.getImports()); List> dependencies = new ArrayList<>(); Map toscaArtifacts = component.getToscaArtifacts(); - if (isNotEmpty(toscaArtifacts)) { - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); - if (artifactDefinition != null) { - Map> importsListMember = new HashMap<>(); - Map interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); - StringBuilder keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-").append(component.getName()) - .append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - additionalImports.add(importsListMember); - } + final Map> substituteTypeImportEntry = generateComponentSubstituteTypeImport(component, toscaArtifacts); + if (!substituteTypeImportEntry.isEmpty()) { + additionalImports.add(substituteTypeImportEntry); } List componentInstances = component.getComponentInstances(); if (componentInstances != null && !componentInstances.isEmpty()) { @@ -569,6 +596,25 @@ public class ToscaExportHandler { return Either.left(new ImmutablePair<>(toscaTemplate, componentCache)); } + private Map> generateComponentSubstituteTypeImport(final Component component, + final Map toscaArtifacts) { + + if (component instanceof Service && !((Service) component).isSubstituteCandidate()) { + return Collections.emptyMap(); + } + if (MapUtils.isEmpty(toscaArtifacts)) { + return Collections.emptyMap(); + } + final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); + if (artifactDefinition == null) { + return Collections.emptyMap(); + } + final var importEntryName = component.getComponentType().toString().toLowerCase() + "-" + component.getName() + "-interface"; + return Map.of(importEntryName, + Map.of(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())) + ); + } + private List>> getDefaultToscaImportConfig() { return getConfiguration().getDefaultImports(); } @@ -1459,20 +1505,21 @@ public class ToscaExportHandler { return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; } - private Either convertCapabilities(Component component, SubstitutionMapping substitutionMappings, - Map componentCache) { - Either result = Either.left(substitutionMappings); - Either, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter - .convertSubstitutionMappingCapabilities(componentCache, component); + private Either, ToscaError> convertSubstitutionMappingCapabilities(final Component component, + final Map componentCache) { + Either, ToscaError> toscaCapabilitiesRes = + capabilityRequirementConverter.convertSubstitutionMappingCapabilities(componentCache, component); if (toscaCapabilitiesRes.isRight()) { - result = Either.right(toscaCapabilitiesRes.right().value()); log.debug("Failed convert capabilities for the component {}. ", component.getName()); - } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) { - substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); + return Either.right(toscaCapabilitiesRes.right().value()); + } + if (isNotEmpty(toscaCapabilitiesRes.left().value())) { log.debug("Finish convert capabilities for the component {}. ", component.getName()); + return Either.left(toscaCapabilitiesRes.left().value()); } log.debug("Finished to convert capabilities for the component {}. ", component.getName()); - return result; + + return Either.left(Collections.emptyMap()); } private Either convertCapabilities(Map componentsCache, Component component, ToscaNodeType nodeType, diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java index a2dc5091e9..b9fb5b10cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.Map; import lombok.Getter; import lombok.Setter; +import org.apache.commons.collections.MapUtils; @Getter public class ToscaTopolgyTemplate { @@ -53,4 +54,14 @@ public class ToscaTopolgyTemplate { } this.policies.putAll(policiesMap); } + + public boolean isEmpty() { + return substitution_mappings == null && + MapUtils.isEmpty(inputs) && + MapUtils.isEmpty(outputs) && + MapUtils.isEmpty(node_templates) && + MapUtils.isEmpty(groups) && + MapUtils.isEmpty(policies) && + MapUtils.isEmpty(relationshipTemplates); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java index 117ef9cc5a..1416707835 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java @@ -270,8 +270,8 @@ public class ElementOperationMock implements IElementOperation { } @Override - public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { - // TODO Auto-generated method stub + public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, + boolean inTransaction) { return null; } @@ -282,9 +282,14 @@ public class ElementOperationMock implements IElementOperation { } @Override - public List getBaseTypes(String categoryName, String modelName) { + public List getServiceBaseTypes(String categoryName, String modelName) { // TODO Auto-generated method stub return null; } + @Override + public boolean isBaseTypeRequired(String categoryName) { + return true; + } + } 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 index 268534a67a..ee37ea130d 100644 --- 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 @@ -40,7 +40,6 @@ import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogicTest; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.components.path.ForwardingPathValidator; import org.openecomp.sdc.be.components.utils.ComponentBusinessLogicMock; @@ -75,12 +74,9 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; public abstract class BaseServiceBusinessLogicTest extends ComponentBusinessLogicMock { - private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); private static final String SERVICE_CATEGORY = "Mobility"; private final ServletContext servletContext = Mockito.mock(ServletContext.class); private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java index 8eb840a664..9fb0efb862 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java @@ -21,6 +21,9 @@ */ package org.openecomp.sdc.be.components.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; @@ -35,15 +38,12 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; @@ -66,8 +66,7 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -@RunWith(MockitoJUnitRunner.class) -public class ElementBusinessLogicTest extends BaseBusinessLogicMock { +class ElementBusinessLogicTest extends BaseBusinessLogicMock { private User user; @@ -89,9 +88,9 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { @InjectMocks private ElementBusinessLogic elementBusinessLogic; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); elementBusinessLogic = new ElementBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, elementDao, userAdminManager); elementBusinessLogic.setComponentsUtils(componentsUtils); @@ -103,7 +102,7 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { } @Test - public void testGetFollowed_givenUserWithDesignerRole_thenReturnsSuccessful() { + void testGetFollowed_givenUserWithDesignerRole_thenReturnsSuccessful() { user.setUserId("designer1"); user.setRole(Role.DESIGNER.name()); @@ -123,23 +122,23 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { .thenReturn(Either.left(services)); Map> result = elementBusinessLogic.getFollowed(user).left().value(); - Assert.assertTrue(result.get("services").size() == 1); - Assert.assertTrue(result.get("resources").size() == 1); + assertEquals(1, result.get("services").size()); + assertEquals(1, result.get("resources").size()); } @Test - public void testGetFollowed_givenUserWithProductStrategistRole_thenReturnsEmptyList() { + void testGetFollowed_givenUserWithProductStrategistRole_thenReturnsEmptyList() { user.setUserId("pstra1"); user.setRole(Role.PRODUCT_STRATEGIST.name()); Map> result = elementBusinessLogic.getFollowed(user).left().value(); - Assert.assertEquals("products list should be empty", 0, result.get("products").size()); + assertEquals(0, result.get("products").size(), "products list should be empty"); } @Test - public void testGetFollowed_givenUserWithProductManagerRole_thenReturnsProducts() { + void testGetFollowed_givenUserWithProductManagerRole_thenReturnsProducts() { user.setUserId("pmanager1"); user.setRole(Role.PRODUCT_MANAGER.name()); @@ -150,83 +149,79 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { .thenReturn(Either.left(products)); Map> result = elementBusinessLogic.getFollowed(user).left().value(); - Assert.assertEquals("1 product should exist", 1, result.get("products").size()); - + assertEquals(1, result.get("products").size(), "1 product should exist"); } @Test - public void testGetFollowed_givenUserWithRoleAdminErrorOccursGettingResources_thenReturnsError() { + void testGetFollowed_givenUserWithRoleAdminErrorOccursGettingResources_thenReturnsError() { user.setUserId("admin1"); user.setRole(Role.ADMIN.name()); when(toscaOperationFacade.getFollowed(any(), anySet(), any(), eq(ComponentTypeEnum.RESOURCE))) .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - Assert.assertTrue(elementBusinessLogic.getFollowed(user).isRight()); + assertTrue(elementBusinessLogic.getFollowed(user).isRight()); } @Test - public void testGetAllCategories_givenUserIsNull_thenReturnsError() { - Assert.assertTrue(elementBusinessLogic.getAllCategories(null, null).isRight()); + void testGetAllCategories_givenUserIsNull_thenReturnsError() { + assertTrue(elementBusinessLogic.getAllCategories(null, null).isRight()); } - @Test(expected = ComponentException.class) - public void testGetAllCategories_givenValidationOfUserFails_thenReturnsError() { - doThrow(new ByResponseFormatComponentException(new ResponseFormat())).when(userValidations).validateUserExists(eq(user.getUserId())); - elementBusinessLogic.getAllCategories(null, user.getUserId()); + @Test + void testGetAllCategories_givenValidationOfUserFails_thenReturnsError() { + final String userId = user.getUserId(); + doThrow(new ByResponseFormatComponentException(new ResponseFormat())).when(userValidations).validateUserExists(userId); + assertThrows(ComponentException.class, () -> elementBusinessLogic.getAllCategories(null, userId)); } @Test - public void testGetAllCategories_givenInvalidComponentType_thenReturnsError() { - when(userValidations.validateUserExists(eq(user.getUserId()))).thenReturn(user); - - Assert.assertTrue(elementBusinessLogic.getAllCategories("NONE", user.getUserId()).isRight()); + void testGetAllCategories_givenInvalidComponentType_thenReturnsError() { + when(userValidations.validateUserExists(user.getUserId())).thenReturn(user); + assertTrue(elementBusinessLogic.getAllCategories("NONE", user.getUserId()).isRight()); } @Test - public void testGetAllCategories_givenValidUserAndComponentType_thenReturnsSuccessful() { - + void testGetAllCategories_givenValidUserAndComponentType_thenReturnsSuccessful() { List categoryDefinitionList = new ArrayList<>(); categoryDefinitionList.add(new CategoryDefinition()); - when(userValidations.validateUserExists(eq(user.getUserId()))).thenReturn(user); + when(userValidations.validateUserExists(user.getUserId())).thenReturn(user); when(elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, false)) .thenReturn(Either.left(categoryDefinitionList)); - Assert.assertTrue(elementBusinessLogic.getAllCategories(ComponentTypeEnum.RESOURCE_PARAM_NAME, user.getUserId()) + assertTrue(elementBusinessLogic.getAllCategories(ComponentTypeEnum.RESOURCE_PARAM_NAME, user.getUserId()) .isLeft()); } @Test - public void testGetAllCategories_givenValidUserId_thenReturnsSuccessful() { - + void testGetAllCategories_givenValidUserId_thenReturnsSuccessful() { List dummyCategoryDefinitionList = new ArrayList<>(); dummyCategoryDefinitionList.add(new CategoryDefinition()); - when(userValidations.validateUserExists(eq(user.getUserId()))) + when(userValidations.validateUserExists(user.getUserId())) .thenReturn(user); when(elementDao.getAllCategories(any(NodeTypeEnum.class), anyBoolean())) .thenReturn(Either.left(dummyCategoryDefinitionList)); - Assert.assertTrue(elementBusinessLogic.getAllCategories(user.getUserId()).isLeft()); + assertTrue(elementBusinessLogic.getAllCategories(user.getUserId()).isLeft()); } @Test - public void testDeleteCategory_givenValidComponentTypeAndCategoryId_thenReturnsSuccessful() { - + void testDeleteCategory_givenValidComponentTypeAndCategoryId_thenReturnsSuccessful() { when(elementDao.deleteCategory(any(NodeTypeEnum.class), anyString())) .thenReturn(Either.left(new CategoryDefinition())); - Assert.assertTrue(elementBusinessLogic.deleteCategory("cat1", "resources", user.getUserId()).isLeft()); + assertTrue(elementBusinessLogic.deleteCategory("cat1", "resources", user.getUserId()).isLeft()); } @Test - public void testCreateSubCategory_givenValidSubCategory_thenReturnsSuccessful() { + void testCreateSubCategory_givenValidSubCategory_thenReturnsSuccessful() { user.setRole(Role.ADMIN.name()); SubCategoryDefinition subCatDef = new SubCategoryDefinition(); subCatDef.setName("subCat1"); - when(userValidations.validateUserExists(eq(user.getUserId()))) + when(userValidations.validateUserExists(user.getUserId())) .thenReturn(user); when(elementDao.getCategory(any(NodeTypeEnum.class), anyString())) .thenReturn(Either.left(new CategoryDefinition())); @@ -237,48 +232,49 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { when(elementDao.createSubCategory(anyString(), any(SubCategoryDefinition.class), any(NodeTypeEnum.class))) .thenReturn(Either.left(subCatDef)); - Assert.assertTrue(elementBusinessLogic.createSubCategory(subCatDef, "resources", + assertTrue(elementBusinessLogic.createSubCategory(subCatDef, "resources", "cat1", user.getUserId()).isLeft()); } @Test - public void testCreateSubCategory_givenNullSubCategory_thenReturnsError() { - Assert.assertTrue(elementBusinessLogic.createSubCategory(null, "resources", + void testCreateSubCategory_givenNullSubCategory_thenReturnsError() { + assertTrue(elementBusinessLogic.createSubCategory(null, "resources", "cat1", user.getUserId()).isRight()); } - @Test(expected = ComponentException.class) - public void testCreateSubCategory_givenUserValidationFails_thenReturnsException() { + @Test + void testCreateSubCategory_givenUserValidationFails_thenReturnsException() { SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(); - doThrow(new ByResponseFormatComponentException(new ResponseFormat())).when(userValidations).validateUserExists(eq(user.getUserId())); - elementBusinessLogic.createSubCategory(subCategoryDefinition, "resources", "cat1", user.getUserId()); + final String userId = user.getUserId(); + doThrow(new ByResponseFormatComponentException(new ResponseFormat())).when(userValidations).validateUserExists(userId); + assertThrows(ComponentException.class, + () -> elementBusinessLogic.createSubCategory(subCategoryDefinition, "resources", "cat1", userId)); } - @Test(expected = ComponentException.class) - public void testcreateCategory_VALIDATION_OF_USER_FAILED() { + @Test + void testcreateCategory_VALIDATION_OF_USER_FAILED() { CategoryDefinition catdefinition = new CategoryDefinition(); String userid = ""; ResponseFormat responseFormat = new ResponseFormat(7); when(userValidations.validateUserExists("")).thenThrow(new ByResponseFormatComponentException(responseFormat)); - elementBusinessLogic.createCategory(catdefinition, "Service", userid); + assertThrows(ComponentException.class, () -> elementBusinessLogic.createCategory(catdefinition, "Service", userid)); } @Test - public void testcreateCategory_MISSING_INFORMATION() throws Exception { + void testcreateCategory_MISSING_INFORMATION() { CategoryDefinition catdefinition = new CategoryDefinition(); ResponseFormat responseFormat = new ResponseFormat(9); User user = new User(); when(userValidations.validateUserExists("USR")).thenReturn(user); when(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(responseFormat); Either response = elementBusinessLogic.createCategory(catdefinition, "Service", "USR"); - Assert.assertTrue(response.isRight()); - Assert.assertEquals((Integer) 9, response.right().value().getStatus()); + assertTrue(response.isRight()); + assertEquals((Integer) 9, response.right().value().getStatus()); } @Test - public void testcreateCategory_Invalid_componentType() throws Exception { - + void testcreateCategory_Invalid_componentType() { CategoryDefinition catdefinition = new CategoryDefinition(); catdefinition.setName("CAT01"); ResponseFormat responseFormat = new ResponseFormat(9); @@ -287,13 +283,12 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { when(userValidations.validateUserExists("USR")).thenReturn(user); when(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(responseFormat); Either response = elementBusinessLogic.createCategory(catdefinition, "Service", "USR"); - Assert.assertTrue(response.isRight()); - Assert.assertEquals((Integer) 9, response.right().value().getStatus()); + assertTrue(response.isRight()); + assertEquals((Integer) 9, response.right().value().getStatus()); } @Test - public void testcreateCategory_Invalid() throws Exception { - + void testcreateCategory_Invalid() { CategoryDefinition catdefinition = new CategoryDefinition(); catdefinition.setName("CAT01"); ResponseFormat responseFormat = new ResponseFormat(9); @@ -302,26 +297,26 @@ public class ElementBusinessLogicTest extends BaseBusinessLogicMock { when(userValidations.validateUserExists("USR")).thenReturn(user); when(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(responseFormat); Either response = elementBusinessLogic.createCategory(catdefinition, "SERVICE_PARAM_NAME", "USR"); - Assert.assertTrue(response.isRight()); - Assert.assertEquals((Integer) 9, response.right().value().getStatus()); + assertTrue(response.isRight()); + assertEquals((Integer) 9, response.right().value().getStatus()); } @Test - public void testGetBaseTypes_givenValidUserAndComponentType_thenReturnsSuccessful() { - + void testGetBaseTypes_givenValidUserAndComponentType_thenReturnsSuccessful() { List baseTypes = new ArrayList<>(); baseTypes.add(new BaseType("org.openecomp.type")); String categoryName = "CAT01"; String modelName = "MODEL01"; - when(userValidations.validateUserExistsActionStatus(eq(user.getUserId()))).thenReturn(ActionStatus.OK); - when(elementDao.getBaseTypes(categoryName, modelName)).thenReturn(baseTypes); - Assert.assertTrue(elementBusinessLogic.getBaseTypes(categoryName, user.getUserId(), modelName).isLeft()); + when(userValidations.validateUserExistsActionStatus(user.getUserId())).thenReturn(ActionStatus.OK); + when(elementDao.getServiceBaseTypes(categoryName, modelName)).thenReturn(baseTypes); + assertTrue(elementBusinessLogic.getBaseTypes(categoryName, user.getUserId(), modelName).isLeft()); } @Test - public void testGetBaseTypes_givenUserValidationFails_thenReturnsException() { - when(userValidations.validateUserExistsActionStatus(eq(user.getUserId()))).thenReturn(ActionStatus.RESTRICTED_OPERATION); - Assert.assertTrue(elementBusinessLogic.getBaseTypes("CAT01", user.getUserId(), null).isRight()); + void testGetBaseTypes_givenUserValidationFails_thenReturnsException() { + when(userValidations.validateUserExistsActionStatus(user.getUserId())).thenReturn(ActionStatus.RESTRICTED_OPERATION); + assertTrue(elementBusinessLogic.getBaseTypes("CAT01", user.getUserId(), null).isRight()); } + } \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicBaseTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicBaseTestSetup.java new file mode 100644 index 0000000000..44daa34aeb --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicBaseTestSetup.java @@ -0,0 +1,397 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import javax.servlet.ServletContext; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mockito; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceCategoryValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceEnvironmentContextValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceFieldValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceFunctionValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceInstantiationTypeValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceNamingPolicyValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceRoleValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceTypeValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceValidator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +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.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.jsonjanusgraph.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.GraphLockOperation; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +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.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.web.context.WebApplicationContext; + +class ServiceBusinessLogicBaseTestSetup extends BaseBusinessLogicMock { + + protected ServiceBusinessLogic bl; + protected static final String SERVICE_CATEGORY = "Mobility"; + protected static final String INSTANTIATION_TYPE = "A-la-carte"; + 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 ResponseFormatManager responseManager = null; + protected ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + protected AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + protected ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + protected GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + protected JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); + protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + protected GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + protected UserValidations userValidations = Mockito.mock(UserValidations.class); + protected ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class); + protected CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class); + protected ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class); + protected ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class); + IElementOperation mockElementDao = new ElementOperationMock(); + DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); + ServiceDistributionValidation serviceDistributionValidation = Mockito.mock(ServiceDistributionValidation.class); + ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class); + ForwardingPathValidator forwardingPathValidator = Mockito.mock(ForwardingPathValidator.class); + UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class); + protected ServiceTypeValidator serviceTypeValidator = new ServiceTypeValidator(componentsUtils); + protected ServiceCategoryValidator serviceCategoryValidator = new ServiceCategoryValidator(componentsUtils, mockElementDao); + protected ServiceRoleValidator serviceRoleValidator = new ServiceRoleValidator(componentsUtils); + protected ServiceFunctionValidator serviceFunctionValidator = new ServiceFunctionValidator(componentsUtils); + protected ServiceInstantiationTypeValidator serviceInstantiationTypeValidator = new ServiceInstantiationTypeValidator(componentsUtils); + protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils); + protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils); + protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils); + protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils); + protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils); + protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade); + protected final ComponentValidator componentValidator = Mockito.mock(ComponentValidator.class); + protected ServiceValidator serviceValidator = createServiceValidator(); + + protected User user = null; + protected 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 final String SERVICE_ROLE = JsonPresentationFields.SERVICE_ROLE.getPresentation(); + protected static final String SERVICE_TYPE = JsonPresentationFields.SERVICE_TYPE.getPresentation(); + protected static final String SERVICE_FUNCTION = JsonPresentationFields.SERVICE_FUNCTION.getPresentation(); + + public ServiceBusinessLogicBaseTestSetup() { + + } + + protected ServiceValidator createServiceValidator() { + List componentFieldValidators = Arrays.asList(componentContactIdValidator, + componentDescriptionValidator, + componentIconValidator, componentNameValidator, + new ComponentProjectCodeValidator(componentsUtils), + componentTagsValidator); + + List serviceFieldValidators = Arrays.asList(serviceCategoryValidator, new ServiceEnvironmentContextValidator(), + serviceInstantiationTypeValidator, new ServiceNamingPolicyValidator(componentsUtils), + serviceRoleValidator, serviceTypeValidator); + return new ServiceValidator(componentsUtils, componentFieldValidators, serviceFieldValidators); + } + + + + @BeforeEach + public void setup() { + + // Elements + IElementOperation mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user); + when(userValidations.validateUserExists(eq("jh0003"))).thenReturn(user); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user); + 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); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.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 + Service serviceResponse = createServiceObject(true); + Either eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + when(userValidations.validateUserExists(user)).thenReturn(user); + + genericService = setupGenericServiceMock(); + Either findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + + bl = new ServiceBusinessLogic(elementDao, groupOperation, groupInstanceOperation, + groupTypeOperation, groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, + artifactBl, distributionEngine, componentInstanceBusinessLogic, + serviceDistributionValidation, forwardingPathValidator, uiComponentDataConverter, + artifactToscaOperation, componentContactIdValidator, + componentNameValidator, componentTagsValidator, componentValidator, + componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); + bl.setComponentContactIdValidator(componentContactIdValidator); + bl.setComponentIconValidator(componentIconValidator); + bl.setComponentTagsValidator(componentTagsValidator); + bl.setComponentNameValidator(componentNameValidator); + bl.setComponentDescriptionValidator(componentDescriptionValidator); + bl.setComponentProjectCodeValidator(componentProjectCodeValidator); + bl.setServiceCategoryValidator(serviceCategoryValidator); + bl.setServiceTypeValidator(serviceTypeValidator); + bl.setServiceFunctionValidator(serviceFunctionValidator); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setServiceValidator(createServiceValidator()); + bl.setGraphLockOperation(graphLockOperation); + bl.setJanusGraphDao(mockJanusGraphDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setUserValidations(userValidations); + bl.setCatalogOperations(catalogOperation); + + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setUniqueId("sid"); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + category.setIcons(Collections.singletonList("defaulticon")); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setInstantiationType(INSTANTIATION_TYPE); + + service.setDescription("description"); + List tgs = new ArrayList<>(); + tgs.add(service.getName()); + service.setTags(tgs); + service.setIcon("defaulticon"); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + service.setEcompGeneratedNaming(true); + + 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() { + 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"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + + 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"); + 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"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + List list = new ArrayList<>() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List listPrev = new ArrayList<>(); + Either, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List listCurr = new ArrayList<>() { + { + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + Either, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2)); + when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList); + + Either, ActionStatus> restoreAuditList = Either.left(Collections.singletonList(auditRestore)); + when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList); + + } + + protected 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"); + + List notifyResults = Collections.singletonList(notifyEvent); + Either, ActionStatus> eitherNotify = Either.left(notifyResults); + + Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); + + List requestResults = Collections.singletonList(requestEvent); + Either, ActionStatus> eitherRequest = Either.left(requestResults); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); + + Either eitherService = Either.left(createServiceObject(true)); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); + + Either, ActionStatus> emptyEventList = Either.left(Collections.emptyList()); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); + } + + private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + assertResponse(createResponse.right().value(), expectedStatus, variables); + } + + protected void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) { + ResponseFormat actualResponse = e.getResponseFormat() != null ? + e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + assertResponse(actualResponse, expectedStatus, variables); + } + + protected void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals(expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage(), "assert error description"); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java index a64e3c1c85..5c074b0599 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java @@ -24,11 +24,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -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.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; import com.google.common.collect.Lists; @@ -42,8 +43,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -72,28 +72,27 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.http.HttpStatus; -public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup { +class ServiceBusinessLogicTest extends ServiceBusinessLogicBaseTestSetup { private final static String DEFAULT_ICON = "defaulticon"; private static final String ALREADY_EXIST = "alreadyExist"; - private static final String DOES_NOT_EXIST = "doesNotExist"; @Test - public void testGetComponentAuditRecordsCertifiedVersion() { + void testGetComponentAuditRecordsCertifiedVersion() { Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); assertTrue(componentAuditRecords.isLeft()); assertEquals(3, componentAuditRecords.left().value().size()); } @Test - public void testGetComponentAuditRecordsUnCertifiedVersion() { + void testGetComponentAuditRecordsUnCertifiedVersion() { Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); assertTrue(componentAuditRecords.isLeft()); assertEquals(4, componentAuditRecords.left().value().size()); } @Test - public void testHappyScenario() { + void testHappyScenario() { Service service = createServiceObject(false); when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService)); Either createResponse = bl.createService(service, user); @@ -105,7 +104,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testServiceCreationPluginCall() { + void testServiceCreationPluginCall() { final Service service = createServiceObject(false); when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService)); final List serviceCreationPlugins = new ArrayList<>(); @@ -138,7 +137,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup @Test - public void testCreateServiceWhenGenericTypeHasProperties() { + void testCreateServiceWhenGenericTypeHasProperties() { final Service service = createServiceObject(false); final Resource genericTypeResource = mockGenericTypeResource(); @@ -158,7 +157,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testCreateServiceWhenGenericTypeAndServiceHasProperties() { + void testCreateServiceWhenGenericTypeAndServiceHasProperties() { final Service service = createServiceObject(false); service.setProperties(mockPropertyList()); service.getProperties().remove(0); @@ -185,7 +184,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testHappyScenarioCRNullProjectCode() { + void testHappyScenarioCRNullProjectCode() { Service service = createServiceObject(false); service.setProjectCode(null); when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService)); @@ -198,7 +197,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testHappyScenarioCREmptyStringProjectCode() { + void testHappyScenarioCREmptyStringProjectCode() { createServiceValidator(); Service service = createServiceObject(false); service.setProjectCode(""); @@ -242,7 +241,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup // Service name - start @Test - public void testFailedServiceValidations() { + void testFailedServiceValidations() { testServiceNameAlreadyExists(); testServiceNameEmpty(); @@ -504,7 +503,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup fail(); } @Test - public void markDistributionAsDeployedTestAlreadyDeployed() { + void markDistributionAsDeployedTestAlreadyDeployed() { String notifyAction = "DNotify"; String requestAction = "DRequest"; String resultAction = "DResult"; @@ -533,7 +532,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void markDistributionAsDeployedTestSuccess() { + void markDistributionAsDeployedTestSuccess() { String notifyAction = "DNotify"; String requestAction = "DRequest"; String did = "123456"; @@ -547,7 +546,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void markDistributionAsDeployedTestNotDistributed() { + void markDistributionAsDeployedTestNotDistributed() { String notifyAction = "DNotify"; String requestAction = "DRequest"; String did = "123456"; @@ -632,7 +631,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testDeleteMarkedServices() { + void testDeleteMarkedServices() { List ids = new ArrayList<>(); List responseIds = new ArrayList<>(); String resourceInUse = "123"; @@ -658,13 +657,12 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup assertFalse(resourceIdList.isEmpty()); assertTrue(resourceIdList.contains(resourceFree)); assertFalse(resourceIdList.contains(resourceInUse)); - } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test - public void testFindGroupInstanceOnRelatedComponentInstance() { + void testFindGroupInstanceOnRelatedComponentInstance() { Class targetClass = ServiceBusinessLogic.class; String methodName = "findGroupInstanceOnRelatedComponentInstance"; @@ -739,21 +737,33 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup return (Service)createNewComponent(); } - @Test - public void testDerivedFromGeneric() { + void testDerivedFromGeneric() { Service service = createServiceObject(true); + service.setDerivedFromGenericInfo(genericService); when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService)); Either createResponse = bl.createService(service, user); assertTrue(createResponse.isLeft()); service = createResponse.left().value(); - assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName()); - assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion()); + assertEquals(genericService.getToscaResourceName(), service.getDerivedFromGenericType()); + assertEquals(genericService.getVersion(), service.getDerivedFromGenericVersion()); + } + + @Test + void testServiceWithoutDerivedFromGeneric() { + final Service service = createServiceObject(true); + when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService)); + final Either createResponse = bl.createService(service, user); + assertTrue(createResponse.isLeft()); + final Service actualService = createResponse.left().value(); + assertNull(actualService.getDerivedFromGenericType()); + assertNull(actualService.getDerivedFromGenericVersion()); } @Test - public void testUpdateMetadataNamingPolicy() { + void testUpdateMetadataNamingPolicy() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setEcompGeneratedNaming(false); @@ -767,7 +777,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testUpdateMetadataToEmptyProjectCode() { + void testUpdateMetadataToEmptyProjectCode() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setProjectCode("12345"); @@ -779,7 +789,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testUpdateMetadataFromEmptyProjectCode() { + void testUpdateMetadataFromEmptyProjectCode() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setProjectCode(""); @@ -791,7 +801,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testUpdateMetadataProjectCode() { + void testUpdateMetadataProjectCode() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setProjectCode("33333"); @@ -803,7 +813,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testUpdateMetadataServiceType() { + void testUpdateMetadataServiceType() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setServiceType("alice"); @@ -824,13 +834,13 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testCreateDefaultMetadataServiceFunction() { + void testCreateDefaultMetadataServiceFunction() { Service currentService = createServiceObject(true); assertThat(currentService.getServiceFunction()).isEqualTo(""); } @Test - public void testCreateCustomMetadataServiceFunction() { + void testCreateCustomMetadataServiceFunction() { String customServiceFunctionName = "customName"; Service currentService = createServiceObject(true); currentService.setServiceFunction(customServiceFunctionName); @@ -838,7 +848,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testUpdateMetadataServiceFunction() { + void testUpdateMetadataServiceFunction() { Service currentService = createServiceObject(true); Service newService = createServiceObject(false); currentService.setServiceFunction("alice"); @@ -862,7 +872,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup @Test - public void testServiceFunctionExceedLength() { + void testServiceFunctionExceedLength() { String serviceName = "Service"; String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; Service serviceFunctionExceedLength = createServiceObject(false); @@ -879,7 +889,7 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testServiceFunctionInvalidCharacter(){ + void testServiceFunctionInvalidCharacter(){ String serviceName = "Service"; String serviceFunction = "a?"; Service serviceFunctionExceedLength = createServiceObject(false); @@ -896,30 +906,30 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup } @Test - public void testAddPropertyServiceConsumptionServiceNotFound() { + void testAddPropertyServiceConsumptionServiceNotFound() { Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); Either operationEither = bl.addPropertyServiceConsumption("1", "2", "3", user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } @Test - public void testAddPropertyServiceConsumptionParentServiceIsEmpty() { + void testAddPropertyServiceConsumptionParentServiceIsEmpty() { Either eitherService = Either.left(createNewComponent()); Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); Either operationEither = bl.addPropertyServiceConsumption("1", "2", "3", user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } @Test - public void testAddPropertyServiceConsumptionNoMatchingComponent() { + void testAddPropertyServiceConsumptionNoMatchingComponent() { Service aService = createNewService(); Either eitherService = Either.left(aService); Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); @@ -929,12 +939,12 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup Either operationEither = bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3", user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } @Test - public void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() { + void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() { Service aService = createNewService(); aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId()); Either eitherService = Either.left(aService); @@ -943,12 +953,12 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup Either operationEither = bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3", user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } @Test - public void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() { + void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() { Service aService = createNewService(); aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId()); Either eitherService = Either.left(aService); @@ -964,12 +974,12 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup Either operationEither = bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3", user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } @Test - public void testAddPropertyServiceConsumptionNoInputsCandidate() { + void testAddPropertyServiceConsumptionNoInputsCandidate() { Service aService = createNewService(); aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId()); Either eitherService = Either.left(aService); @@ -990,8 +1000,8 @@ public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup Either operationEither = bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId, user.getUserId(), new ServiceConsumptionData()); - Assert.assertTrue(operationEither.isRight()); - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); + assertTrue(operationEither.isRight()); + assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue()); } private Resource mockGenericTypeResource() { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBussinessLogicBaseTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBussinessLogicBaseTestSetup.java deleted file mode 100644 index 64b84d4b00..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBussinessLogicBaseTestSetup.java +++ /dev/null @@ -1,441 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import fj.data.Either; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import javax.servlet.ServletContext; -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.distribution.engine.DistributionEngine; -import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; -import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; -import org.openecomp.sdc.be.components.path.ForwardingPathValidator; -import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; -import org.openecomp.sdc.be.components.validation.UserValidations; -import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; -import org.openecomp.sdc.be.components.validation.component.ComponentValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceCategoryValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceEnvironmentContextValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceFieldValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceFunctionValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceInstantiationTypeValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceNamingPolicyValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceRoleValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceTypeValidator; -import org.openecomp.sdc.be.components.validation.service.ServiceValidator; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao; -import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -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.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.jsonjanusgraph.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.GraphLockOperation; -import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; -import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; -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.Constants; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.web.context.WebApplicationContext; - -public class ServiceBussinessLogicBaseTestSetup extends BaseBusinessLogicMock{ - - protected ServiceBusinessLogic bl; - protected static final String SERVICE_CATEGORY = "Mobility"; - protected static final String INSTANTIATION_TYPE = "A-la-carte"; - 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 ResponseFormatManager responseManager = null; - protected ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); - protected AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); - protected ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); - protected GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - protected JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); - protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - protected GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - protected UserValidations userValidations = Mockito.mock(UserValidations.class); - protected ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class); - protected CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class); - protected ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class); - protected ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class); - IElementOperation mockElementDao = new ElementOperationMock(); - DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); - ServiceDistributionValidation serviceDistributionValidation = Mockito.mock(ServiceDistributionValidation.class); - ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class); - ForwardingPathValidator forwardingPathValidator = Mockito.mock(ForwardingPathValidator.class); - UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class); - protected ServiceTypeValidator serviceTypeValidator = new ServiceTypeValidator(componentsUtils); - protected ServiceCategoryValidator serviceCategoryValidator = new ServiceCategoryValidator(componentsUtils, mockElementDao); - protected ServiceRoleValidator serviceRoleValidator = new ServiceRoleValidator(componentsUtils); - protected ServiceFunctionValidator serviceFunctionValidator = new ServiceFunctionValidator(componentsUtils); - protected ServiceInstantiationTypeValidator serviceInstantiationTypeValidator = new ServiceInstantiationTypeValidator(componentsUtils); - protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils); - protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils); - protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils); - protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils); - protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils); - protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade); - protected final ComponentValidator componentValidator = Mockito.mock(ComponentValidator.class); - protected ServiceValidator serviceValidator = createServiceValidator(); - - protected User user = null; - protected 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 final String SERVICE_ROLE = JsonPresentationFields.SERVICE_ROLE.getPresentation(); - protected static final String SERVICE_TYPE = JsonPresentationFields.SERVICE_TYPE.getPresentation(); - protected static final String SERVICE_FUNCTION = JsonPresentationFields.SERVICE_FUNCTION.getPresentation(); - - public ServiceBussinessLogicBaseTestSetup() { - - } - - protected ServiceValidator createServiceValidator() { - List componentFieldValidators = Arrays.asList(componentContactIdValidator, - componentDescriptionValidator, - componentIconValidator, componentNameValidator, - new ComponentProjectCodeValidator(componentsUtils), - componentTagsValidator); - - List serviceFieldValidators = Arrays.asList(serviceCategoryValidator, new ServiceEnvironmentContextValidator(), - serviceInstantiationTypeValidator, new ServiceNamingPolicyValidator(componentsUtils), - serviceRoleValidator, serviceTypeValidator); - return new ServiceValidator(componentsUtils, componentFieldValidators, serviceFieldValidators); - } - - - - @Before - public void setup() { - - // Elements - IElementOperation mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user); - when(userValidations.validateUserExists(eq("jh0003"))).thenReturn(user); - when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(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); - when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.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 - Service serviceResponse = createServiceObject(true); - Either eitherCreate = Either.left(serviceResponse); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); - Either eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); - Either eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); - when(userValidations.validateUserExists(user)).thenReturn(user); - - genericService = setupGenericServiceMock(); - Either findLatestGeneric = Either.left(genericService); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); - - - bl = new ServiceBusinessLogic(elementDao, groupOperation, groupInstanceOperation, - groupTypeOperation, groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, - artifactBl, distributionEngine, componentInstanceBusinessLogic, - serviceDistributionValidation, forwardingPathValidator, uiComponentDataConverter, - artifactToscaOperation, componentContactIdValidator, - componentNameValidator, componentTagsValidator, componentValidator, - componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); - bl.setComponentContactIdValidator(componentContactIdValidator); - bl.setComponentIconValidator(componentIconValidator); - bl.setComponentTagsValidator(componentTagsValidator); - bl.setComponentNameValidator(componentNameValidator); - bl.setComponentDescriptionValidator(componentDescriptionValidator); - bl.setComponentProjectCodeValidator(componentProjectCodeValidator); - bl.setServiceCategoryValidator(serviceCategoryValidator); - bl.setServiceTypeValidator(serviceTypeValidator); - bl.setServiceFunctionValidator(serviceFunctionValidator); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setArtifactBl(artifactBl); - bl.setServiceValidator(createServiceValidator()); - bl.setGraphLockOperation(graphLockOperation); - bl.setJanusGraphDao(mockJanusGraphDao); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - bl.setComponentsUtils(componentsUtils); - bl.setCassandraAuditingDao(auditingDao); - bl.setUserValidations(userValidations); - bl.setCatalogOperations(catalogOperation); - - mockAuditingDaoLogic(); - - responseManager = ResponseFormatManager.getInstance(); - - - } - - protected Resource setupGenericServiceMock(){ - Resource genericService = new Resource(); - genericService.setVersion("1.0"); - genericService.setToscaResourceName(GENERIC_SERVICE_NAME); - return genericService; - } - - protected Service createServiceObject(boolean afterCreate) { - Service service = new Service(); - service.setUniqueId("sid"); - service.setName("Service"); - CategoryDefinition category = new CategoryDefinition(); - category.setName(SERVICE_CATEGORY); - category.setIcons(Collections.singletonList("defaulticon")); - List categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setInstantiationType(INSTANTIATION_TYPE); - - service.setDescription("description"); - List tgs = new ArrayList<>(); - tgs.add(service.getName()); - service.setTags(tgs); - // service.setVendorName("Motorola"); - // service.setVendorRelease("1.0.0"); - service.setIcon("defaulticon"); - // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - service.setContactId("aa1234"); - service.setProjectCode("12345"); - service.setEcompGeneratedNaming(true); - - 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() { - 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, - // ActionStatus> >() { - // public Either, ActionStatus> - // answer(InvocationOnMock invocation) { - // final Either, ActionStatus> either; - // final List list; - // Object[] args = invocation.getArguments(); - // Map filterMap = - // (Map) args[0]; - // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ - // list = new - // ArrayList(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; - // either = Either.left(list); - // - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ - // list = new ArrayList(); - // either = Either.left(list); - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ - // list = new - // ArrayList(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; - // either = Either.left(list); - // } - // else{ - // either = null; - // } - // return either; - // } - // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); - // - // - List list = new ArrayList() { - { - add(createResourceAudit); - add(checkInResourceAudit); - add(checkOutResourceAudit); - } - }; - Either, ActionStatus> result = Either.left(list); - Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); - - List listPrev = new ArrayList<>(); - Either, ActionStatus> resultPrev = Either.left(listPrev); - Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); - - List listCurr = new ArrayList() { - { - add(checkOutResourceAudit); - } - }; - Either, ActionStatus> resultCurr = Either.left(listCurr); - Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); - - Either, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2)); - when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList); - - Either, ActionStatus> restoreAuditList = Either.left(Collections.singletonList(auditRestore)); - when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList); - - } - - protected 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"); - - List notifyResults = Collections.singletonList(notifyEvent); - Either, ActionStatus> eitherNotify = Either.left(notifyResults); - - Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); - - List requestResults = Collections.singletonList(requestEvent); - Either, ActionStatus> eitherRequest = Either.left(requestResults); - Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); - - Either eitherService = Either.left(createServiceObject(true)); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); - - Either, ActionStatus> emptyEventList = Either.left(Collections.emptyList()); - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); - } - - private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { - assertResponse(createResponse.right().value(), expectedStatus, variables); - } - - protected void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) { - ResponseFormat actualResponse = e.getResponseFormat() != null ? - e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - assertResponse(actualResponse, expectedStatus, variables); - } - - protected void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceValidationsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceValidationsTest.java index 2a33329fe4..7bc7a3c10c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceValidationsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceValidationsTest.java @@ -20,21 +20,21 @@ package org.openecomp.sdc.be.components.impl; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + import fj.data.Either; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.exception.ResponseFormat; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { +class ServiceValidationsTest extends ServiceBusinessLogicBaseTestSetup { @Test - public void testInvalidEnvironmentContext() { + void testInvalidEnvironmentContext() { Service newService = createServiceObject(false); newService.setEnvironmentContext("not valid"); try { @@ -47,7 +47,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testValidEnvironmentContext() { + void testValidEnvironmentContext() { Service newService = createServiceObject(false); newService.setEnvironmentContext("Critical_Revenue-Bearing"); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); @@ -55,14 +55,14 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testCreateServiceWithNoEnvironmentContext() { + void testCreateServiceWithNoEnvironmentContext() { Service newService = createServiceObject(false); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); assertThat(service.left().value().getEnvironmentContext()).isEqualTo("General_Revenue-Bearing"); } @Test - public void testInvalidInstantiationType() { + void testInvalidInstantiationType() { Service newService = createServiceObject(false); newService.setInstantiationType("not valid"); try { @@ -75,7 +75,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testEmptyInstantiationType() { + void testEmptyInstantiationType() { Service newService = createServiceObject(false); newService.setInstantiationType(null); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); @@ -83,7 +83,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testValidInstantiationType() { + void testValidInstantiationType() { Service newService = createServiceObject(false); newService.setInstantiationType("Macro"); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); @@ -91,7 +91,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testInvalidServiceRole() { + void testInvalidServiceRole() { Service newService = createServiceObject(false); newService.setServiceRole("gsg*"); try { @@ -104,7 +104,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testTooLongServiceRole() { + void testTooLongServiceRole() { Service newService = createServiceObject(false); newService.setServiceRole("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); try { @@ -117,7 +117,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testValidServiceRole() { + void testValidServiceRole() { Service newService = createServiceObject(false); newService.setServiceRole("role"); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); @@ -125,7 +125,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testInvalidServiceType() { + void testInvalidServiceType() { Service newService = createServiceObject(false); newService.setServiceType("gsg*"); try { @@ -138,7 +138,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testValidServiceType() { + void testValidServiceType() { Service newService = createServiceObject(false); newService.setServiceType("type"); Either service = bl.validateServiceBeforeCreate(newService, user, AuditingActionEnum.CREATE_RESOURCE); @@ -146,7 +146,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testTooLongServiceType() { + void testTooLongServiceType() { Service newService = createServiceObject(false); newService.setServiceType("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); try { @@ -159,7 +159,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testEcompGeneratedNamingIsMissing() { + void testEcompGeneratedNamingIsMissing() { Service newService = createServiceObject(false); newService.setEcompGeneratedNaming(null); try { @@ -173,7 +173,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testNamingPolicyWIthEcompNamingFalse() { + void testNamingPolicyWIthEcompNamingFalse() { Service newService = createServiceObject(false); newService.setEcompGeneratedNaming(false); newService.setNamingPolicy("policy"); @@ -182,7 +182,7 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testInvalidNamingPolicy() { + void testInvalidNamingPolicy() { Service newService = createServiceObject(false); newService.setNamingPolicy("פוליסי"); try { @@ -195,9 +195,13 @@ public class ServiceValidationsTest extends ServiceBussinessLogicBaseTestSetup { } @Test - public void testTooLongNamingPolicy() { + void testTooLongNamingPolicy() { Service newService = createServiceObject(false); - newService.setNamingPolicy("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + newService.setNamingPolicy("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); try { bl.createService(newService, user); } catch (ComponentException exp) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java index ce7a10eb28..821d4271f8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java @@ -22,11 +22,12 @@ package org.openecomp.sdc.be.tosca; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -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.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions; import static org.openecomp.sdc.be.tosca.ComponentCache.entry; @@ -35,7 +36,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -58,14 +58,13 @@ import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -95,9 +94,10 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; 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.test.BaseConfDependent; import org.openecomp.sdc.exception.ResponseFormat; -public class CsarUtilsTest extends BeConfDependentTest { +class CsarUtilsTest extends BaseConfDependent { @InjectMocks CsarUtils testSubject; @@ -120,13 +120,25 @@ public class CsarUtilsTest extends BeConfDependentTest { @Mock private ArtifactsBusinessLogic artifactsBusinessLogic; + private final List nodesFromPackage = Arrays.asList("tosca.nodes.Root", "tosca.nodes.Container.Application"); + + private final byte[] contentData; + public CsarUtilsTest() throws IOException { + contentData = getFileResource("yamlValidation/resource-serviceTemplate.yml"); } - @Before - public void setUpMock() throws Exception { + @BeforeAll + public static void setupBeforeClass() { + componentName = "catalog-be"; + confPath = "src/test/resources/config"; + setUp(); + } + + @BeforeEach + public void setUpMock() { ExternalConfiguration.setAppName("catalog-be"); - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); initConfigurationManager(); } @@ -140,18 +152,13 @@ public class CsarUtilsTest extends BeConfDependentTest { new ConfigurationManager(confSource); } - private final List nodesFromPackage = Arrays.asList("tosca.nodes.Root", "tosca.nodes.Container.Application"); - - private final byte[] contentData = getFileResource("yamlValidation/resource-serviceTemplate.yml"); - - private NonMetaArtifactInfo createNonMetaArtifactInfoTestSubject() { return new CsarUtils.NonMetaArtifactInfo("mock", "mock", ArtifactTypeEnum.AAI_SERVICE_MODEL.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, new byte[0], "mock", true); } @Test - public void testCreateCsar() { + void testCreateCsar() { Component component = new Resource(); Map toscaArtifacts = new HashMap<>(); ArtifactDefinition artifact = new ArtifactDefinition(); @@ -171,7 +178,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testCreateCsarWithGenerateCsarZipResponseIsLeft() { + void testCreateCsarWithGenerateCsarZipResponseIsLeft() { Component component = new Resource(); Map toscaArtifacts = new HashMap<>(); ArtifactDefinition artifact = new ArtifactDefinition(); @@ -214,7 +221,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenGetDependenciesIsRight() { + void testPopulateZipWhenGetDependenciesIsRight() { Component component = new Service(); boolean getFromCS = false; @@ -252,7 +259,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenExportComponentIsRight() { + void testPopulateZipWhenExportComponentIsRight() { Component component = new Resource(); boolean getFromCS = false; @@ -284,7 +291,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenComponentIsServiceAndCollectComponentCsarDefinitionIsRight() { + void testPopulateZipWhenComponentIsServiceAndCollectComponentCsarDefinitionIsRight() { Component component = new Service(); boolean getFromCS = false; @@ -355,7 +362,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenGetEntryDataIsRight() { + void testPopulateZipWhenGetEntryDataIsRight() { Component component = new Service(); boolean getFromCS = true; @@ -404,7 +411,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenGetEntryDataOfInnerComponentIsRight() { + void testPopulateZipWhenGetEntryDataOfInnerComponentIsRight() { Component component = new Service(); boolean getFromCS = false; @@ -454,7 +461,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testPopulateZipWhenLatestSchemaFilesFromCassandraIsRight() { + void testPopulateZipWhenLatestSchemaFilesFromCassandraIsRight() { Component component = new Service(); boolean getFromCS = false; @@ -507,7 +514,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testAddInnerComponentsToCache() { + void testAddInnerComponentsToCache() { ComponentCache componentCache = ComponentCache.overwritable(overwriteIfSameVersions()); Component childComponent = new Resource(); Component componentRI = new Service(); @@ -540,7 +547,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testAddInnerComponentsToCacheWhenGetToscaElementIsRight() { + void testAddInnerComponentsToCacheWhenGetToscaElementIsRight() { Map> componentCache = new HashMap<>(); Component childComponent = new Resource(); @@ -573,7 +580,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testWriteComponentInterface() throws IOException { + void testWriteComponentInterface() throws IOException { String fileName = "name.hello"; ToscaRepresentation tosca = ToscaRepresentation.make("value".getBytes()); @@ -582,14 +589,13 @@ public class CsarUtilsTest extends BeConfDependentTest { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out)) { - List> output = Deencapsulation.invoke(testSubject, "writeComponentInterface", new Resource(), zip, fileName, false); - + List> output = Deencapsulation.invoke(testSubject, "writeComponentInterface", new Resource(), zip, fileName); assertNotNull(output); } } @Test - public void testGetEntryData() { + void testGetEntryData() { String cassandraId = "id"; Component childComponent = new Resource(); @@ -603,7 +609,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testGetLatestSchemaFilesFromCassandraWhenListOfSchemasIsEmpty() { + void testGetLatestSchemaFilesFromCassandraWhenListOfSchemasIsEmpty() { List filesData = new ArrayList<>(); Mockito.when( @@ -617,7 +623,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testExtractVfcsArtifactsFromCsar() { + void testExtractVfcsArtifactsFromCsar() { String key = "Artifacts/org.openecomp.resource.some/Deployment/to/resource"; byte[] data = "value".getBytes(); @@ -632,7 +638,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testAddExtractedVfcArtifactWhenArtifactsContainsExtractedArtifactKey() { + void testAddExtractedVfcArtifactWhenArtifactsContainsExtractedArtifactKey() { ImmutablePair extractedVfcArtifact = new ImmutablePair( "key", new ArtifactDefinition()); Map> artifacts = new HashMap<>(); @@ -644,7 +650,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testAddExtractedVfcArtifactWhenArtifactsDoesntContainsExtractedArtifactKey() { + void testAddExtractedVfcArtifactWhenArtifactsDoesntContainsExtractedArtifactKey() { ImmutablePair extractedVfcArtifact = new ImmutablePair( "key", new ArtifactDefinition()); Map> artifacts = new HashMap<>(); @@ -658,7 +664,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testExtractVfcArtifact() { + void testExtractVfcArtifact() { String path = "path/to/informational/artificat"; Map map = new HashMap<>(); map.put(path, "value".getBytes()); @@ -675,7 +681,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testDetectArtifactGroupTypeWithExceptionBeingCaught() { + void testDetectArtifactGroupTypeWithExceptionBeingCaught() { Either output = Deencapsulation.invoke(testSubject, "detectArtifactGroupType", "type", Map.class); assertNotNull(output); @@ -684,7 +690,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testDetectArtifactGroupTypeWWhenCollectedWarningMessagesContainesKey() { + void testDetectArtifactGroupTypeWWhenCollectedWarningMessagesContainesKey() { Map>> collectedWarningMessages = new HashMap<>(); collectedWarningMessages.put("Warning - unrecognized artifact group type {} was received.", new HashSet<>()); @@ -696,94 +702,94 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testNonMetaArtifactInfoCtor() { + void testNonMetaArtifactInfoCtor() { createNonMetaArtifactInfoTestSubject(); } @Test - public void testNonMetaArtifactInfoGetPath() { + void testNonMetaArtifactInfoGetPath() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getPath(); } @Test - public void testNonMetaArtifactInfoGetArtifactName() { + void testNonMetaArtifactInfoGetArtifactName() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getArtifactName(); } @Test - public void testNonMetaArtifactInfoGetArtifactType() { + void testNonMetaArtifactInfoGetArtifactType() { final NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); assertThat("The artifact type should be as expected", testSubject.getArtifactType(), is(ArtifactTypeEnum.AAI_SERVICE_MODEL.getType())); } @Test - public void testNonMetaArtifactInfoGetDisplayName() { + void testNonMetaArtifactInfoGetDisplayName() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getDisplayName(); } @Test - public void testNonMetaArtifactInfoGetArtifactGroupType() { + void testNonMetaArtifactInfoGetArtifactGroupType() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getArtifactGroupType(); } @Test - public void testNonMetaArtifactInfoGetArtifactLabel() { + void testNonMetaArtifactInfoGetArtifactLabel() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getArtifactLabel(); } @Test - public void testNonMetaArtifactInfoGetIsFromCsar() { + void testNonMetaArtifactInfoGetIsFromCsar() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.isFromCsar(); } @Test - public void testNonMetaArtifactInfoGetPayloadData() { + void testNonMetaArtifactInfoGetPayloadData() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getPayloadData(); } @Test - public void testNonMetaArtifactInfoGetArtifaactChecksum() { + void testNonMetaArtifactInfoGetArtifaactChecksum() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getArtifactChecksum(); } @Test - public void testNonMetaArtifactInfoGetArtifactUniqueId() { + void testNonMetaArtifactInfoGetArtifactUniqueId() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.getArtifactUniqueId(); } @Test - public void testNonMetaArtifactInfosetArtifactUniqueId() { + void testNonMetaArtifactInfosetArtifactUniqueId() { NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); testSubject.setArtifactUniqueId("artifactUniqueId"); } @Test - public void testValidateNonMetaArtifactWithExceptionCaught() { + void testValidateNonMetaArtifactWithExceptionCaught() { CsarUtils.validateNonMetaArtifact("", new byte[0], new HashMap<>()); } @Test - public void testCollectComponentCsarDefinitionWhenComponentIsServiceAndGetToscaElementIsLeft() { + void testCollectComponentCsarDefinitionWhenComponentIsServiceAndGetToscaElementIsLeft() { Component component = new Service(); component.setUniqueId("uniqueId"); List resourceInstances = new ArrayList<>(); @@ -815,7 +821,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testCollectComponentTypeArtifactsWhenFetchedComponentHasComponentInstances() { + void testCollectComponentTypeArtifactsWhenFetchedComponentHasComponentInstances() { Component component = new Service(); Component fetchedComponent = new Resource(); component.setUniqueId("uniqueId"); @@ -853,7 +859,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testCollectComponentTypeArtifactsWhenFetchedComponentDontHaveComponentInstances() { + void testCollectComponentTypeArtifactsWhenFetchedComponentDontHaveComponentInstances() { Component component = new Service(); Component fetchedComponent = new Resource(); component.setUniqueId("uniqueId"); @@ -893,7 +899,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testValidateNonMetaArtifactHappyScenario() { + void testValidateNonMetaArtifactHappyScenario() { String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; byte[] payloadData = "some payload data".getBytes(); Map>> collectedWarningMessages = new HashMap<>(); @@ -909,7 +915,7 @@ public class CsarUtilsTest extends BeConfDependentTest { } @Test - public void testValidateNonMetaArtifactScenarioWithWarnnings() { + void testValidateNonMetaArtifactScenarioWithWarnnings() { String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; byte[] payloadData = "some payload data".getBytes(); Map>> collectedWarningMessages = new HashMap<>(); @@ -921,42 +927,35 @@ public class CsarUtilsTest extends BeConfDependentTest { eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); assertTrue(eitherNonMetaArtifact.isLeft()); - assertTrue(collectedWarningMessages.size() == 1); - assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); + assertEquals(1, collectedWarningMessages.size()); + assertEquals(2, collectedWarningMessages.values().iterator().next().size()); } @Test - public void testValidateNonMetaArtifactUnhappyScenario() { + void testValidateNonMetaArtifactUnhappyScenario() { String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; byte[] payloadData = "some payload data".getBytes(); Map>> collectedWarningMessages = new HashMap<>(); Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); assertTrue(eitherNonMetaArtifact.isRight()); - assertTrue(!collectedWarningMessages.isEmpty()); + assertFalse(collectedWarningMessages.isEmpty()); } - @Test(expected = IOException.class) - public void testAddSchemaFilesFromCassandraAddingDuplicatedEntry() throws IOException { + @Test + void testAddSchemaFilesFromCassandraAddingDuplicatedEntry() throws IOException { final String rootPath = System.getProperty("user.dir"); final Path path = Paths.get(rootPath + "/src/test/resources/sdc.zip"); - try { - final byte[] data = Files.readAllBytes(path); - try (final ByteArrayOutputStream out = new ByteArrayOutputStream(); - final ZipOutputStream zip = new ZipOutputStream(out);) { - Deencapsulation.invoke(testSubject, "addSchemaFilesFromCassandra", - zip, data, nodesFromPackage); - zip.putNextEntry(new ZipEntry("Definitions/nodes.yml")); - zip.finish(); - } - } catch (final IOException e) { - Assert.assertTrue("duplicate entry: Definitions/nodes.yml".equals(e.getMessage())); - throw new IOException("Could not add Schema Files From Cassandra", e); + final byte[] data = Files.readAllBytes(path); + try (final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(out)) { + Deencapsulation.invoke(testSubject, "addSchemaFilesFromCassandra", zip, data, nodesFromPackage); + final IOException actualException = assertThrows(IOException.class, () -> zip.putNextEntry(new ZipEntry("Definitions/nodes.yml"))); + assertEquals("duplicate entry: Definitions/nodes.yml", actualException.getMessage()); } } @Test - public void testFindNonRootNodesFromPackage() { + void testFindNonRootNodesFromPackage() { final Resource resource = new Resource(); resource.setDerivedList(nodesFromPackage); final Component component = resource; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java index d9fc8de623..6a3810f102 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java @@ -22,13 +22,11 @@ package org.openecomp.sdc.be.tosca; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyList; @@ -57,13 +55,12 @@ import mockit.Deencapsulation; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Triple; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; @@ -103,7 +100,6 @@ 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.InterfaceLifecycleOperation; import org.openecomp.sdc.be.tosca.exception.ToscaConversionException; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; import org.openecomp.sdc.be.tosca.model.ToscaNodeType; @@ -114,8 +110,9 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; import org.openecomp.sdc.be.tosca.utils.InputConverter; import org.openecomp.sdc.be.tosca.utils.OutputConverter; +import org.openecomp.sdc.common.test.BaseConfDependent; -public class ToscaExportHandlerTest extends BeConfDependentTest { +class ToscaExportHandlerTest extends BaseConfDependent { private static final String COMPONENT_PROPERTY_NAME = "prop1"; private static final String COMPONENT_PROPERTY_TYPE = "string"; @@ -164,9 +161,16 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { @Mock private AttributeConverter attributeConverter; - @Before - public void setUpMock() { - MockitoAnnotations.initMocks(this); + @BeforeAll + public static void setupBeforeClass() { + componentName = "catalog-be"; + confPath = "src/test/resources/config"; + setUp(); + } + + @BeforeEach + void setUpMock() { + MockitoAnnotations.openMocks(this); doReturn(new ToscaProperty()).when(propertyConvertor).convertProperty(any(), any(), eq(PROPERTY)); doReturn(new HashMap()).when(interfacesOperationsConverter) .getInterfacesMap(any(), isNull(), anyMap(), anyMap(), anyBoolean(), anyBoolean()); @@ -232,55 +236,55 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testExportComponent() throws Exception { + void testExportComponent() { Component component = getNewResource(); Either result; when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())) .thenReturn(Either.left(Collections.emptyMap())); // default test when component is Resource result = testSubject.exportComponent(component); - Assert.assertNotNull(result); + assertNotNull(result); component = getNewService(); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Service.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Service.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); // default test when component is Service result = testSubject.exportComponent(component); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testExportComponentInterface() throws Exception { - Component component = getNewResource(); + void testExportComponentInterface() { + Resource component = getNewResource(); Either result; - ((Resource) component).setInterfaces(new HashMap<>()); + component.setInterfaces(new HashMap<>()); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())) .thenReturn(Either.left(Collections.emptyMap())); // default test when convertInterfaceNodeType is right result = testSubject.exportComponentInterface(component, false); - Assert.assertNotNull(result); + assertNotNull(result); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // default test when convertInterfaceNodeType is left result = testSubject.exportComponentInterface(component, false); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertInterfaceNodeTypeProperties() throws Exception { + void testConvertInterfaceNodeTypeProperties() { Resource component = getNewResource(); @@ -300,58 +304,57 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { .thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); // when convertRequirements is called, make it return the same value as 3rd (index=2) argument. - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenAnswer(i -> Either.left(i.getArgument(2))); Either result = (Either) Deencapsulation .invoke(testSubject, "convertInterfaceNodeType", new HashMap(), component, new ToscaTemplate(TOSCA_VERSION), new HashMap(), false); - Assert.assertNotNull(result); - assertThat(result.isLeft(), is(true)); + assertNotNull(result); + assertTrue(result.isLeft()); Map nodeTypeMap = result.left().value().getNode_types(); - assertThat(nodeTypeMap.size(), is(1)); + assertEquals(1,nodeTypeMap.size()); ToscaNodeType toscaNodeType = nodeTypeMap.values().iterator().next(); Map propertyMap = toscaNodeType.getProperties(); // Check if inputs and properties in component are merged properly - assertThat(propertyMap.size(), is(2)); - assertThat(propertyMap.containsKey(COMPONENT_INPUT_NAME), is(true)); - assertThat(propertyMap.containsKey(COMPONENT_PROPERTY_NAME), is(true)); + assertEquals(2, propertyMap.size()); + assertTrue(propertyMap.containsKey(COMPONENT_INPUT_NAME)); + assertTrue(propertyMap.containsKey(COMPONENT_PROPERTY_NAME)); } @Test - public void testCreateToscaRepresentation() throws Exception { + void testCreateToscaRepresentation() { ToscaTemplate toscaTemplate = new ToscaTemplate(""); ToscaRepresentation result; // default test result = testSubject.createToscaRepresentation(toscaTemplate); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testGetDependencies() throws Exception { + void testGetDependencies() { Component component = new Resource(); Either result; // default test result = testSubject.getDependencies(component); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testSetImports() throws Exception { + void testSetImports() { Resource resource = new Resource(); resource.setResourceType(ResourceTypeEnum.PNF); - Component component = resource; - component.setName("TestResourceName"); + resource.setName("TestResourceName"); Map artifactList = new HashMap<>(); ArtifactDefinition artifact = new ArtifactDefinition(); artifact.setArtifactName("name.name2"); artifactList.put("assettoscatemplate", artifact); - component.setArtifacts(artifactList); - component.setToscaArtifacts(artifactList); + resource.setArtifacts(artifactList); + resource.setToscaArtifacts(artifactList); ToscaTemplate toscaTemplate = new ToscaTemplate(""); ComponentInstance ci = new ComponentInstance(); @@ -360,25 +363,25 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { ci.setSourceModelUid("modelName"); List componentInstanceList = new LinkedList<>(); componentInstanceList.add(ci); - component.setComponentInstances(componentInstanceList); + resource.setComponentInstances(componentInstanceList); - when(toscaOperationFacade.getToscaFullElement("name")).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaFullElement("name")).thenReturn(Either.left(resource)); Either>, ToscaError> result; - result = Deencapsulation.invoke(testSubject, "fillImports", component, toscaTemplate); + result = Deencapsulation.invoke(testSubject, "fillImports", resource, toscaTemplate); verify(toscaOperationFacade, times(1)).getToscaFullElement("name"); - Assert.assertTrue(result.isLeft()); + assertTrue(result.isLeft()); ToscaTemplate toscaTemplateRes = result.left().value().left; - Assert.assertEquals(8, toscaTemplateRes.getImports().size()); - Assert.assertNotNull(toscaTemplateRes.getImports().get(6).get("resource-TestResourceName-interface")); - Assert.assertNotNull(toscaTemplateRes.getImports().get(7).get("resource-TestResourceName")); - Assert.assertEquals(1, toscaTemplateRes.getDependencies().size()); - Assert.assertEquals("name.name2", toscaTemplateRes.getDependencies().get(0).getLeft()); + assertEquals(8, toscaTemplateRes.getImports().size()); + assertNotNull(toscaTemplateRes.getImports().get(6).get("resource-TestResourceName-interface")); + assertNotNull(toscaTemplateRes.getImports().get(7).get("resource-TestResourceName")); + assertEquals(1, toscaTemplateRes.getDependencies().size()); + assertEquals("name.name2", toscaTemplateRes.getDependencies().get(0).getLeft()); } @Test - public void testConvertToscaTemplate() throws Exception { + void testConvertToscaTemplate() throws Exception { final Component component = getNewResource(); final ToscaTemplate toscaNode = new ToscaTemplate(""); @@ -393,7 +396,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { component.setComponentInstances(resourceInstances); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.right(false)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.right(false)); final Map map = new HashMap<>(); map.put("mock", new ToscaProperty()); @@ -401,11 +404,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertToscaTemplateWhenComponentContainsGroup() throws ToscaConversionException { + void testConvertToscaTemplateWhenComponentContainsGroup() throws ToscaConversionException { Component component = getNewResource(); ToscaTemplate toscaNode = new ToscaTemplate(""); Either result; @@ -424,16 +427,15 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { String[] array = {"value1", "value2"}; substitutionMappingMap.put("key", array); - when(capabilityRequirementConverter.convertSubstitutionMappingCapabilities(any(Map.class), + when(capabilityRequirementConverter.convertSubstitutionMappingCapabilities(anyMap(), any(Component.class))).thenReturn(Either.left(substitutionMappingMap)); - when(capabilityRequirementConverter.convertSubstitutionMappingRequirements(any(Map.class), - any(Component.class), any(SubstitutionMapping.class))) - .thenReturn(Either.left(new SubstitutionMapping())); + when(capabilityRequirementConverter.convertSubstitutionMappingRequirements(any(Component.class), anyMap())) + .thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(inputConverter.convertInputs(any(List.class), any(Map.class))).thenReturn(new HashMap<>()); + when(inputConverter.convertInputs(anyList(), anyMap())).thenReturn(new HashMap<>()); when(groupExportParser.getGroups(component)).thenReturn(null); @@ -443,11 +445,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test component contains group result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertToscaTemplateWhenComponentIsService() throws Exception { + void testConvertToscaTemplateWhenComponentIsService() throws Exception { Component component = getNewService(); ToscaTemplate toscaNode = new ToscaTemplate(""); Either result; @@ -470,8 +472,8 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { .thenReturn(Either.left(substitutionMappingMap)); when(capabilityRequirementConverter - .convertSubstitutionMappingRequirements(anyMap(), any(Component.class), any(SubstitutionMapping.class))) - .thenReturn(Either.left(new SubstitutionMapping())); + .convertSubstitutionMappingRequirements(any(Component.class), anyMap())) + .thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); @@ -482,11 +484,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test component contains group result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertMetadata_1() throws Exception { + void testConvertMetadata_1() { Component component = getNewResource(); boolean isInstance = true; @@ -496,11 +498,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test Map result = Deencapsulation.invoke(testSubject, "convertMetadata", component, isInstance, componentInstance); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testFillImports() throws Exception { + void testFillImports() { Component component = getNewService(); ToscaTemplate toscaTemplate = new ToscaTemplate(""); @@ -533,11 +535,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "fillImports", component, toscaTemplate); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testCreateDependency() throws Exception { + void testCreateDependency() { Map componentCache = new HashMap<>(); List>> imports = new ArrayList<>(); @@ -560,21 +562,21 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test Deencapsulation.invoke(testSubject, "createDependency", componentCache, imports, dependecies, ci); - Assert.assertFalse(componentCache.isEmpty()); + assertFalse(componentCache.isEmpty()); } @Test - public void testGetInterfaceFilename() throws Exception { + void testGetInterfaceFilename() { String artifactName = "artifact.name"; String result; // default test result = ToscaExportHandler.getInterfaceFilename(artifactName); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertNodeType() throws Exception { + void testConvertNodeType() { Component component = new Resource(); ToscaTemplate toscaNode = new ToscaTemplate(""); Map nodeTypes = new HashMap<>(); @@ -586,11 +588,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation .invoke(testSubject, "convertNodeType", new HashMap<>(), component, toscaNode, nodeTypes); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertInterfaceNodeType() throws Exception { + void testConvertInterfaceNodeType() { Component component = getNewResource(); ToscaTemplate toscaNode = new ToscaTemplate(""); Map nodeTypes = new HashMap<>(); @@ -603,52 +605,52 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())) .thenReturn(Either.left(Collections.emptyMap())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // default test result = Deencapsulation.invoke(testSubject, "convertInterfaceNodeType", new HashMap<>(), component, toscaNode , nodeTypes, false); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertReqCapAndTypeName() throws Exception { + void testConvertReqCapAndTypeName() { Component component = new Resource(); ToscaTemplate toscaNode = new ToscaTemplate(""); - Map nodeTypes = new HashMap(); + Map nodeTypes = new HashMap<>(); ToscaNodeType toscaNodeType = new ToscaNodeType(); Map dataTypes = new HashMap<>(); Either result; when( capabilityRequirementConverter - .convertCapabilities(any(Map.class), any(Resource.class), any(Map.class))) + .convertCapabilities(anyMap(), any(Resource.class), anyMap())) .thenReturn(new HashMap<>()); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // default test result = Deencapsulation .invoke(testSubject, "convertReqCapAndTypeName", new HashMap<>(), component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - Assert.assertNotNull(result); + assertNotNull(result); component = new Service(); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Service.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Service.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // test when component is service result = Deencapsulation .invoke(testSubject, "convertReqCapAndTypeName", new HashMap<>(), component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertNodeTemplatesWhenComponentIsService() throws Exception { + void testConvertNodeTemplatesWhenComponentIsService() { final Component component = getNewService(); final List componentInstances = new ArrayList<>(); final Map> componentInstancesProperties = new HashMap<>(); @@ -725,13 +727,13 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { componentInstancesProperties.put("id", list); component.setComponentInstancesProperties(componentInstancesProperties); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.left(component)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.left(component)); when(capabilityRequirementConverter - .convertComponentInstanceCapabilities(any(ComponentInstance.class), any(Map.class), any(ToscaNodeTemplate.class))) + .convertComponentInstanceCapabilities(any(ComponentInstance.class), anyMap(), any(ToscaNodeTemplate.class))) .thenReturn(Either.left(new ToscaNodeTemplate())); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), any(ToscaNodeType.class))) + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))) .thenReturn(Either.left(new ToscaNodeType())); when(toscaOperationFacade.getToscaFullElement("uid")).thenReturn(Either.left(component)); when(toscaOperationFacade.getToscaFullElement("sourceModelUid")).thenReturn(Either.left(component)); @@ -745,8 +747,8 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { .thenReturn(Either.left(substitutionMappingMap)); when(capabilityRequirementConverter - .convertSubstitutionMappingRequirements(any(Map.class), any(Component.class), any(SubstitutionMapping.class))) - .thenReturn(Either.left(new SubstitutionMapping())); + .convertSubstitutionMappingRequirements(any(Component.class), anyMap())) + .thenReturn(Either.left(Collections.emptyMap())); // default test final Either toscaRepresentationToscaErrorEither = testSubject.exportComponent(component); @@ -755,7 +757,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testConvertNodeTemplatesWhenComponentIsResource() throws Exception { + void testConvertNodeTemplatesWhenComponentIsResource() { final Resource component = getNewResource(); component.setResourceType(VF); final List componentInstances = new ArrayList<>(); @@ -849,13 +851,13 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { componentInstancesInputs.put("id", componentInstanceInputs); component.setComponentInstancesInputs(componentInstancesInputs); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.left(component)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.left(component)); when(capabilityRequirementConverter - .convertComponentInstanceCapabilities(any(ComponentInstance.class), any(Map.class), any(ToscaNodeTemplate.class))) + .convertComponentInstanceCapabilities(any(ComponentInstance.class), anyMap(), any(ToscaNodeTemplate.class))) .thenReturn(Either.left(new ToscaNodeTemplate())); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), any(ToscaNodeType.class))) + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))) .thenReturn(Either.left(new ToscaNodeType())); when(toscaOperationFacade.getToscaFullElement("uid")).thenReturn(Either.left(component)); when(toscaOperationFacade.getToscaFullElement("sourceModelUid")).thenReturn(Either.left(component)); @@ -869,8 +871,8 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { .thenReturn(Either.left(substitutionMappingMap)); when(capabilityRequirementConverter - .convertSubstitutionMappingRequirements(any(Map.class), any(Component.class), any(SubstitutionMapping.class))) - .thenReturn(Either.left(new SubstitutionMapping())); + .convertSubstitutionMappingRequirements(any(Component.class), anyMap())) + .thenReturn(Either.left(Collections.emptyMap())); // default test final Either toscaRepresentationToscaErrorEither = testSubject.exportComponent(component); @@ -879,7 +881,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testConvertNodeTemplatesWhenConvertComponentInstanceCapabilitiesIsRight() throws Exception { + void testConvertNodeTemplatesWhenConvertComponentInstanceCapabilitiesIsRight() { Component component = getNewResource(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); @@ -912,13 +914,13 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { componentCache.put("uid", component); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.left(component)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.left(component)); when(capabilityRequirementConverter - .convertComponentInstanceCapabilities(any(ComponentInstance.class), any(Map.class), any(ToscaNodeTemplate.class))) + .convertComponentInstanceCapabilities(any(ComponentInstance.class), anyMap(), any(ToscaNodeTemplate.class))) .thenReturn(Either.right(ToscaError.GENERAL_ERROR)); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // default test @@ -927,7 +929,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testConvetNodeTemplateWhenGetOriginComponentIsRight() throws Exception { + void testConvetNodeTemplateWhenGetOriginComponentIsRight() { Component component = getNewResource(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); @@ -966,10 +968,10 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { componentCache.put("uid", component); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.right(false)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.right(false)); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); // default test @@ -978,7 +980,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testConvertNodeTemplatesWhenConvertComponentInstanceRequirmentsIsRight() { + void testConvertNodeTemplatesWhenConvertComponentInstanceRequirmentsIsRight() { Resource component = getNewResource(); component.setResourceType(VF); List componentInstances = new ArrayList<>(); @@ -1021,10 +1023,10 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { component.setComponentInstances(componentInstances); doReturn(Either.left(component)).when(toscaOperationFacade).getToscaFullElement("id"); - when(capabilityRequirementConverter.getOriginComponent(any(Map.class), any(ComponentInstance.class))).thenReturn(Either.left(component)); + when(capabilityRequirementConverter.getOriginComponent(anyMap(), any(ComponentInstance.class))).thenReturn(Either.left(component)); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Resource.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Resource.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class))) .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); @@ -1035,7 +1037,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testCreateNodeType() throws Exception { + void testCreateNodeType() { Component component = new Resource(); List array = new ArrayList<>(); @@ -1045,16 +1047,16 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test when component is resource result = Deencapsulation.invoke(testSubject, "createNodeType", component); - Assert.assertNotNull(result); + assertNotNull(result); component = new Service(); // test when component is service result = Deencapsulation.invoke(testSubject, "createNodeType", component); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testCreateProxyInterfaceTypesComponentNotFound() throws Exception { + void testCreateProxyInterfaceTypesComponentNotFound() { Component container = new Service(); Either, ToscaError> result; List componentInstances = new ArrayList<>(); @@ -1069,11 +1071,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { any(ComponentParametersView.class))) .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); result = Deencapsulation.invoke(testSubject, "createProxyInterfaceTypes", container); - Assert.assertTrue(result.isRight()); + assertTrue(result.isRight()); } @Test - public void testCreateProxyInterfaceTypesWhenInterfaceLifecycleFetchFailed() { + void testCreateProxyInterfaceTypesWhenInterfaceLifecycleFetchFailed() { Component container = new Service(); Either, ToscaError> result; List componentInstances = new ArrayList<>(); @@ -1090,11 +1092,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())) .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); result = Deencapsulation.invoke(testSubject, "createProxyInterfaceTypes", container); - Assert.assertTrue(result.isRight()); + assertTrue(result.isRight()); } @Test - public void testCreateProxyInterfaceTypesPositive() { + void testCreateProxyInterfaceTypesPositive() { Component container = new Service(); Either, ToscaError> result; List componentInstances = new ArrayList<>(); @@ -1117,13 +1119,13 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { .thenReturn(Either.left(proxyResource)); result = Deencapsulation.invoke(testSubject, "createProxyInterfaceTypes", container); - Assert.assertNotNull(result); - Assert.assertTrue(result.isLeft()); - Assert.assertEquals(1, result.left().value().size()); + assertNotNull(result); + assertTrue(result.isLeft()); + assertEquals(1, result.left().value().size()); } @Test - public void testCreateProxyNodeTypes() throws Exception { + void testCreateProxyNodeTypes() { Map componentCache = new HashMap<>(); Component container = new Resource(); Either, ToscaError> result; @@ -1140,11 +1142,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test when getLatestByName return is right result = Deencapsulation.invoke(testSubject, "createProxyNodeTypes", componentCache, container); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testCreateServiceSubstitutionNodeTypes() throws Exception { + void testCreateServiceSubstitutionNodeTypes() { Map componentCache = new HashMap<>(); Component referencedService = getNewService(); @@ -1166,17 +1168,17 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(any())) .thenReturn(Either.left(Collections.emptyMap())); when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(new HashMap<>())); - when(capabilityRequirementConverter.convertRequirements(any(Map.class), any(Service.class), + when(capabilityRequirementConverter.convertRequirements(anyMap(), any(Service.class), any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); ToscaTemplate toscaNode = new ToscaTemplate("1_1"); Deencapsulation.invoke(testSubject, "createServiceSubstitutionNodeTypes", componentCache, containerService, toscaNode); - Assert.assertNotNull(toscaNode.getNode_types()); + assertNotNull(toscaNode.getNode_types()); } @Test - public void testCreateProxyNodeTypesWhenGetLatestByNameReturnValue() { + void testCreateProxyNodeTypesWhenGetLatestByNameReturnValue() { Map componentCache = new HashMap<>(); Component container = new Resource(); Either, ToscaError> result; @@ -1202,11 +1204,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test when getLatestByName is left result = Deencapsulation.invoke(testSubject, "createProxyNodeTypes", componentCache, container); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testCreateProxyNodeType() throws Exception { + void testCreateProxyNodeType() { Map componentCache = new HashMap<>(); Component origComponent = new Resource(); Component proxyComponent = new Resource(); @@ -1218,11 +1220,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "createProxyNodeType", componentCache, origComponent, proxyComponent, instance); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertComponentInstanceRequirements() throws Exception { + void testConvertComponentInstanceRequirements() { Component component = new Resource(); ComponentInstance componentInstance = new ComponentInstance(); List relations = new ArrayList<>(); @@ -1234,7 +1236,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertComponentInstanceRequirements", component, componentInstance, relations, nodeTypeTemplate, originComponent, componentCache); - Assert.assertNotNull(result); + assertNotNull(result); RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); reldef.setFromNode("name"); @@ -1254,11 +1256,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test when filteredRElations ins't empty result = Deencapsulation.invoke(testSubject, "convertComponentInstanceRequirements", component, componentInstance, relations, nodeTypeTemplate, originComponent, componentCache); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void buildRequirementFailure() { + void buildRequirementFailure() { final Component fromOriginComponent = new Resource(); final ComponentInstance fromInstance = new ComponentInstance(); final String fromInstanceUid = "fromInstanceUid"; @@ -1357,7 +1359,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testBuildRequirement() { + void testBuildRequirement() { final ComponentInstance fromInstance = new ComponentInstance(); fromInstance.setUniqueId("name"); fromInstance.setComponentUid("string"); @@ -1438,7 +1440,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testAddRequirmentsWithBuildAndAddRequirements() { + void testAddRequirmentsWithBuildAndAddRequirements() { ComponentInstance fromInstance = new ComponentInstance(); Component fromOriginComponent = new Resource(); List instancesList = new ArrayList<>(); @@ -1501,7 +1503,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testBuildAndAddRequirement() { + void testBuildAndAddRequirement() { Component fromOriginComponent = new Resource(); Component toOriginComponent = new Resource(); CapabilityDefinition capability = new CapabilityDefinition(); @@ -1541,7 +1543,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testBuildRequirementBuildSubstitutedNameReturnsValueTwice() { + void testBuildRequirementBuildSubstitutedNameReturnsValueTwice() { final Component fromOriginComponent = new Resource(); final Component toOriginComponent = new Resource(); final CapabilityDefinition capability = new CapabilityDefinition(); @@ -1574,7 +1576,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { } @Test - public void testIsRequirementBelongToRelation() throws Exception { + void testIsRequirementBelongToRelation() { Component originComponent = new Resource(); RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); @@ -1588,11 +1590,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // test return false result = Deencapsulation.invoke(testSubject, "isRequirementBelongToRelation", originComponent, reqAndRelationshipPair, requirement, fromInstanceId); - Assert.assertFalse(result); + assertFalse(result); } @Test - public void testIsRequirementBelongToRelationWithNonAtomicComponent() { + void testIsRequirementBelongToRelationWithNonAtomicComponent() { Component originComponent = new Service(); RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); @@ -1603,11 +1605,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test return true result = Deencapsulation.invoke(testSubject, "isRequirementBelongToRelation", originComponent, reqAndRelationshipPair, requirement, fromInstanceId); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testIsRequirementBelongToOwner() throws Exception { + void testIsRequirementBelongToOwner() { RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); RequirementDefinition requirement = new RequirementDefinition(); @@ -1621,37 +1623,37 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "isRequirementBelongToOwner", reqAndRelationshipPair, requirement, fromInstanceId, originComponent); - Assert.assertFalse(result); + assertFalse(result); } @Test - public void testIsCvfc() throws Exception { + void testIsCvfc() { Component component = new Service(); boolean result; result = Deencapsulation.invoke(testSubject, "isCvfc", component); - Assert.assertFalse(result); + assertFalse(result); } @Test - public void testConvertCapabilities() throws Exception { - Component component = new Resource(); - SubstitutionMapping substitutionMappings = new SubstitutionMapping(); - Map componentCache = new HashMap<>(); - Either result; + void testConvertCapabilities() { + final Component component = new Resource(); + final Map componentCache = new HashMap<>(); + final Either, ToscaError> expectedResult = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); when(capabilityRequirementConverter.convertSubstitutionMappingCapabilities(componentCache, component)) - .thenReturn(Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR)); + .thenReturn(expectedResult); // default test return isRight - result = Deencapsulation.invoke(testSubject, "convertCapabilities", component, substitutionMappings, - componentCache); - Assert.assertNotNull(result); + final Either, ToscaError> actualResult = + Deencapsulation.invoke(testSubject, "convertSubstitutionMappingCapabilities", component, componentCache); + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); } @Test - public void testConvertCapabilities_1() throws Exception { + void testConvertCapabilities_1() { Component component = new Resource(); ToscaNodeType nodeType = new ToscaNodeType(); Map dataTypes = new HashMap<>(); @@ -1663,11 +1665,11 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation .invoke(testSubject, "convertCapabilities", new HashMap<>(), component, nodeType, dataTypes); - Assert.assertNotNull(result); + assertNotNull(result); } @Test - public void testConvertToNodeTemplateArtifacts() throws Exception { + void testConvertToNodeTemplateArtifacts() { Map container = new HashMap<>(); ToscaArtifactDataDefinition art = new ToscaArtifactDataDefinition(); art.setFile("test_file"); @@ -1675,78 +1677,78 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Map result; container.put("test_art", art); result = Deencapsulation.invoke(testSubject, "convertToNodeTemplateArtifacts", container); - Assert.assertNotNull(result); - Assert.assertTrue(MapUtils.isNotEmpty(result)); - Assert.assertEquals("test_file", result.get("test_art").getFile()); - Assert.assertEquals("test_type", result.get("test_art").getType()); + assertNotNull(result); + assertTrue(MapUtils.isNotEmpty(result)); + assertEquals("test_file", result.get("test_art").getFile()); + assertEquals("test_type", result.get("test_art").getType()); } @Test - public void testGetProxyNodeTypeInterfacesNoInterfaces() { + void testGetProxyNodeTypeInterfacesNoInterfaces() { Component service = new Service(); Optional> proxyNodeTypeInterfaces = testSubject.getProxyNodeTypeInterfaces(service, DATA_TYPES); - Assert.assertFalse(proxyNodeTypeInterfaces.isPresent()); + assertFalse(proxyNodeTypeInterfaces.isPresent()); } @Test - public void testGetProxyNodeTypeInterfaces() { + void testGetProxyNodeTypeInterfaces() { Component service = getTestComponent(); Optional> proxyNodeTypeInterfaces = testSubject.getProxyNodeTypeInterfaces(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypeInterfaces.isPresent()); + assertTrue(proxyNodeTypeInterfaces.isPresent()); Map componentInterfaces = proxyNodeTypeInterfaces.get(); - Assert.assertNotNull(componentInterfaces); + assertNotNull(componentInterfaces); } @Test - public void testGetProxyNodeTypePropertiesComponentNull() { + void testGetProxyNodeTypePropertiesComponentNull() { Optional> proxyNodeTypeProperties = testSubject.getProxyNodeTypeProperties(null, DATA_TYPES); - Assert.assertFalse(proxyNodeTypeProperties.isPresent()); + assertFalse(proxyNodeTypeProperties.isPresent()); } @Test - public void testGetProxyNodeTypePropertiesNoProperties() { + void testGetProxyNodeTypePropertiesNoProperties() { Component service = new Service(); Optional> proxyNodeTypeProperties = testSubject.getProxyNodeTypeProperties(service, DATA_TYPES); - Assert.assertFalse(proxyNodeTypeProperties.isPresent()); + assertFalse(proxyNodeTypeProperties.isPresent()); } @Test - public void testGetProxyNodeTypeProperties() { + void testGetProxyNodeTypeProperties() { Component service = getTestComponent(); service.setProperties(Arrays.asList(createMockProperty("componentPropStr", "Default String Prop"), createMockProperty("componentPropInt", null))); Optional> proxyNodeTypeProperties = testSubject.getProxyNodeTypeProperties(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypeProperties.isPresent()); + assertTrue(proxyNodeTypeProperties.isPresent()); Map componentProperties = proxyNodeTypeProperties.get(); - Assert.assertNotNull(componentProperties); - Assert.assertEquals(2, componentProperties.size()); + assertNotNull(componentProperties); + assertEquals(2, componentProperties.size()); } @Test - public void testAddInputsToPropertiesNoInputs() { + void testAddInputsToPropertiesNoInputs() { Component service = getTestComponent(); service.setProperties(Arrays.asList(createMockProperty("componentPropStr", "Default String Prop"), createMockProperty("componentPropInt", null))); Optional> proxyNodeTypePropertiesResult = testSubject.getProxyNodeTypeProperties(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypePropertiesResult.isPresent()); + assertTrue(proxyNodeTypePropertiesResult.isPresent()); Map proxyNodeTypeProperties = proxyNodeTypePropertiesResult.get(); testSubject.addInputsToProperties(DATA_TYPES, null, proxyNodeTypeProperties); - Assert.assertNotNull(proxyNodeTypeProperties); - Assert.assertEquals(2, proxyNodeTypeProperties.size()); + assertNotNull(proxyNodeTypeProperties); + assertEquals(2, proxyNodeTypeProperties.size()); testSubject.addInputsToProperties(DATA_TYPES, new ArrayList<>(), proxyNodeTypeProperties); - Assert.assertEquals(2, proxyNodeTypeProperties.size()); + assertEquals(2, proxyNodeTypeProperties.size()); } @Test - public void testAddInputsToPropertiesWithInputs() { + void testAddInputsToPropertiesWithInputs() { Component service = getTestComponent(); service.setProperties(Arrays.asList(createMockProperty("componentPropStr", "Default String Prop"), createMockProperty("componentPropInt", null))); @@ -1755,30 +1757,30 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Optional> proxyNodeTypePropertiesResult = testSubject.getProxyNodeTypeProperties(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypePropertiesResult.isPresent()); + assertTrue(proxyNodeTypePropertiesResult.isPresent()); Map proxyNodeTypeProperties = proxyNodeTypePropertiesResult.get(); testSubject.addInputsToProperties(DATA_TYPES, service.getInputs(), proxyNodeTypeProperties); - Assert.assertNotNull(proxyNodeTypeProperties); - Assert.assertEquals(4, proxyNodeTypeProperties.size()); + assertNotNull(proxyNodeTypeProperties); + assertEquals(4, proxyNodeTypeProperties.size()); } @Test - public void testAddInputsToPropertiesOnlyInputs() { + void testAddInputsToPropertiesOnlyInputs() { Component service = getTestComponent(); service.setInputs(Arrays.asList(createMockInput("componentInputStr1", "Default String Input1"), createMockInput("componentInputStr2", "Default String Input2"))); Optional> proxyNodeTypePropertiesResult = testSubject.getProxyNodeTypeProperties(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypePropertiesResult.isPresent()); + assertTrue(proxyNodeTypePropertiesResult.isPresent()); Map proxyNodeTypeProperties = proxyNodeTypePropertiesResult.get(); testSubject.addInputsToProperties(DATA_TYPES, service.getInputs(), proxyNodeTypeProperties); - Assert.assertNotNull(proxyNodeTypeProperties); - Assert.assertEquals(2, proxyNodeTypeProperties.size()); + assertNotNull(proxyNodeTypeProperties); + assertEquals(2, proxyNodeTypeProperties.size()); } @Test - public void testOperationImplementationInProxyNodeTypeNotPresent() { + void testOperationImplementationInProxyNodeTypeNotPresent() { Component service = getTestComponent(); InterfaceDefinition interfaceDefinition = service.getInterfaces().get("normalizedServiceComponentName-interface"); @@ -1795,9 +1797,9 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { "Default String Input1"), createMockInput("componentInputStr2", "Default String Input2"))); Optional> proxyNodeTypeInterfaces = testSubject.getProxyNodeTypeInterfaces(service, DATA_TYPES); - Assert.assertTrue(proxyNodeTypeInterfaces.isPresent()); + assertTrue(proxyNodeTypeInterfaces.isPresent()); Map componentInterfaces = proxyNodeTypeInterfaces.get(); - Assert.assertNotNull(componentInterfaces); + assertNotNull(componentInterfaces); } private Component getTestComponent() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/BaseType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/BaseType.java index 5c88101b2f..584edad022 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/BaseType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/BaseType.java @@ -33,7 +33,7 @@ public class BaseType { @Setter private String toscaResourceName; - private List versions = new ArrayList<>(); + private final List versions = new ArrayList<>(); public BaseType(final String toscaResourceName) { this.toscaResourceName = toscaResourceName; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java index e0ca719005..1c0cfc4c5d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java @@ -638,6 +638,11 @@ public abstract class Component implements PropertiesOwner { } public void setDerivedFromGenericInfo(Resource genericType) { + if (genericType == null) { + derivedFromGenericType = null; + derivedFromGenericVersion = null; + return; + } derivedFromGenericType = genericType.getToscaResourceName(); derivedFromGenericVersion = genericType.getVersion(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java index a06f737c83..bc8efb528d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java @@ -19,16 +19,15 @@ */ package org.openecomp.sdc.be.model; -import static java.util.Optional.ofNullable; - import java.util.HashMap; -import java.util.List; import java.util.Map; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.CategoryBaseTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; @@ -143,7 +142,7 @@ public class Service extends Component { } private ServiceMetadataDataDefinition getServiceMetadataDefinition() { - return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); + return getMetadataDefinition(); } public String getServiceFunction() { @@ -167,9 +166,18 @@ public class Service extends Component { } private String fetchToscaNameFromConfigBasedOnService(final String serviceCategory) { - final Map> serviceNodeTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceNodeTypes(); - final List stringList = ofNullable(serviceNodeTypes).map(serviceNames -> serviceNames.get(serviceCategory)).orElse(null); - return stringList != null ? stringList.get(0) : null; + final Map serviceNodeTypesConfig = + ConfigurationManager.getConfigurationManager().getConfiguration().getServiceBaseNodeTypes(); + if (serviceNodeTypesConfig == null) { + return null; + } + + final CategoryBaseTypeConfig categoryBaseTypeConfig = serviceNodeTypesConfig.get(serviceCategory); + if (categoryBaseTypeConfig == null || CollectionUtils.isEmpty(categoryBaseTypeConfig.getBaseTypes())) { + return null; + } + + return categoryBaseTypeConfig.getBaseTypes().get(0); } @Override @@ -182,14 +190,22 @@ public class Service extends Component { } public void setAbstract(Boolean isAbstract) { - ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setIsAbstract(isAbstract); + getMetadataDefinition().setIsAbstract(isAbstract); } public void setVendorName(String vendorName) { - ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorName(vendorName); + getMetadataDefinition().setVendorName(vendorName); } public void setVendorRelease(String vendorRelease) { - ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorRelease(vendorRelease); + getMetadataDefinition().setVendorRelease(vendorRelease); + } + + public boolean isSubstituteCandidate() { + return getDerivedFromGenericType() != null; + } + + private ServiceMetadataDataDefinition getMetadataDefinition() { + return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java index 7457ed727e..ebc563268e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java @@ -86,7 +86,15 @@ public interface IElementOperation { Either, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction); - List getBaseTypes(String categoryName, String modelName); + List getServiceBaseTypes(String categoryName, String modelName); + + /** + * Checks if a category requires a base type. + * + * @param categoryName the category name + * @return {@code true} if a base type is required, {@code false} otherwise. + */ + boolean isBaseTypeRequired(String categoryName); Either getCategory(NodeTypeEnum nodeType, String categoryId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java index b98f8d9dea..127d778f73 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java @@ -21,19 +21,24 @@ package org.openecomp.sdc.be.model.operations.impl; import fj.data.Either; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphVertex; import org.openecomp.sdc.be.config.ArtifactConfigManager; import org.openecomp.sdc.be.config.ArtifactConfiguration; +import org.openecomp.sdc.be.config.CategoryBaseTypeConfig; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -382,13 +387,18 @@ public class ElementOperation implements IElementOperation { } @Override - public List getBaseTypes(final String categoryName, final String modelName) { - final ArrayList baseTypes = new ArrayList<>(); - final Map> categoriesSpecificBaseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceNodeTypes(); - final List categorySpecificBaseType = categoriesSpecificBaseTypes == null ? null : categoriesSpecificBaseTypes.get(categoryName); - final String generalBaseType = ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get("Service"); - final List baseToscaResourceNames = categorySpecificBaseType == null ? List.of(generalBaseType) : categorySpecificBaseType; + public List getServiceBaseTypes(final String categoryName, final String modelName) { + + final CategoryBaseTypeConfig categoryBaseTypeConfig = getCategoryBaseTypeConfig(categoryName).orElse(null); + final List baseToscaResourceNames; + if (categoryBaseTypeConfig == null) { + final String generalBaseType = getConfiguration().getGenericAssetNodeTypes().get("Service"); + baseToscaResourceNames = List.of(generalBaseType); + } else { + baseToscaResourceNames = getCategoryBaseTypes(categoryName); + } + final ArrayList baseTypes = new ArrayList<>(); baseToscaResourceNames.forEach(baseToscaResourceName -> { final Map props = new EnumMap<>(GraphPropertyEnum.class); props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, baseToscaResourceName); @@ -413,6 +423,48 @@ public class ElementOperation implements IElementOperation { return baseTypes; } + private Configuration getConfiguration() { + return ConfigurationManager.getConfigurationManager().getConfiguration(); + } + + @Override + public boolean isBaseTypeRequired(final String categoryName) { + final Map categoriesSpecificBaseTypeMap = getConfiguration().getServiceBaseNodeTypes(); + if (MapUtils.isEmpty(categoriesSpecificBaseTypeMap)) { + return true; + } + + final CategoryBaseTypeConfig categoryBaseTypeConfig = categoriesSpecificBaseTypeMap.get(categoryName); + if (categoryBaseTypeConfig == null) { + return true; + } + + return categoryBaseTypeConfig.isRequired(); + } + + private List getCategoryBaseTypes(final String categoryName) { + final Optional categoryBaseTypeConfigOptional = getCategoryBaseTypeConfig(categoryName); + if (categoryBaseTypeConfigOptional.isEmpty()) { + return Collections.emptyList(); + } + + final CategoryBaseTypeConfig categoryBaseTypeConfig = categoryBaseTypeConfigOptional.get(); + if (CollectionUtils.isEmpty(categoryBaseTypeConfig.getBaseTypes())) { + return Collections.emptyList(); + } + + return categoryBaseTypeConfig.getBaseTypes(); + } + + private Optional getCategoryBaseTypeConfig(final String categoryName) { + final Map categoriesSpecificBaseTypes = getConfiguration().getServiceBaseNodeTypes(); + if (categoriesSpecificBaseTypes == null) { + return Optional.empty(); + } + + return Optional.ofNullable(categoriesSpecificBaseTypes.get(categoryName)); + } + private Map> addTypesDerivedFromVertex(final Map> types, final GraphVertex vertex) { final Either, JanusGraphOperationStatus> derivedFromVertex = janusGraphDao.getParentVertices(vertex, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseAll); @@ -900,7 +952,7 @@ public class ElementOperation implements IElementOperation { @Override public Either getDefaultHeatTimeout() { - return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()); + return Either.left(getConfiguration().getHeatArtifactDeploymentTimeout()); } @Override diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java index 3cd14d8b27..1811dff764 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java @@ -54,7 +54,8 @@ public class ModelTestBase { appConfigDir); configurationManager = new ConfigurationManager(configurationSource); - Configuration configuration = new Configuration(); + Configuration configuration = configurationManager.getConfiguration(); + configuration.setCassandraConfig(null); configuration.setJanusGraphInMemoryGraph(true); environmentContext.setDefaultValue("General_Revenue-Bearing"); @@ -64,11 +65,10 @@ public class ModelTestBase { configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout); Map deploymentRIArtifacts = new HashMap<>(); ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); - Object artifactDataObj = new HashMap(); - ((HashMap) artifactDataObj).put("1", artifactInfo); + HashMap artifactDataObj = new HashMap<>(); + artifactDataObj.put("1", artifactInfo); deploymentRIArtifacts.put("VfHeatEnv", artifactDataObj); - configurationManager.setConfiguration(configuration); configurationManager.getConfiguration().setDeploymentResourceInstanceArtifacts(deploymentRIArtifacts); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java index 447b053fea..b48acd0940 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java @@ -26,10 +26,8 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import org.junit.Assert; import org.junit.Test; import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; @@ -212,7 +210,7 @@ public class ResourceTest extends ModelConfDependentTest { Configuration existingConfiguration = configurationManager.getConfiguration(); Configuration newConfiguration = new Configuration(); - newConfiguration.setServiceNodeTypes(null); + newConfiguration.setServiceBaseNodeTypes(null); Map genericAssetNodeTypes = new HashMap<>(); genericAssetNodeTypes.put("VFC", "org.openecomp.resource.abstract.nodes.VFC"); newConfiguration.setGenericAssetNodeTypes(genericAssetNodeTypes); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java index d84d97b547..ebbb3f4f5e 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java @@ -271,10 +271,10 @@ public class ServiceTest { } @Test - public void testFetchGenericTypeToscaNameFromConfigNoToscaTypesForCategories() throws Exception { + public void testFetchGenericTypeToscaNameFromConfigNoToscaTypesForCategories() { Configuration existingConfiguration = configurationManager.getConfiguration(); Configuration newConfiguration = new Configuration(); - newConfiguration.setServiceNodeTypes(null); + newConfiguration.setServiceBaseNodeTypes(null); Map genericAssetNodeTypes = new HashMap<>(); genericAssetNodeTypes.put("Service", "org.openecomp.resource.abstract.nodes.service"); newConfiguration.setGenericAssetNodeTypes(genericAssetNodeTypes); @@ -290,7 +290,7 @@ public class ServiceTest { } @Test - public void testFetchGenericTypeToscaNameFromConfigNoToscaTypeForRelevantCategory() throws Exception { + public void testFetchGenericTypeToscaNameFromConfigNoToscaTypeForRelevantCategory() { Service testSubject = createTestSubject(); CategoryDefinition category = new CategoryDefinition(); category.setName("CategoryD"); @@ -300,17 +300,17 @@ public class ServiceTest { } @Test - public void testFetchGenericTypeToscaNameFromConfigToscaTypeDefinedForCategory() throws Exception { + public void testFetchGenericTypeToscaNameFromConfigToscaTypeDefinedForCategory() { Service testSubject = createTestSubject(); CategoryDefinition category = new CategoryDefinition(); - category.setName("CategoryB"); + category.setName("CategoryA"); testSubject.addCategory(category); String result = testSubject.fetchGenericTypeToscaNameFromConfig(); - assertEquals("org.openecomp.resource.abstract.nodes.B", result); + assertEquals("org.openecomp.resource.abstract.nodes.A", result); Configuration configuration = new Configuration(); - configuration.setServiceNodeTypes(null); + configuration.setServiceBaseNodeTypes(null); configurationManager.setConfiguration(configuration); } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java index cf3b6dad8b..ed9313e697 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java @@ -20,9 +20,10 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isNull; @@ -43,6 +44,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.config.ArtifactConfiguration; +import org.openecomp.sdc.be.config.CategoryBaseTypeConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphDao; @@ -77,9 +79,11 @@ public class ElementOperationTest extends ModelTestBase { @Mock private JanusGraphGenericDao janusGraphDao; + @Mock + private HealingJanusGraphDao healingJanusGraphDao; - private static String CATEGORY = "category"; - private static String SUBCATEGORY = "subcategory"; + private static final String CATEGORY = "category"; + private static final String SUBCATEGORY = "subcategory"; @BeforeAll public static void setupBeforeClass() { @@ -448,13 +452,15 @@ public class ElementOperationTest extends ModelTestBase { @Test public void testBaseTypes_serviceSpecific() { - Map> preExistingServiceNodeTypes = configurationManager.getConfiguration().getServiceNodeTypes(); + Map preExistingServiceNodeTypes = configurationManager.getConfiguration().getServiceBaseNodeTypes(); Map preExistingGenericNodeTypes = configurationManager.getConfiguration().getGenericAssetNodeTypes(); try { - Map> serviceNodeTypes = new HashMap<>(); - serviceNodeTypes.put("serviceCategoryA", List.of("org.base.type")); - configurationManager.getConfiguration().setServiceNodeTypes(serviceNodeTypes); + final Map serviceBaseNodeTypeConfigMap = new HashMap<>(); + final var categoryBaseTypeConfig = new CategoryBaseTypeConfig(); + categoryBaseTypeConfig.setBaseTypes(List.of("org.base.type")); + serviceBaseNodeTypeConfigMap.put("serviceCategoryA", categoryBaseTypeConfig); + configurationManager.getConfiguration().setServiceBaseNodeTypes(serviceBaseNodeTypeConfigMap); Map genericNodeTypes = new HashMap<>(); genericNodeTypes.put("service", "org.service.default"); @@ -483,7 +489,7 @@ public class ElementOperationTest extends ModelTestBase { JsonParseFlagEnum.ParseAll)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); when(derivedTypeVertex.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)).thenReturn("org.parent.type"); - List baseTypes = elementOperation.getBaseTypes("serviceCategoryA", null); + List baseTypes = elementOperation.getServiceBaseTypes("serviceCategoryA", null); assertEquals(2, baseTypes.size()); assertEquals("org.base.type", baseTypes.get(0).getToscaResourceName()); @@ -491,14 +497,14 @@ public class ElementOperationTest extends ModelTestBase { assertEquals("1.0", baseTypes.get(0).getVersions().get(0)); assertEquals("org.parent.type", baseTypes.get(1).getToscaResourceName()); } finally { - configurationManager.getConfiguration().setServiceNodeTypes(preExistingServiceNodeTypes); + configurationManager.getConfiguration().setServiceBaseNodeTypes(preExistingServiceNodeTypes); configurationManager.getConfiguration().setGenericAssetNodeTypes(preExistingGenericNodeTypes); } } @Test public void testBaseTypes_default() { - Map> preExistingServiceNodeTypes = configurationManager.getConfiguration().getServiceNodeTypes(); + Map preExistingServiceNodeTypes = configurationManager.getConfiguration().getServiceBaseNodeTypes(); Map preExistingGenericNodeTypes = configurationManager.getConfiguration().getGenericAssetNodeTypes(); @@ -506,7 +512,7 @@ public class ElementOperationTest extends ModelTestBase { Map genericNodeTypes = new HashMap<>(); genericNodeTypes.put("Service", "org.service.default"); configurationManager.getConfiguration().setGenericAssetNodeTypes(genericNodeTypes); - configurationManager.getConfiguration().setServiceNodeTypes(null); + configurationManager.getConfiguration().setServiceBaseNodeTypes(null); HealingJanusGraphDao healingJanusGraphDao = mock(HealingJanusGraphDao.class); final var elementOperation = new ElementOperation(new JanusGraphGenericDao(new JanusGraphClient()), healingJanusGraphDao); @@ -519,14 +525,60 @@ public class ElementOperationTest extends ModelTestBase { when(healingJanusGraphDao.getParentVertices(baseTypeVertex, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseAll)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); - List baseTypes = elementOperation.getBaseTypes("serviceCategoryA", null); + List baseTypes = elementOperation.getServiceBaseTypes("serviceCategoryA", null); assertEquals(1, baseTypes.size()); assertEquals("org.service.default", baseTypes.get(0).getToscaResourceName()); assertEquals(1, baseTypes.get(0).getVersions().size()); } finally { - configurationManager.getConfiguration().setServiceNodeTypes(preExistingServiceNodeTypes); + configurationManager.getConfiguration().setServiceBaseNodeTypes(preExistingServiceNodeTypes); configurationManager.getConfiguration().setGenericAssetNodeTypes(preExistingGenericNodeTypes); } } + + @Test + public void testGetServiceBaseTypes_categoryWithRequiredBaseType() { + defaultBaseTypeMock(); + final List actualBaseTypeList = elementOperation.getServiceBaseTypes("CategoryA", null); + assertEquals(actualBaseTypeList.size(), 1); + final BaseType expectedBaseType = actualBaseTypeList.get(0); + assertEquals(expectedBaseType.getToscaResourceName(), "org.openecomp.resource.abstract.nodes.A"); + + } + + @Test + public void testGetServiceBaseTypes_categoryWithOptionalBaseType() { + defaultBaseTypeMock(); + final List actualBaseTypeList = elementOperation.getServiceBaseTypes("CategoryC", null); + assertEquals(actualBaseTypeList.size(), 2); + assertEquals(actualBaseTypeList.get(0).getToscaResourceName(), "org.openecomp.resource.abstract.nodes.C1"); + assertEquals(actualBaseTypeList.get(1).getToscaResourceName(), "org.openecomp.resource.abstract.nodes.C2"); + } + + @Test + public void testGetServiceBaseTypes_categoryWithNoBaseType() { + defaultBaseTypeMock(); + final List actualBaseTypeList = elementOperation.getServiceBaseTypes("CategoryB", null); + assertTrue(actualBaseTypeList.isEmpty()); + } + + @Test + public void testGetServiceBaseTypes_notConfiguredCategoryThatFallsBackToGenericType() { + defaultBaseTypeMock(); + final List actualBaseTypeList = elementOperation.getServiceBaseTypes("CategoryD", null); + + assertEquals(actualBaseTypeList.size(), 1); + final BaseType expectedBaseType = actualBaseTypeList.get(0); + assertEquals(expectedBaseType.getToscaResourceName(), "org.openecomp.resource.abstract.nodes.service"); + } + + private void defaultBaseTypeMock() { + final GraphVertex baseTypeVertex = mock(GraphVertex.class); + when(baseTypeVertex.getMetadataProperty(GraphPropertyEnum.VERSION)).thenReturn("1.0"); + when(healingJanusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap(), isNull(), eq(JsonParseFlagEnum.ParseAll), isNull())) + .thenReturn(Either.left(Collections.singletonList(baseTypeVertex))); + when(healingJanusGraphDao.getParentVertices(eq(baseTypeVertex), eq(EdgeLabelEnum.DERIVED_FROM), eq(JsonParseFlagEnum.ParseAll))) + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + } + } diff --git a/catalog-model/src/test/resources/config/configuration.yaml b/catalog-model/src/test/resources/config/configuration.yaml index 02b9af9c1b..a3ab97ab60 100644 --- a/catalog-model/src/test/resources/config/configuration.yaml +++ b/catalog-model/src/test/resources/config/configuration.yaml @@ -393,13 +393,18 @@ genericAssetNodeTypes: PNF: org.openecomp.resource.abstract.nodes.PNF Service: org.openecomp.resource.abstract.nodes.service -serviceNodeTypes: +serviceBaseNodeTypes: CategoryA: - - org.openecomp.resource.abstract.nodes.A + required: true + baseTypes: + - org.openecomp.resource.abstract.nodes.A CategoryB: - - org.openecomp.resource.abstract.nodes.B + required: false CategoryC: - - org.openecomp.resource.abstract.nodes.C + required: false + baseTypes: + - org.openecomp.resource.abstract.nodes.C1 + - org.openecomp.resource.abstract.nodes.C2 workloadContext: Production environmentContext: diff --git a/catalog-ui/src/app/models/base-types.ts b/catalog-ui/src/app/models/base-types.ts index ac5f8428f3..526355e0f8 100644 --- a/catalog-ui/src/app/models/base-types.ts +++ b/catalog-ui/src/app/models/base-types.ts @@ -20,9 +20,10 @@ interface ListBaseTypesResponse { baseTypes: BaseTypeResponse[]; + required: boolean; } interface BaseTypeResponse { - toscaResourceName:string; - versions:string[]; + toscaResourceName: string; + versions: string[]; } diff --git a/catalog-ui/src/app/models/components/service.ts b/catalog-ui/src/app/models/components/service.ts index d11a06abdf..1c7c6b60b4 100644 --- a/catalog-ui/src/app/models/components/service.ts +++ b/catalog-ui/src/app/models/components/service.ts @@ -220,6 +220,10 @@ export class Service extends Component { this.iconSprite = "sprite-services-icons"; } + public isSubstituteCandidate(): boolean { + return !!this.derivedFromGenericType; + } + public toJSON = ():any => { let temp = angular.copy(this); temp.componentService = undefined; diff --git a/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.spec.ts b/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.spec.ts index d5c0b6093b..2f27f468b6 100644 --- a/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.spec.ts +++ b/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.spec.ts @@ -169,28 +169,49 @@ describe('composition-panel component', () => { expect(fixture).toMatchSnapshot(); }); - it('When Topology Template is Service and no instance is selected Expect (info, deployment, inputs, info and api)', () => { - + it('When Topology Template is Service and no instance is selected Expect tabs info, deployment, inputs, info, api, substitution filter', () => { const selectedComponent: Service = new Service(null, null); selectedComponent.isResource = jest.fn(() => false); - selectedComponent.isService = jest.fn(() => true ); + selectedComponent.isService = jest.fn(() => true); + selectedComponent.isSubstituteCandidate = jest.fn(() => true); + fixture.componentInstance.store.select = jest.fn(() => Observable.of(selectedComponent)); + + fixture.componentInstance.topologyTemplate = selectedComponent; + + // Call ngOnInit + fixture.componentInstance.ngOnInit(); + + // Expect that + expect(fixture.componentInstance.tabs.length).toBe(6); + expect(fixture.componentInstance.tabs[0]).toEqual(tabs.infoTab); + expect(fixture.componentInstance.tabs[1]).toEqual(tabs.deploymentArtifacts); + expect(fixture.componentInstance.tabs[2]).toEqual(tabs.inputs); + expect(fixture.componentInstance.tabs[3]).toEqual(tabs.infoArtifacts); + expect(fixture.componentInstance.tabs[4]).toEqual(tabs.apiArtifacts); + expect(fixture.componentInstance.tabs[5]).toEqual(tabs.substitutionFilter); + }); + + it('When Topology Template is Service without base type, and no instance is selected. Expect tabs info, deployment, inputs, info and api', () => { + + const selectedComponent: Service = new Service(null, null); + selectedComponent.isResource = jest.fn(() => false); + selectedComponent.isService = jest.fn(() => true); + selectedComponent.isSubstituteCandidate = jest.fn(() => false); fixture.componentInstance.store.select = jest.fn(() => Observable.of(selectedComponent)); - // const pnfMock = Mock.of({ isResource : () => false }); fixture.componentInstance.topologyTemplate = selectedComponent; // Call ngOnInit fixture.componentInstance.ngOnInit(); // Expect that - expect (fixture.componentInstance.tabs.length).toBe(6); - expect (fixture.componentInstance.tabs[0]).toEqual(tabs.infoTab); - expect (fixture.componentInstance.tabs[1]).toEqual(tabs.deploymentArtifacts); - expect (fixture.componentInstance.tabs[2]).toEqual(tabs.inputs); - expect (fixture.componentInstance.tabs[3]).toEqual(tabs.infoArtifacts); - expect (fixture.componentInstance.tabs[4]).toEqual(tabs.apiArtifacts); - expect (fixture.componentInstance.tabs[5]).toEqual(tabs.substitutionFilter); + expect(fixture.componentInstance.tabs.length).toBe(5); + expect(fixture.componentInstance.tabs[0]).toEqual(tabs.infoTab); + expect(fixture.componentInstance.tabs[1]).toEqual(tabs.deploymentArtifacts); + expect(fixture.componentInstance.tabs[2]).toEqual(tabs.inputs); + expect(fixture.componentInstance.tabs[3]).toEqual(tabs.infoArtifacts); + expect(fixture.componentInstance.tabs[4]).toEqual(tabs.apiArtifacts); }); @@ -223,6 +244,7 @@ describe('composition-panel component', () => { const selectedComponent: Service = new Service(null, null); selectedComponent.isResource = jest.fn(() => false); selectedComponent.isService = jest.fn(() => true ); + selectedComponent.isSubstituteCandidate = jest.fn(() => true ); fixture.componentInstance.store.select = jest.fn(() => Observable.of(selectedComponent)); fixture.componentInstance.selectedComponentIsServiceProxyInstance = jest.fn(() => true); diff --git a/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.ts b/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.ts index 6ed73b3384..3422cc142d 100644 --- a/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.ts +++ b/catalog-ui/src/app/ng2/pages/composition/panel/composition-panel.component.ts @@ -264,7 +264,7 @@ export class CompositionPanelComponent { this.tabs.push(tabs.apiArtifacts); } - if((component.isService() || this.isVF()) && !this.isComponentInstanceSelected()){ + if (this.showSubstitutionFilterTab(component)) { this.tabs.push(tabs.substitutionFilter); } @@ -279,6 +279,17 @@ export class CompositionPanelComponent { } + private showSubstitutionFilterTab(component): boolean { + if ((component.isService() || this.isVF()) && !this.isComponentInstanceSelected()) { + if (component.isService()) { + return (component).isSubstituteCandidate(); + } + return true; + } + + return false; + } + private toggleSidebarDisplay = () => { // this.withSidebar = !this.withSidebar; this.store.dispatch(new OnSidebarOpenOrCloseAction()); diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html index b54cbc97c2..747624a03f 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html @@ -87,7 +87,7 @@
Add Property
+ (click)="addProperty(component.model)" data-tests-id="properties-add-button" [ngClass]="{'disabled': !showAddProperties()}">Add Property
Add Input
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts index 09fd888755..e0a1cbf8ff 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts @@ -38,6 +38,7 @@ import { PropertyBEModel, PropertyFEModel, PropertyInputDetail, + Service, SimpleFlatProperty } from "app/models"; import {ResourceType} from "app/utils"; @@ -67,7 +68,6 @@ import {ToscaPresentationData} from "../../../models/tosca-presentation"; import {Observable} from "rxjs"; import {ToscaGetFunctionType} from "../../../models/tosca-get-function-type.enum"; import {TranslateService} from "../../shared/translator/translate.service"; -import {Model} from '../../../models/model'; const SERVICE_SELF_TITLE = "SELF"; @Component({ @@ -250,6 +250,13 @@ export class PropertiesAssignmentComponent { return this.selectedInstanceData && this.selectedInstanceData.uniqueId == this.component.uniqueId; } + showAddProperties = (): boolean => { + if (this.component.isService() && !(this.component).isSubstituteCandidate()) { + return false; + } + return this.isSelf(); + } + getServiceProperties() { this.loadingProperties = true; this.topologyTemplateService diff --git a/catalog-ui/src/app/ng2/services/element.service.ts b/catalog-ui/src/app/ng2/services/element.service.ts index b3cf8c38f4..dc0218fcc3 100644 --- a/catalog-ui/src/app/ng2/services/element.service.ts +++ b/catalog-ui/src/app/ng2/services/element.service.ts @@ -33,10 +33,9 @@ export class ElementService { this.baseUrl = sdcConfig.api.root; } - getCategoryBasetypes(categoryName:string, modelName:string):Observable { + getCategoryBaseTypes(categoryName: string, modelName: string): Observable { let modelQueryParam: string = modelName ? '?model=' + modelName : ''; - return this.http.get(this.baseUrl + "/v1/category/services/" + categoryName + "/baseTypes" + modelQueryParam) - .pipe(map(response => response.baseTypes)); + return this.http.get(this.baseUrl + "/v1/category/services/" + categoryName + "/baseTypes" + modelQueryParam); } } diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts index c423028467..9c103b4c4a 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts @@ -248,7 +248,6 @@ export class GeneralViewModel { this.$scope.componentCategories = new componentCategories(); this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory; - // Init UIModel this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name); @@ -454,15 +453,24 @@ export class GeneralViewModel { this.$scope.initBaseTypes = ():void => { if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) { + if (!this.$scope.component.derivedFromGenericType) { + this.$scope.component.derivedFromGenericVersion = undefined; + this.$scope.showBaseTypeVersions = false; + return; + } let modelName = this.$scope.component.model ? this.$scope.component.model : null; - this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => { + const categoryName = this.$scope.component.categories[0].name; + this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((data: ListBaseTypesResponse) => { this.$scope.baseTypes = [] this.$scope.baseTypeVersions = [] - data.forEach(baseType => { - this.$scope.baseTypes.push(baseType.toscaResourceName) - if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){ + this.$scope.isBaseTypeRequired = data.required; + data.baseTypes.forEach(baseType => { + this.$scope.baseTypes.push(baseType.toscaResourceName); + if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) { baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version)); - }}); + } + }); + this.$scope.showBaseTypeVersions = true; }) } }; @@ -734,16 +742,18 @@ export class GeneralViewModel { } } if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) { - let modelName : string = this.$scope.component.model ? this.$scope.component.model : null; - this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => { - - if(this.$scope.isCreateMode()){ + const modelName : string = this.$scope.component.model ? this.$scope.component.model : null; + this.elementService.getCategoryBaseTypes(this.$scope.component.categories[0].name, modelName) + .subscribe((data: ListBaseTypesResponse) => { + if (this.$scope.isCreateMode()) { this.loadBaseTypes(data); } else { - var isValidForBaseType:boolean = false; - data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){ - isValidForBaseType = true; - };}); + let isValidForBaseType:boolean = false; + data.baseTypes.forEach(baseType => { + if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) { + isValidForBaseType = true; + } + }); this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType); } }); @@ -760,16 +770,24 @@ export class GeneralViewModel { }; this.$scope.onBaseTypeChange = (): void => { - let modelName : string = this.$scope.component.model ? this.$scope.component.model : null; - this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => { + if (!this.$scope.component.derivedFromGenericType) { + this.$scope.component.derivedFromGenericVersion = undefined; + this.$scope.showBaseTypeVersions = false; + return; + } + + const modelName : string = this.$scope.component.model ? this.$scope.component.model : null; + const categoryName = this.$scope.component.categories[0].name; + this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((baseTypeResponseList: ListBaseTypesResponse) => { this.$scope.baseTypeVersions = [] - data.forEach(baseType => { - if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) { + baseTypeResponseList.baseTypes.forEach(baseType => { + if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) { baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version)); this.$scope.component.derivedFromGenericVersion = baseType.versions[0]; - }; + } }); - }) + this.$scope.showBaseTypeVersions = true; + }); }; this.$scope.onModelChange = (): void => { @@ -785,8 +803,8 @@ export class GeneralViewModel { this.$scope.component.icon = DEFAULT_ICON; } }; - this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload); + this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload); this.$scope.isMetadataKeyMandatory = (key: string): boolean => { let metadataKey = this.getMetadataKey(this.$scope.component.categories, key); @@ -837,22 +855,28 @@ export class GeneralViewModel { private filterBaseTypesByModelAndCategory(modelName:string) { let categories = this.$scope.component.categories; if (categories) { - this.elementService.getCategoryBasetypes(categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => { + this.elementService.getCategoryBaseTypes(categories[0].name, modelName).subscribe((data: ListBaseTypesResponse) => { this.loadBaseTypes(data); }); } } - private loadBaseTypes(data:BaseTypeResponse[]) { + private loadBaseTypes(baseTypeResponseList: ListBaseTypesResponse) { + this.$scope.isBaseTypeRequired = baseTypeResponseList.required; this.$scope.baseTypes = []; this.$scope.baseTypeVersions = []; - data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName)); - let baseType = data[0]; - if (baseType) { + baseTypeResponseList.baseTypes.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName)); + if (this.$scope.isBaseTypeRequired) { + const baseType = baseTypeResponseList.baseTypes[0]; baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version)); this.$scope.component.derivedFromGenericType = baseType.toscaResourceName; - this.$scope.component.derivedFromGenericVersion = baseType.versions[0]; + this.$scope.component.derivedFromGenericVersion = this.$scope.baseTypeVersions[0]; + this.$scope.showBaseTypeVersions = true; + return } + this.$scope.component.derivedFromGenericType = undefined; + this.$scope.component.derivedFromGenericVersion = undefined; + this.$scope.showBaseTypeVersions = false; } private setUnsavedChanges = (hasChanges: boolean): void => { diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html index e7ce00b176..bb0cceb173 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html @@ -591,25 +591,25 @@ -
-
- - +
+ +
-
- +
+