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 +++++++++--------- 18 files changed, 994 insertions(+), 937 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 (limited to 'catalog-be') 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() { -- cgit 1.2.3-korg