From 5b593496b8f1b8e8be8d7d2dbcc223332e65a49b Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 29 Jul 2018 16:13:45 +0300 Subject: re base code Change-Id: I12a5ca14a6d8a87e9316b9ff362eb131105f98a5 Issue-ID: SDC-1566 Signed-off-by: Michael Lando --- .../model/AdditionalInformationDefinitionTest.java | 4 +- .../sdc/be/model/ArtifactDefinitionTest.java | 6 +- .../sdc/be/model/ArtifactUiDownloadDataTest.java | 54 - .../org/openecomp/sdc/be/model/CapReqDefTest.java | 4 +- .../sdc/be/model/CapabilityDefinitionTest.java | 6 +- .../CapabilityRequirementRelationshipTest.java | 7 - .../sdc/be/model/CapabilityTypeDefinitionTest.java | 4 +- .../sdc/be/model/CapabiltyInstanceTest.java | 4 +- .../sdc/be/model/ComponentInstInputsMapTest.java | 10 +- .../sdc/be/model/ComponentInstanceInputTest.java | 4 +- .../be/model/ComponentInstancePropertyTest.java | 4 +- .../sdc/be/model/ComponentInstanceTest.java | 6 +- .../sdc/be/model/ComponentParametersViewTest.java | 45 +- .../org/openecomp/sdc/be/model/CsarInfoTest.java | 201 --- .../sdc/be/model/DataTypeDefinitionTest.java | 4 +- .../sdc/be/model/FunctionalMenuInfoTest.java | 44 - .../sdc/be/model/GroupDefinitionTest.java | 6 +- .../openecomp/sdc/be/model/GroupInstanceTest.java | 11 +- .../sdc/be/model/GroupTypeDefinitionTest.java | 10 +- .../sdc/be/model/InputDefinitionTest.java | 4 +- .../sdc/be/model/InterfaceDefinitionTest.java | 6 +- .../org/openecomp/sdc/be/model/ModelTestBase.java | 47 +- .../openecomp/sdc/be/model/NodeTypeInfoTest.java | 135 -- .../sdc/be/model/ParsedToscaYamlInfoTest.java | 4 +- .../sdc/be/model/PolicyDefinitionTest.java | 6 +- .../sdc/be/model/PolicyTargetDTOTest.java | 4 +- .../sdc/be/model/PolicyTypeDefinitionTest.java | 4 +- .../org/openecomp/sdc/be/model/ProductTest.java | 4 +- .../sdc/be/model/PropertyDefinitionTest.java | 6 +- .../sdc/be/model/RequirementImplDefTest.java | 112 -- .../sdc/be/model/RequirementInstanceTest.java | 66 - .../org/openecomp/sdc/be/model/ResourceTest.java | 11 +- .../org/openecomp/sdc/be/model/ServiceTest.java | 4 +- .../sdc/be/model/TargetCapabilityRelDefTest.java | 4 +- .../openecomp/sdc/be/model/UploadCapInfoTest.java | 79 - .../be/model/UploadComponentInstanceInfoTest.java | 4 +- .../openecomp/sdc/be/model/UploadPropInfoTest.java | 102 -- .../openecomp/sdc/be/model/UploadReqInfoTest.java | 55 - .../sdc/be/model/UploadResourceInfoTest.java | 6 +- .../model/cache/ApplicationDataTypeCacheTest.java | 13 +- .../sdc/be/model/cache/ComponentCacheTest.java | 973 ++++++------- .../be/model/cache/jobs/CheckAndUpdateJobTest.java | 7 +- .../be/model/category/CategoryDefinitionTest.java | 57 - .../model/category/SubCategoryDefinitionTest.java | 57 - .../model/config/ModelOperationsSpringConfig.java | 2 +- .../be/model/jsontitan/datamodel/NodeTypeTest.java | 173 --- .../jsontitan/datamodel/TopologyTemplateTest.java | 414 ------ .../datamodel/ToscaElementTypeEnumTest.java | 25 - .../jsontitan/enums/JsonConstantKeysEnumTest.java | 22 - .../jsontitan/operations/ArchiveOperationTest.java | 486 +++++++ .../operations/ArtifactsOperationsTest.java | 21 +- .../ExternalReferencesOperationTest.java | 96 +- .../jsontitan/operations/GroupsOperationTest.java | 102 ++ .../operations/InterfacesOperationTest.java | 24 +- .../operations/NodeTemplateOperationGraphTest.java | 239 +++ .../operations/NodeTemplateOperationTest.java | 369 +++-- .../operations/PolicyOperationIntegrationTest.java | 24 +- .../jsontitan/operations/PolicyOperationTest.java | 17 +- ...TemplateOperationCapabilityIntegrationTest.java | 47 +- .../TopologyTemplateOperationIntegrationTest.java | 200 --- .../operations/TopologyTemplateOperationTest.java | 82 +- .../ToscaElementOperationCatalogTest.java | 73 + .../operations/ToscaElementOperationTest.java | 21 +- .../operations/ToscaElementOperationTestImpl.java | 3 +- .../ToscaOperationFacadePoliciesTest.java | 35 +- .../operations/ToscaOperationFacadeTest.java | 115 +- .../jsontitan/operations/UpgradeOperationTest.java | 183 +++ .../be/model/jsontitan/utils/GraphTestUtils.java | 40 +- .../model/jsontitan/utils/InterfaceUtilsTest.java | 10 +- .../sdc/be/model/operations/JsonObjectTest.java | 73 +- .../impl/AdditionalInformationOperationTest.java | 71 +- .../impl/AnnotationTypeOperationsTest.java | 197 +++ .../operations/impl/ArtifactOperationTest.java | 751 +++++----- .../impl/CapabilityTypeOperationTest.java | 570 +++++--- .../impl/ComponentInstanceOperationTest.java | 3 +- .../operations/impl/ElementOperationTest.java | 108 +- .../operations/impl/GroupTypeOperationTest.java | 577 +++++++- .../impl/HeatParametersOperationTest.java | 324 ++--- .../operations/impl/InterfaceOperationTest.java | 342 ++--- .../operations/impl/PolicyTypeOperationTest.java | 608 ++++---- .../operations/impl/PropertyOperationTest.java | 981 ++++++------- .../impl/ToscaElementLifecycleOperationTest.java | 1071 +++++++------- .../operations/impl/UserAdminOperationTest.java | 553 ++++--- .../impl/util/DataTypeValidatorTest.java | 1532 ++++++++++---------- .../operations/impl/util/OperationTestsUtil.java | 101 +- .../be/model/operations/impl/util/PrintGraph.java | 561 ++++--- .../impl/util/ResourceCreationUtils.java | 18 +- .../model/serialize/TestResourceSerialization.java | 232 +-- .../sdc/be/model/tosca/ToscaTypeTest.java | 65 - .../tosca/constraints/EqualConstraintTest.java | 28 - .../constraints/GreaterThanConstraintTest.java | 36 - .../tosca/constraints/InRangeConstraintTest.java | 58 - .../tosca/constraints/LengthConstraintTest.java | 36 - .../constraints/LessOrEqualConstraintTest.java | 38 - .../tosca/constraints/MaxLengthConstraintTest.java | 34 - .../tosca/constraints/MinLengthConstraintTest.java | 36 - .../tosca/constraints/PatternConstraintTest.java | 23 - .../constraints/ValidValuesConstraintTest.java | 40 - .../tosca/converters/BooleanConverterTest.java | 37 - .../converters/DataTypePropertyConverterTest.java | 15 +- .../tosca/converters/DefaultConverterTest.java | 37 - .../model/tosca/converters/FloatConverterTest.java | 22 - .../tosca/converters/HeatBooleanConverterTest.java | 23 - .../HeatCommaDelimitedListConverterTest.java | 23 - .../tosca/converters/HeatJsonConverterTest.java | 23 - .../tosca/converters/HeatNumberConverterTest.java | 23 - .../tosca/converters/HeatStringConverterTest.java | 32 +- .../tosca/converters/IntegerConverterTest.java | 46 - .../model/tosca/converters/JsonConverterTest.java | 37 - .../model/tosca/converters/ListConverterTest.java | 28 - .../tosca/converters/LowerCaseConverterTest.java | 4 +- .../model/tosca/converters/MapConverterTest.java | 43 - .../tosca/converters/StringConvertorTest.java | 22 - .../converters/ToscaBooleanConverterTest.java | 21 - .../tosca/converters/ToscaFloatConverterTest.java | 8 +- .../converters/ToscaJsonValueConverterTest.java | 37 - .../converters/ToscaListValueConverterTest.java | 23 - .../tosca/converters/ToscaStringConvertorTest.java | 37 - .../converters/ToscaValueDefaultConverterTest.java | 37 - .../tosca/validators/IntegerValidatorTest.java | 78 +- .../model/tosca/validators/MapValidatorTest.java | 4 +- .../validators/ToscaBooleanValidatorTest.java | 4 +- .../model/tosca/version/ComparableVersionTest.java | 62 - .../sdc/be/model/tosca/version/VersionTest.java | 129 -- .../sdc/be/ui/model/UiCategoriesTest.java | 80 - .../be/ui/model/UiComponentDataTransferTest.java | 444 ------ .../be/ui/model/UiResourceDataTransferTest.java | 193 --- .../sdc/be/ui/model/UiResourceMetadataTest.java | 213 --- .../sdc/be/ui/model/UiServiceDataTransferTest.java | 58 - .../sdc/be/ui/model/UiServiceMetadataTest.java | 122 -- .../sdc/be/unittests/utils/FactoryUtilsTest.java | 18 +- .../be/unittests/utils/ModelConfDependentTest.java | 2 +- 132 files changed, 6892 insertions(+), 9187 deletions(-) delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactUiDownloadDataTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/CsarInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/FunctionalMenuInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/NodeTypeInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementImplDefTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementInstanceTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadCapInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadPropInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadReqInfoTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/category/CategoryDefinitionTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/category/SubCategoryDefinitionTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/ToscaTypeTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraintTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ListConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/MapConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertorTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertorTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersionTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/VersionTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiCategoriesTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransferTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransferTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceMetadataTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransferTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceMetadataTest.java (limited to 'catalog-model/src/test/java/org') diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/AdditionalInformationDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/AdditionalInformationDefinitionTest.java index f8f116539f..697cdbe6ab 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/AdditionalInformationDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/AdditionalInformationDefinitionTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import java.util.LinkedList; + public class AdditionalInformationDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactDefinitionTest.java index 3c0034aa3b..e374eeafaf 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactDefinitionTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; - public class ArtifactDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactUiDownloadDataTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactUiDownloadDataTest.java deleted file mode 100644 index dc801581b9..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ArtifactUiDownloadDataTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.openecomp.sdc.be.model; - -import org.junit.Test; - -public class ArtifactUiDownloadDataTest { - - private ArtifactUiDownloadData createTestSubject() { - return new ArtifactUiDownloadData(); - } - - - @Test - public void testSetArtifactName() throws Exception { - ArtifactUiDownloadData testSubject; - String artifactName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setArtifactName(artifactName); - } - - - @Test - public void testSetBase64Contents() throws Exception { - ArtifactUiDownloadData testSubject; - String base64Contents = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setBase64Contents(base64Contents); - } - - - @Test - public void testGetArtifactName() throws Exception { - ArtifactUiDownloadData testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getArtifactName(); - } - - - @Test - public void testGetBase64Contents() throws Exception { - ArtifactUiDownloadData testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getBase64Contents(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapReqDefTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapReqDefTest.java index 6c7e879a9e..3965426ee6 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapReqDefTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapReqDefTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; +import org.junit.Test; + import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; - public class CapReqDefTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityDefinitionTest.java index ffe0a829bb..8fba70efd9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityDefinitionTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import java.util.LinkedList; +import java.util.List; + public class CapabilityDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationshipTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationshipTest.java index 85cbef6958..8528eed85a 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationshipTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationshipTest.java @@ -70,11 +70,4 @@ public class CapabilityRequirementRelationshipTest { testSubject.setRequirement(requirement); } - @Test - public void testGetSerialversionuid() throws Exception { - long result; - - // default test - result = CapabilityRequirementRelationship.getSerialversionuid(); - } } \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityTypeDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityTypeDefinitionTest.java index dde80598e7..117c0f6f1a 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityTypeDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabilityTypeDefinitionTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.CapabilityTypeDataDefinition; +import java.util.Map; + public class CapabilityTypeDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabiltyInstanceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabiltyInstanceTest.java index ff13a6ce04..d18680e59d 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabiltyInstanceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CapabiltyInstanceTest.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.model; -import java.util.Map; - import org.junit.Test; +import java.util.Map; + public class CapabiltyInstanceTest { private CapabiltyInstance createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstInputsMapTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstInputsMapTest.java index 006d4fc7ad..95247c7cd4 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstInputsMapTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstInputsMapTest.java @@ -1,12 +1,13 @@ package org.openecomp.sdc.be.model; +import org.junit.Assert; +import org.junit.Test; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import org.junit.Test; - public class ComponentInstInputsMapTest { private ComponentInstInputsMap createTestSubject() { @@ -46,7 +47,7 @@ public class ComponentInstInputsMapTest { @Test public void testSetComponentInstancePropInput() throws Exception { ComponentInstInputsMap testSubject; - Map> componentInstanceProperties = null; + Map> componentInstanceProperties = new HashMap<>(); // default test testSubject = createTestSubject(); @@ -63,8 +64,7 @@ public class ComponentInstInputsMapTest { try { testSubject.resolvePropertiesToDeclare(); } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Assert.assertTrue(e.getClass() == IllegalStateException.class); } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceInputTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceInputTest.java index d02b05fac5..fbb4bd8c24 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceInputTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceInputTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import java.util.List; + public class ComponentInstanceInputTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstancePropertyTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstancePropertyTest.java index a734722f2a..cec822fe00 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstancePropertyTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstancePropertyTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import java.util.List; + public class ComponentInstancePropertyTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceTest.java index 39eba764c9..5c45ef4d9c 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentInstanceTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model; -import java.util.List; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import java.util.List; +import java.util.Map; + public class ComponentInstanceTest { private ComponentInstance createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java index 8dd2d0da3f..d84b821950 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; - import org.junit.Test; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import java.util.LinkedList; + public class ComponentParametersViewTest { private ComponentParametersView createTestSubject() { @@ -214,17 +214,6 @@ public class ComponentParametersViewTest { } - @Test - public void testSetIgnoreAdditionalInformation() throws Exception { - ComponentParametersView testSubject; - boolean ignoreAdditionalInformation = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreAdditionalInformation(ignoreAdditionalInformation); - } - - @Test public void testIsIgnoreArtifacts() throws Exception { ComponentParametersView testSubject; @@ -301,16 +290,6 @@ public class ComponentParametersViewTest { result = testSubject.isIgnoreInterfaces(); } - - @Test - public void testSetIgnoreInterfaces() throws Exception { - ComponentParametersView testSubject; - boolean ignoreInterfaces = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreInterfaces(ignoreInterfaces); - } @Test @@ -345,16 +324,6 @@ public class ComponentParametersViewTest { result = testSubject.isIgnoreComponentInstancesAttributesFrom(); } - - @Test - public void testSetIgnoreComponentInstancesAttributesFrom() throws Exception { - ComponentParametersView testSubject; - boolean ignoreComponentInstancesAttributesFrom = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreComponentInstancesAttributesFrom(ignoreComponentInstancesAttributesFrom); - } @Test @@ -367,16 +336,6 @@ public class ComponentParametersViewTest { result = testSubject.isIgnoreDerivedFrom(); } - - @Test - public void testSetIgnoreDerivedFrom() throws Exception { - ComponentParametersView testSubject; - boolean ignoreDerivedFrom = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreDerivedFrom(ignoreDerivedFrom); - } @Test diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CsarInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/CsarInfoTest.java deleted file mode 100644 index d7444e3602..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/CsarInfoTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.openecomp.sdc.be.model; - -import java.util.Map; -import java.util.Queue; - -import org.junit.Test; - - -public class CsarInfoTest { - - private CsarInfo createTestSubject() { - return new CsarInfo("", new User(), "", null, "", false); - } - - - @Test - public void testGetVfResourceName() throws Exception { - CsarInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getVfResourceName(); - } - - - @Test - public void testSetVfResourceName() throws Exception { - CsarInfo testSubject; - String vfResourceName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setVfResourceName(vfResourceName); - } - - - @Test - public void testGetModifier() throws Exception { - CsarInfo testSubject; - User result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getModifier(); - } - - - @Test - public void testSetModifier() throws Exception { - CsarInfo testSubject; - User modifier = null; - - // default test - testSubject = createTestSubject(); - testSubject.setModifier(modifier); - } - - - @Test - public void testGetCsarUUID() throws Exception { - CsarInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCsarUUID(); - } - - - @Test - public void testSetCsarUUID() throws Exception { - CsarInfo testSubject; - String csarUUID = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCsarUUID(csarUUID); - } - - - @Test - public void testGetCsar() throws Exception { - CsarInfo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCsar(); - } - - - @Test - public void testSetCsar() throws Exception { - CsarInfo testSubject; - Map csar = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCsar(csar); - } - - - @Test - public void testGetMainTemplateContent() throws Exception { - CsarInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMainTemplateContent(); - } - - - @Test - public void testGetMappedToscaMainTemplate() throws Exception { - CsarInfo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMappedToscaMainTemplate(); - } - - - @Test - public void testGetCreatedNodesToscaResourceNames() throws Exception { - CsarInfo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCreatedNodesToscaResourceNames(); - } - - - @Test - public void testSetCreatedNodesToscaResourceNames() throws Exception { - CsarInfo testSubject; - Map createdNodesToscaResourceNames = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCreatedNodesToscaResourceNames(createdNodesToscaResourceNames); - } - - - @Test - public void testGetCvfcToCreateQueue() throws Exception { - CsarInfo testSubject; - Queue result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCvfcToCreateQueue(); - } - - - @Test - public void testSetCvfcToCreateQueue() throws Exception { - CsarInfo testSubject; - Queue cvfcToCreateQueue = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCvfcToCreateQueue(cvfcToCreateQueue); - } - - - @Test - public void testIsUpdate() throws Exception { - CsarInfo testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isUpdate(); - } - - - @Test - public void testSetUpdate() throws Exception { - CsarInfo testSubject; - boolean isUpdate = false; - - // default test - testSubject = createTestSubject(); - testSubject.setUpdate(isUpdate); - } - - - @Test - public void testGetCreatedNodes() throws Exception { - CsarInfo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCreatedNodes(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/DataTypeDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/DataTypeDefinitionTest.java index 1b5abb8a1c..d7798272ae 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/DataTypeDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/DataTypeDefinitionTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; +import java.util.List; + public class DataTypeDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/FunctionalMenuInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/FunctionalMenuInfoTest.java deleted file mode 100644 index ca5d1a2ec8..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/FunctionalMenuInfoTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openecomp.sdc.be.model; - -import org.junit.Test; - - -public class FunctionalMenuInfoTest { - - private FunctionalMenuInfo createTestSubject() { - return new FunctionalMenuInfo(); - } - - - @Test - public void testGetFunctionalMenu() throws Exception { - FunctionalMenuInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getFunctionalMenu(); - } - - - @Test - public void testSetFunctionalMenu() throws Exception { - FunctionalMenuInfo testSubject; - String functionalMenu = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setFunctionalMenu(functionalMenu); - } - - - @Test - public void testToString() throws Exception { - FunctionalMenuInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupDefinitionTest.java index 58709aa889..f8b250d842 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupDefinitionTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import java.util.LinkedList; +import java.util.List; + public class GroupDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupInstanceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupInstanceTest.java index 84acf9dac8..346e9d3301 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupInstanceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupInstanceTest.java @@ -1,15 +1,14 @@ package org.openecomp.sdc.be.model; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import mockit.Deencapsulation; import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import mockit.Deencapsulation; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; public class GroupInstanceTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupTypeDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupTypeDefinitionTest.java index 47e11e1d29..4d70048cfa 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupTypeDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/GroupTypeDefinitionTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; +import java.util.HashMap; +import java.util.List; + public class GroupTypeDefinitionTest { @@ -46,7 +46,7 @@ public class GroupTypeDefinitionTest { // default test testSubject = createTestSubject(); - testSubject.getCapabilityTypes(); + testSubject.getCapabilities(); } @Test @@ -55,7 +55,7 @@ public class GroupTypeDefinitionTest { // default test testSubject = createTestSubject(); - testSubject.setCapabilityTypes(new LinkedList<>()); + testSubject.setCapabilities(new HashMap<>()); } @Test diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/InputDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/InputDefinitionTest.java index e865f4e81e..0b8bdd5091 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/InputDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/InputDefinitionTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import java.util.List; + public class InputDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/InterfaceDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/InterfaceDefinitionTest.java index 5a8e155056..41cad06014 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/InterfaceDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/InterfaceDefinitionTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.HashMap; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import java.util.HashMap; +import java.util.Map; + public class InterfaceDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java index 04c9d5149d..ade46d8102 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java @@ -20,17 +20,30 @@ package org.openecomp.sdc.be.model; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.util.Iterator; + public class ModelTestBase { - protected static ConfigurationManager configurationManager; + protected static ConfigurationManager configurationManager; + protected static final String CONTAINER_ID = "containerId"; + protected static final String CONTAINER_NAME = "containerName"; - public static void init() { + public static void init() { String appConfigDir = "src/test/resources/config"; ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); @@ -42,4 +55,34 @@ public class ModelTestBase { configurationManager.setConfiguration(configuration); } + + protected void removeGraphVertices(Either graphResult) { + TitanGraph graph = graphResult.left().value(); + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + } + + protected PropertyDefinition createSimpleProperty(String defaultValue, String name, String type) { + PropertyDefinition prop1 = new PropertyDefinition(); + prop1.setDefaultValue(defaultValue); + prop1.setName(name); + prop1.setType(type); + return prop1; + } + + protected GraphVertex createBasicContainerGraphVertex() { + GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); + resource.addMetadataProperty(GraphPropertyEnum.NAME, CONTAINER_NAME); + resource.setJsonMetadataField(JsonPresentationFields.NAME, CONTAINER_NAME); + resource.setJsonMetadataField(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + return resource; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/NodeTypeInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/NodeTypeInfoTest.java deleted file mode 100644 index d6d39ae825..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/NodeTypeInfoTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.openecomp.sdc.be.model; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; - - -public class NodeTypeInfoTest { - - private NodeTypeInfo createTestSubject() { - return new NodeTypeInfo(); - } - - - @Test - public void testGetUnmarkedCopy() throws Exception { - NodeTypeInfo testSubject; - NodeTypeInfo result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getUnmarkedCopy(); - } - - - @Test - public void testGetType() throws Exception { - NodeTypeInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getType(); - } - - - @Test - public void testSetType() throws Exception { - NodeTypeInfo testSubject; - String type = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setType(type); - } - - - @Test - public void testGetTemplateFileName() throws Exception { - NodeTypeInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getTemplateFileName(); - } - - - @Test - public void testSetTemplateFileName() throws Exception { - NodeTypeInfo testSubject; - String templateFileName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setTemplateFileName(templateFileName); - } - - - @Test - public void testGetDerivedFrom() throws Exception { - NodeTypeInfo testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedFrom(); - } - - - @Test - public void testSetDerivedFrom() throws Exception { - NodeTypeInfo testSubject; - List derivedFrom = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedFrom(derivedFrom); - } - - - @Test - public void testIsNested() throws Exception { - NodeTypeInfo testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isNested(); - } - - - @Test - public void testSetNested() throws Exception { - NodeTypeInfo testSubject; - boolean isNested = false; - - // default test - testSubject = createTestSubject(); - testSubject.setNested(isNested); - } - - - @Test - public void testGetMappedToscaTemplate() throws Exception { - NodeTypeInfo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMappedToscaTemplate(); - } - - - @Test - public void testSetMappedToscaTemplate() throws Exception { - NodeTypeInfo testSubject; - Map mappedToscaTemplate = null; - - // default test - testSubject = createTestSubject(); - testSubject.setMappedToscaTemplate(mappedToscaTemplate); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfoTest.java index cec44b402e..eeb1213504 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfoTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfoTest.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.model; -import java.util.Map; - import org.junit.Test; +import java.util.Map; + public class ParsedToscaYamlInfoTest { private ParsedToscaYamlInfo createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyDefinitionTest.java index c7a21b844a..f518f414b2 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyDefinitionTest.java @@ -1,11 +1,11 @@ package org.openecomp.sdc.be.model; -import java.util.HashMap; -import java.util.LinkedList; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import java.util.HashMap; +import java.util.LinkedList; + public class PolicyDefinitionTest { private PolicyDefinition createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTargetDTOTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTargetDTOTest.java index 9559a230ca..5e32fa124a 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTargetDTOTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTargetDTOTest.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; +import java.util.List; + public class PolicyTargetDTOTest { private PolicyTargetDTO createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTypeDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTypeDefinitionTest.java index 3f57ecf281..265b88b06c 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTypeDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PolicyTypeDefinitionTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; +import java.util.List; + public class PolicyTypeDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ProductTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ProductTest.java index 021e044f34..edde844c97 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ProductTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ProductTest.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.model; -import java.util.List; - import org.junit.Test; +import java.util.List; + public class ProductTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PropertyDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PropertyDefinitionTest.java index 5a8888b8b0..2cd8d376f6 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/PropertyDefinitionTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/PropertyDefinitionTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import java.util.LinkedList; +import java.util.List; + public class PropertyDefinitionTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementImplDefTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementImplDefTest.java deleted file mode 100644 index 58bccbefda..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementImplDefTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.openecomp.sdc.be.model; - -import java.util.Map; - -import org.junit.Test; - - -public class RequirementImplDefTest { - - private RequirementImplDef createTestSubject() { - return new RequirementImplDef(); - } - - - @Test - public void testGetNodeId() throws Exception { - RequirementImplDef testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNodeId(); - } - - - @Test - public void testSetNodeId() throws Exception { - RequirementImplDef testSubject; - String nodeId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNodeId(nodeId); - } - - - @Test - public void testGetUniqueId() throws Exception { - RequirementImplDef testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getUniqueId(); - } - - - @Test - public void testSetUniqueId() throws Exception { - RequirementImplDef testSubject; - String uniqueId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setUniqueId(uniqueId); - } - - - @Test - public void testGetRequirementProperties() throws Exception { - RequirementImplDef testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRequirementProperties(); - } - - - @Test - public void testSetRequirementProperties() throws Exception { - RequirementImplDef testSubject; - Map requirementProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRequirementProperties(requirementProperties); - } - - - @Test - public void testGetPoint() throws Exception { - RequirementImplDef testSubject; - Point result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getPoint(); - } - - - @Test - public void testSetPoint() throws Exception { - RequirementImplDef testSubject; - Point point = null; - - // default test - testSubject = createTestSubject(); - testSubject.setPoint(point); - } - - - @Test - public void testToString() throws Exception { - RequirementImplDef testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementInstanceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementInstanceTest.java deleted file mode 100644 index 83472b0db5..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/RequirementInstanceTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.openecomp.sdc.be.model; - -import org.junit.Test; - - -public class RequirementInstanceTest { - - private RequirementInstance createTestSubject() { - return new RequirementInstance(); - } - - - @Test - public void testGetNode() throws Exception { - RequirementInstance testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNode(); - } - - - @Test - public void testSetNode() throws Exception { - RequirementInstance testSubject; - String node = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNode(node); - } - - - @Test - public void testGetRelationship() throws Exception { - RequirementInstance testSubject; - RelationshipImpl result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRelationship(); - } - - - @Test - public void testSetRelationship() throws Exception { - RequirementInstance testSubject; - RelationshipImpl relationship = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRelationship(relationship); - } - - - @Test - public void testToString() throws Exception { - RequirementInstance testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java index 53ddbb3f58..cf4ee08043 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java @@ -1,16 +1,15 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import mockit.Deencapsulation; import org.junit.Assert; import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; -import mockit.Deencapsulation; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; public class ResourceTest extends ModelConfDependentTest{ @@ -20,7 +19,7 @@ public class ResourceTest extends ModelConfDependentTest{ @Test public void testCtor() throws Exception { - ComponentMetadataDefinition componentMetadataDefinition = new ComponentMetadataDefinition(); + ComponentMetadataDefinition componentMetadataDefinition = new ResourceMetadataDefinition(); new Resource(componentMetadataDefinition); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java index 7dafe7d1dc..d8f2840cde 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ServiceTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import java.util.Map; + public class ServiceTest { private Service createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/TargetCapabilityRelDefTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/TargetCapabilityRelDefTest.java index ab610116f1..8978ce735e 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/TargetCapabilityRelDefTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/TargetCapabilityRelDefTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; +import org.junit.Test; + import java.util.LinkedList; import java.util.List; -import org.junit.Test; - public class TargetCapabilityRelDefTest { private TargetCapabilityRelDef createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadCapInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadCapInfoTest.java deleted file mode 100644 index 92075ba128..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadCapInfoTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.openecomp.sdc.be.model; - -import java.util.List; - -import org.junit.Test; - - -public class UploadCapInfoTest { - - private UploadCapInfo createTestSubject() { - return new UploadCapInfo(); - } - - - @Test - public void testGetNode() throws Exception { - UploadCapInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNode(); - } - - - @Test - public void testSetNode() throws Exception { - UploadCapInfo testSubject; - String node = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNode(node); - } - - - @Test - public void testGetValidSourceTypes() throws Exception { - UploadCapInfo testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValidSourceTypes(); - } - - - @Test - public void testSetValidSourceTypes() throws Exception { - UploadCapInfo testSubject; - List validSourceTypes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setValidSourceTypes(validSourceTypes); - } - - - @Test - public void testGetProperties() throws Exception { - UploadCapInfo testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProperties(); - } - - - @Test - public void testSetProperties() throws Exception { - UploadCapInfo testSubject; - List properties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setProperties(properties); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfoTest.java index f23e04bfec..484681e35b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfoTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfoTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model; +import org.junit.Test; + import java.util.List; import java.util.Map; -import org.junit.Test; - public class UploadComponentInstanceInfoTest { private UploadComponentInstanceInfo createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadPropInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadPropInfoTest.java deleted file mode 100644 index 9cc0d1c3d9..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadPropInfoTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.openecomp.sdc.be.model; - -import java.util.List; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; - - -public class UploadPropInfoTest { - - private UploadPropInfo createTestSubject() { - return new UploadPropInfo(); - } - - - @Test - public void testGetGet_input() throws Exception { - UploadPropInfo testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGet_input(); - } - - - @Test - public void testSetGet_input() throws Exception { - UploadPropInfo testSubject; - List get_input = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGet_input(get_input); - } - - - @Test - public void testGetValue() throws Exception { - UploadPropInfo testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(); - } - - - @Test - public void testSetValue() throws Exception { - UploadPropInfo testSubject; - Object value = null; - - // default test - testSubject = createTestSubject(); - testSubject.setValue(value); - } - - - @Test - public void testGetDescription() throws Exception { - UploadPropInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDescription(); - } - - - @Test - public void testSetDescription() throws Exception { - UploadPropInfo testSubject; - String description = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDescription(description); - } - - - @Test - public void testIsPassword() throws Exception { - UploadPropInfo testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isPassword(); - } - - - @Test - public void testSetPassword() throws Exception { - UploadPropInfo testSubject; - boolean password = false; - - // default test - testSubject = createTestSubject(); - testSubject.setPassword(password); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadReqInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadReqInfoTest.java deleted file mode 100644 index 9aebec85fe..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadReqInfoTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.openecomp.sdc.be.model; - -import org.junit.Test; - - -public class UploadReqInfoTest { - - private UploadReqInfo createTestSubject() { - return new UploadReqInfo(); - } - - - @Test - public void testGetCapabilityName() throws Exception { - UploadReqInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabilityName(); - } - - - @Test - public void testSetCapabilityName() throws Exception { - UploadReqInfo testSubject; - String capabilityName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabilityName(capabilityName); - } - - - @Test - public void testGetNode() throws Exception { - UploadReqInfo testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNode(); - } - - - @Test - public void testSetNode() throws Exception { - UploadReqInfo testSubject; - String node = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNode(node); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadResourceInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadResourceInfoTest.java index a3c2e84ce8..f4601d2029 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadResourceInfoTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/UploadResourceInfoTest.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be.model; -import java.util.LinkedList; -import java.util.List; - import org.junit.Assert; import org.junit.Test; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.common.api.UploadArtifactInfo; +import java.util.LinkedList; +import java.util.List; + public class UploadResourceInfoTest { private UploadResourceInfo createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java index 8e5cb5be73..48681867f9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java @@ -1,10 +1,7 @@ package org.openecomp.sdc.be.model.cache; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; +import mockit.Deencapsulation; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Test; @@ -18,8 +15,10 @@ import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.resources.data.DataTypeData; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; -import fj.data.Either; -import mockit.Deencapsulation; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java index f9a696bf8d..49e847acf6 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java @@ -1,15 +1,7 @@ package org.openecomp.sdc.be.model.cache; -import java.nio.ByteBuffer; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - +import fj.data.Either; +import mockit.Deencapsulation; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.junit.Assert; @@ -31,654 +23,511 @@ import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ComponentCacheData; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; -import org.openecomp.sdc.common.util.SerializationUtils; -import org.openecomp.sdc.common.util.ZipUtil; -import fj.data.Either; -import mockit.Deencapsulation; +import java.util.*; +import java.util.function.Function; public class ComponentCacheTest extends ModelConfDependentTest { - @InjectMocks - ComponentCache testSubject; - - @Mock - ComponentCassandraDao componentCassandraDao; + @InjectMocks + ComponentCache testSubject; + + @Mock + ComponentCassandraDao componentCassandraDao; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + @Before + public void setUpMocks() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testInit() throws Exception { + // default test + testSubject.init(); + } + + @Test + public void testIsEnabled() throws Exception { + + boolean result; + + // default test + + result = testSubject.isEnabled(); + } + + @Test + public void testSetEnabled() throws Exception { + + boolean enabled = false; + + // default test + + testSubject.setEnabled(enabled); + } + + @Test + public void testGetComponentNotFound() throws Exception { + + String componentUid = "mock"; + Long lastModificationTime = null; + Function filterFieldsFunc = null; + Either result; + + Mockito.when(componentCassandraDao.getComponent("mock")) + .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); + // default test + result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); + } + + @Test + public void testGetComponentInvalidDate() throws Exception { + + String componentUid = "mock"; + Long lastModificationTime = 0L; + Function filterFieldsFunc = null; + Either result; + + ComponentCacheData a = new ComponentCacheData(); + a.setModificationTime(new Date()); + Mockito.when(componentCassandraDao.getComponent("mock")).thenReturn(Either.left(a)); + // default test + result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); + } + + @Test + public void testGetComponentDeserializeError() throws Exception { + + String componentUid = "mock"; + Long lastModificationTime = 0L; + Function filterFieldsFunc = null; + Either result; + + ComponentCacheData a = new ComponentCacheData(); + a.setModificationTime(new Date(0L)); + a.setType(NodeTypeEnum.Resource.getName()); + Mockito.when(componentCassandraDao.getComponent("mock")).thenReturn(Either.left(a)); + // default test + result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); + } + + @Test + public void testGetAllComponentIdTimeAndType() throws Exception { + + Either, ActionStatus> result; + + // default test + + result = testSubject.getAllComponentIdTimeAndType(); + testSubject.setEnabled(false); + result = testSubject.getAllComponentIdTimeAndType(); + } + + @Test + public void testUpdateCatalogInMemoryCacheWithCertified() throws Exception { + + List foundComponents = new LinkedList<>(); - @Mock - ToscaOperationFacade toscaOperationFacade; + // default test + testSubject.init(); + Deencapsulation.invoke(testSubject, "updateCatalogInMemoryCacheWithCertified", foundComponents, + ComponentTypeEnum.RESOURCE); + } - @Before - public void setUpMocks() throws Exception { - MockitoAnnotations.initMocks(this); - } + @Test + public void testGetDataFromInMemoryCache() throws Exception { - @Test - public void testInit() throws Exception { - // default test - testSubject.init(); - } + Set components = new HashSet<>(); + components.add("mock"); + ComponentTypeEnum componentTypeEnum = null; + List result; - @Test - public void testIsEnabled() throws Exception { + // default test + testSubject.init(); + result = Deencapsulation.invoke(testSubject, "getDataFromInMemoryCache", components, + ComponentTypeEnum.RESOURCE); + } - boolean result; + @Test + public void testGetComponents() throws Exception { - // default test + Set components = new HashSet<>(); + Function, List> filterFieldsFunc = new Function, List>() { - result = testSubject.isEnabled(); - } + @Override + public List apply(List t) { + return t; + } + }; + Either, List, Set>, ActionStatus> result; - @Test - public void testSetEnabled() throws Exception { + List list = new LinkedList<>(); + Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(list)); + + // default test + testSubject.init(); + result = testSubject.getComponents(components, filterFieldsFunc); + } + + @Test + public void testGetComponentsNotAllowed() throws Exception { + + Set components = new HashSet<>(); + Function, List> filterFieldsFunc = null; + + Either, List, Set>, ActionStatus> result; + + // default test + testSubject.setEnabled(false); + result = testSubject.getComponents(components, filterFieldsFunc); + } + + @Test + public void testGetComponentsCassndraError() throws Exception { + + Set components = new HashSet<>(); + Function, List> filterFieldsFunc = null; + Either, List, Set>, ActionStatus> result; + + Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))) + .thenReturn(Either.right(ActionStatus.GENERAL_ERROR)); - boolean enabled = false; + // default test + testSubject.init(); + result = testSubject.getComponents(components, filterFieldsFunc); + } - // default test + @Test + public void testGetComponentsForLeftPanel() throws Exception { - testSubject.setEnabled(enabled); - } + ComponentTypeEnum componentTypeEnum = null; + String internalComponentType = "mock"; + Set filteredResources = new HashSet<>(); + Either, List, Set>, ActionStatus> result; - @Test - public void testGetComponentNotFound() throws Exception { + List list = new LinkedList<>(); + Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(list)); - String componentUid = "mock"; - Long lastModificationTime = null; - Function filterFieldsFunc = null; - Either result; + // default test + result = testSubject.getComponentsForLeftPanel(ComponentTypeEnum.RESOURCE, internalComponentType, + filteredResources); + } - Mockito.when(componentCassandraDao.getComponent("mock")) - .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); - // default test - result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); - } + @Test + public void testFilterForLeftPanel() throws Exception { - @Test - public void testGetComponentInvalidDate() throws Exception { + List components = new LinkedList<>(); + List result; - String componentUid = "mock"; - Long lastModificationTime = 0L; - Function filterFieldsFunc = null; - Either result; + // test 1 - ComponentCacheData a = new ComponentCacheData(); - a.setModificationTime(new Date()); - Mockito.when(componentCassandraDao.getComponent("mock")).thenReturn(Either.left(a)); - // default test - result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); - } + result = Deencapsulation.invoke(testSubject, "filterForLeftPanel", components); + Assert.assertNotEquals(null, result); + } - @Test - public void testGetComponentDeserializeError() throws Exception { + @Test + public void testFilterForCatalog() throws Exception { - String componentUid = "mock"; - Long lastModificationTime = 0L; - Function filterFieldsFunc = null; - Either result; + List components = new LinkedList<>(); + List result; - ComponentCacheData a = new ComponentCacheData(); - a.setModificationTime(new Date(0L)); - a.setType(NodeTypeEnum.Resource.getName()); - Mockito.when(componentCassandraDao.getComponent("mock")).thenReturn(Either.left(a)); - // default test - result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); - } + // test 1 + result = Deencapsulation.invoke(testSubject, "filterForCatalog", components); + Assert.assertNotEquals(null, result); + } - @Test - public void testGetComponent() throws Exception { + @Test + public void testFilterFieldsForLeftPanel() throws Exception { + Component result; - String componentUid = "mock"; - Long lastModificationTime = 0L; - Function filterFieldsFunc = null; - Either result; + // default test + Resource resource = new Resource(); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + result = Deencapsulation.invoke(testSubject, "filterFieldsForLeftPanel", resource); + Service service = new Service(); + service.setComponentType(ComponentTypeEnum.SERVICE); + result = Deencapsulation.invoke(testSubject, "filterFieldsForLeftPanel", service); + } - ComponentCacheData a = new ComponentCacheData(); - a.setModificationTime(new Date(0L)); - a.setType(NodeTypeEnum.Resource.getName()); - Resource resource = new Resource(); - Either serialize = SerializationUtils.serializeExt(resource); - byte[] value = serialize.left().value(); - a.setData(ByteBuffer.wrap(value)); - Mockito.when(componentCassandraDao.getComponent("mock")).thenReturn(Either.left(a)); - // default test - result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); - } + @Test + public void testFilterFieldsForCatalog() throws Exception { + Component result; - @Test - public void testGetAllComponentIdTimeAndType() throws Exception { + // default test - Either, ActionStatus> result; + Resource resource = new Resource(); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", resource); + Service service = new Service(); + service.setComponentType(ComponentTypeEnum.SERVICE); + result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", service); + Product product = new Product(); + product.setComponentType(ComponentTypeEnum.PRODUCT); + result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", product); + } - // default test + @Test + public void testCopyFieldsForLeftPanel() throws Exception { - result = testSubject.getAllComponentIdTimeAndType(); - testSubject.setEnabled(false); - result = testSubject.getAllComponentIdTimeAndType(); - } + Component component = new Resource(); + Component filteredComponent = new Resource(); + ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) + .setResourceType(ResourceTypeEnum.VL); + // default test - @Test - public void testUpdateCatalogInMemoryCacheWithCertified() throws Exception { + Deencapsulation.invoke(testSubject, "copyFieldsForLeftPanel", component, filteredComponent); + } - List foundComponents = new LinkedList<>(); + @Test + public void testGetComponentsFullDisabled() throws Exception { - // default test - testSubject.init(); - Deencapsulation.invoke(testSubject, "updateCatalogInMemoryCacheWithCertified", foundComponents, - ComponentTypeEnum.RESOURCE); - } + Set filteredResources = null; + Either, List, Set>, ActionStatus> result; - @Test - public void testGetDataFromInMemoryCache() throws Exception { + // default test + testSubject.setEnabled(false); + result = Deencapsulation.invoke(testSubject, "getComponentsFull", Set.class); + } - Set components = new HashSet<>(); - components.add("mock"); - ComponentTypeEnum componentTypeEnum = null; - List result; - - // default test - testSubject.init(); - result = Deencapsulation.invoke(testSubject, "getDataFromInMemoryCache", components, - ComponentTypeEnum.RESOURCE); - } - - @Test - public void testGetComponents() throws Exception { - - Set components = new HashSet<>(); - Function, List> filterFieldsFunc = new Function, List>() { - - @Override - public List apply(List t) { - return t; - } - }; - Either, List, Set>, ActionStatus> result; - - List list = new LinkedList<>(); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(list)); - - // default test - testSubject.init(); - result = testSubject.getComponents(components, filterFieldsFunc); - } - - @Test - public void testGetComponentsNotAllowed() throws Exception { - - Set components = new HashSet<>(); - Function, List> filterFieldsFunc = null; - Either, List, Set>, ActionStatus> result; - - // default test - testSubject.setEnabled(false); - result = testSubject.getComponents(components, filterFieldsFunc); - } + @Test + public void testGetComponentsFullDesirializeError() throws Exception { - @Test - public void testGetComponentsCassndraError() throws Exception { + Set filteredResources = new HashSet<>(); + filteredResources.add("mock"); + Either, List, Set>, ActionStatus> result; - Set components = new HashSet<>(); - Function, List> filterFieldsFunc = null; - Either, List, Set>, ActionStatus> result; + List a = new LinkedList<>(); + ComponentCacheData e = new ComponentCacheData(); + e.setId("mock"); + e.setType(NodeTypeEnum.Resource.getName()); + a.add(e); + Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(a)); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))) - .thenReturn(Either.right(ActionStatus.GENERAL_ERROR)); - - // default test - testSubject.init(); - result = testSubject.getComponents(components, filterFieldsFunc); - } - - @Test - public void testGetComponentsForLeftPanel() throws Exception { - - ComponentTypeEnum componentTypeEnum = null; - String internalComponentType = "mock"; - Set filteredResources = new HashSet<>(); - Either, List, Set>, ActionStatus> result; + // default test - List list = new LinkedList<>(); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(list)); + result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); + } - // default test - result = testSubject.getComponentsForLeftPanel(ComponentTypeEnum.RESOURCE, internalComponentType, - filteredResources); - } - @Test - public void testFilterForLeftPanel() throws Exception { + @Test + public void testGetComponent_1() throws Exception { - List components = new LinkedList<>(); - List result; + String componentUid = "mock"; + Either result; - // test 1 + Mockito.when(componentCassandraDao.getComponent("mock")) + .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); - result = Deencapsulation.invoke(testSubject, "filterForLeftPanel", components); - Assert.assertNotEquals(null, result); - } + // default test + result = testSubject.getComponent(componentUid); + } - @Test - public void testFilterForCatalog() throws Exception { + @Test + public void testGetComponent_2() throws Exception { - List components = new LinkedList<>(); - List result; + String componentUid = "mock"; + Long lastModificationTime = null; + Either result; - // test 1 - result = Deencapsulation.invoke(testSubject, "filterForCatalog", components); - Assert.assertNotEquals(null, result); - } + Mockito.when(componentCassandraDao.getComponent("mock")) + .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); - @Test - public void testFilterFieldsForLeftPanel() throws Exception { - Component result; + // default test + Function filterFieldsFunc = new Function() { + @Override + public Component apply(Component component) { + return new Resource(); + } + }; + result = testSubject.getComponent(componentUid, lastModificationTime, filterFieldsFunc); + } - // default test - result = Deencapsulation.invoke(testSubject, "filterFieldsForLeftPanel", new Resource()); - result = Deencapsulation.invoke(testSubject, "filterFieldsForLeftPanel", new Service()); - } + @Test + public void testSaveComponent() throws Exception { - @Test - public void testFilterFieldsForCatalog() throws Exception { - Component result; + String componentUid = ""; + Component component = new Resource(); + boolean result; - // default test - result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", new Resource()); - result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", new Service()); - result = Deencapsulation.invoke(testSubject, "filterFieldsForCatalog", new Product()); - } + // default test + Mockito.when(componentCassandraDao.saveComponent(Mockito.any(ComponentCacheData.class))) + .thenReturn(CassandraOperationStatus.OK); - @Test - public void testCopyFieldsForLeftPanel() throws Exception { + result = Deencapsulation.invoke(testSubject, "saveComponent", componentUid, 0L, NodeTypeEnum.Resource, + component); + } - Component component = new Resource(); - Component filteredComponent = new Resource(); - ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) - .setResourceType(ResourceTypeEnum.VL); - // default test + @Test + public void testSetComponent_1Disabled() throws Exception { - Deencapsulation.invoke(testSubject, "copyFieldsForLeftPanel", component, filteredComponent); - } + Component component = new Resource(); + component.setLastUpdateDate(0L); + boolean result; - @Test - public void testGetComponentsFullDisabled() throws Exception { + // default test + testSubject.setEnabled(false); + result = testSubject.setComponent(component, NodeTypeEnum.Resource); + } - Set filteredResources = null; - Either, List, Set>, ActionStatus> result; + @Test + public void testSetComponent_1() throws Exception { - // default test - testSubject.setEnabled(false); - result = Deencapsulation.invoke(testSubject, "getComponentsFull", Set.class); - } + Component component = new Resource(); + component.setLastUpdateDate(0L); + boolean result; - @Test - public void testGetComponentsFull() throws Exception { + // default test - Set filteredResources = new HashSet<>(); - filteredResources.add("mock"); - Either, List, Set>, ActionStatus> result; + result = testSubject.setComponent(component, NodeTypeEnum.Resource); + } - List a = new LinkedList<>(); - ComponentCacheData e = new ComponentCacheData(); - e.setId("mock"); - e.setType(NodeTypeEnum.Resource.getName()); - Resource resource = new Resource(); - Either serialize = SerializationUtils.serializeExt(resource); - byte[] value = serialize.left().value(); - e.setData(ByteBuffer.wrap(value)); - a.add(e); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(a)); - // default test + @Test + public void testGetComponentsFull_1CannotDeserialize() throws Exception { + Map filteredResources = new HashMap<>(); + Either, Set>, ActionStatus> result; - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } + // default test + LinkedList left = new LinkedList<>(); + ComponentCacheData e = new ComponentCacheData(); + e.setType(NodeTypeEnum.Resource.getName()); + left.add(e); + ImmutablePair, Set> immutablePair = ImmutablePair.of(left, new HashSet<>()); + Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.left(immutablePair)); - @Test - public void testGetComponentsFullDesirializeError() throws Exception { + result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); + } - Set filteredResources = new HashSet<>(); - filteredResources.add("mock"); - Either, List, Set>, ActionStatus> result; + @Test + public void testGetComponentsFull_1Disabled() throws Exception { + Map filteredResources = new HashMap<>(); + Either, Set>, ActionStatus> result; - List a = new LinkedList<>(); - ComponentCacheData e = new ComponentCacheData(); - e.setId("mock"); - e.setType(NodeTypeEnum.Resource.getName()); - a.add(e); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(List.class))).thenReturn(Either.left(a)); + // default test + testSubject.setEnabled(false); + result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); + } - // default test + @Test + public void testGetComponentsFull_1NotFound() throws Exception { + Map filteredResources = new HashMap<>(); + Either, Set>, ActionStatus> result; - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } + // default test + Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); - @Test - public void testConvertComponentCacheToComponentServiceZipped() throws Exception { + result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); + } - ComponentCacheData componentCacheData = new ComponentCacheData(); - Either result; + @Test + public void testGetComponentsForCatalog_1Disabled() throws Exception { - componentCacheData.setId("mock"); - componentCacheData.setType(NodeTypeEnum.Service.getName()); - componentCacheData.setIsZipped(true); - Service service = new Service(); - Either serialize = SerializationUtils.serializeExt(service); - byte[] value = serialize.left().value(); + Map components = null; + Either, Set>, ActionStatus> result; - componentCacheData.setData(ByteBuffer.wrap(ZipUtil.zipBytes(value))); + // default test + testSubject.setEnabled(false); + result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); + } - // default test + @Test + public void testGetComponentsForCatalog_1() throws Exception { + Map components = new HashMap<>(); + Either, Set>, ActionStatus> result; - result = Deencapsulation.invoke(testSubject, "convertComponentCacheToComponent", componentCacheData); - } + // default test + ImmutablePair, Set> value = ImmutablePair.of(new LinkedList<>(), new HashSet<>()); + Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.left(value)); + testSubject.init(); + result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); + } - @Test - public void testConvertComponentCacheToComponentProductZipped() throws Exception { + @Test + public void testGetComponentsForCatalog_1Error() throws Exception { + Map components = new HashMap<>(); + Either, Set>, ActionStatus> result; - ComponentCacheData componentCacheData = new ComponentCacheData(); - Either result; + // default test + Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.right(ActionStatus.COMPONENT_NOT_FOUND)); - componentCacheData.setId("mock"); - componentCacheData.setType(NodeTypeEnum.Product.getName()); - componentCacheData.setIsZipped(true); - Product product = new Product(); - Either serialize = SerializationUtils.serializeExt(product); - byte[] value = serialize.left().value(); + result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); + } - componentCacheData.setData(ByteBuffer.wrap(ZipUtil.zipBytes(value))); + @Test + public void testGetComponents_1Disabled() throws Exception { - // default test + Map components = null; + Function, List> filterFieldsFunc = null; + Either, Set>, ActionStatus> result; - result = Deencapsulation.invoke(testSubject, "convertComponentCacheToComponent", componentCacheData); - } + // default test + testSubject.setEnabled(false); + result = testSubject.getComponents(components, filterFieldsFunc); + } - @Test - public void testGetComponent_1() throws Exception { + @Test + public void testGetComponentAndTimeNotFound() throws Exception { - String componentUid = "mock"; - Either result; + String componentUid = ""; + Function filterFieldsFunc = null; + Either, ActionStatus> result; - Mockito.when(componentCassandraDao.getComponent("mock")) - .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); + // default test + Mockito.when(componentCassandraDao.getComponent(Mockito.anyString())).thenReturn(Either.right(ActionStatus.API_RESOURCE_NOT_FOUND)); - // default test - result = testSubject.getComponent(componentUid); - } + result = testSubject.getComponentAndTime(componentUid, filterFieldsFunc); + } - @Test - public void testGetComponent_2() throws Exception { + @Test + public void testGetComponentFromCacheDisabled() throws Exception { + String componentUid = ""; + Long lastModificationTime = null; + Function filterFieldsFunc = null; + Either, ActionStatus> result; + + // test 1 + lastModificationTime = null; + testSubject.setEnabled(false); + result = Deencapsulation.invoke(testSubject, "getComponentFromCache", + new Object[]{componentUid, Long.class, Function.class}); + } - String componentUid = "mock"; - Long lastModificationTime = null; - Either result; + @Test + public void testDeleteComponentFromCacheFails() throws Exception { - Mockito.when(componentCassandraDao.getComponent("mock")) - .thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); + String id = ""; + ActionStatus result; - // default test + // default test - result = testSubject.getComponent(componentUid, lastModificationTime); - } + result = testSubject.deleteComponentFromCache(id); + } - @Test - public void testSetComponentDisabled() throws Exception { + @Test + public void testDeleteComponentFromCacheDisabled() throws Exception { - String componentUid = ""; - Long lastModificationTime = null; - NodeTypeEnum nodeTypeEnum = null; - boolean result; + String id = ""; + ActionStatus result; - // default test - testSubject.setEnabled(false); - result = testSubject.setComponent(componentUid, lastModificationTime, nodeTypeEnum); - } + // default test + testSubject.setEnabled(false); + result = testSubject.deleteComponentFromCache(id); + } - @Test - public void testSetComponentNotFound() throws Exception { + @Test + public void testDeleteComponentFromCache() throws Exception { - String componentUid = ""; - Long lastModificationTime = null; - boolean result; + String id = ""; + ActionStatus result; - // default test - Mockito.when(toscaOperationFacade.getToscaElement(componentUid)) - .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - - result = testSubject.setComponent(componentUid, lastModificationTime, NodeTypeEnum.Resource); - } - - @Test - public void testSetComponent() throws Exception { - - String componentUid = ""; - Long lastModificationTime = 0L; - boolean result; - - // default test - Mockito.when(toscaOperationFacade.getToscaElement(componentUid)).thenReturn(Either.left(new Resource())); - - result = testSubject.setComponent(componentUid, lastModificationTime, NodeTypeEnum.Resource); - } - - @Test - public void testSaveComponent() throws Exception { - - String componentUid = ""; - Component component = new Resource(); - boolean result; - - // default test - Mockito.when(componentCassandraDao.saveComponent(Mockito.any(ComponentCacheData.class))) - .thenReturn(CassandraOperationStatus.OK); - - result = Deencapsulation.invoke(testSubject, "saveComponent", componentUid, 0L, NodeTypeEnum.Resource, - component); - } - - @Test - public void testSetComponent_1Disabled() throws Exception { - - Component component = new Resource(); - component.setLastUpdateDate(0L); - boolean result; - - // default test - testSubject.setEnabled(false); - result = testSubject.setComponent(component, NodeTypeEnum.Resource); - } - - @Test - public void testSetComponent_1() throws Exception { - - Component component = new Resource(); - component.setLastUpdateDate(0L); - boolean result; - - // default test - - result = testSubject.setComponent(component, NodeTypeEnum.Resource); - } - - @Test - public void testGetComponentsFull_1() throws Exception { - Map filteredResources = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - LinkedList left = new LinkedList<>(); - ComponentCacheData e = new ComponentCacheData(); - Either serializeExt = SerializationUtils.serializeExt(new Resource()); - e.setData(ByteBuffer.wrap(serializeExt.left().value())); - e.setType(NodeTypeEnum.Resource.getName()); - left.add(e); - ImmutablePair, Set> immutablePair = ImmutablePair.of(left, new HashSet<>()); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.left(immutablePair)); - - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } - - @Test - public void testGetComponentsFull_1CannotDeserialize() throws Exception { - Map filteredResources = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - LinkedList left = new LinkedList<>(); - ComponentCacheData e = new ComponentCacheData(); - e.setType(NodeTypeEnum.Resource.getName()); - left.add(e); - ImmutablePair, Set> immutablePair = ImmutablePair.of(left, new HashSet<>()); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.left(immutablePair)); - - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } - - @Test - public void testGetComponentsFull_1Disabled() throws Exception { - Map filteredResources = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - testSubject.setEnabled(false); - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } - - @Test - public void testGetComponentsFull_1NotFound() throws Exception { - Map filteredResources = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.right(ActionStatus.ARTIFACT_NOT_FOUND)); - - result = Deencapsulation.invoke(testSubject, "getComponentsFull", filteredResources); - } - - @Test - public void testGetComponentsForCatalog_1Disabled() throws Exception { - - Map components = null; - Either, Set>, ActionStatus> result; - - // default test - testSubject.setEnabled(false); - result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); - } - - @Test - public void testGetComponentsForCatalog_1() throws Exception { - Map components = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - ImmutablePair, Set> value = ImmutablePair.of(new LinkedList<>(), new HashSet<>()); - Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.left(value)); - testSubject.init(); - result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); - } - - @Test - public void testGetComponentsForCatalog_1Error() throws Exception { - Map components = new HashMap<>(); - Either, Set>, ActionStatus> result; - - // default test - Mockito.when(componentCassandraDao.getComponents(Mockito.any(Map.class))).thenReturn(Either.right(ActionStatus.COMPONENT_NOT_FOUND)); - - result = testSubject.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); - } - - @Test - public void testGetComponents_1Disabled() throws Exception { - - Map components = null; - Function, List> filterFieldsFunc = null; - Either, Set>, ActionStatus> result; - - // default test - testSubject.setEnabled(false); - result = testSubject.getComponents(components, filterFieldsFunc); - } - - @Test - public void testGetComponentAndTime() throws Exception { - - String componentUid = ""; - Function filterFieldsFunc = null; - Either, ActionStatus> result; - - // default test - ComponentCacheData a = new ComponentCacheData(); - a.setModificationTime(new Date()); - a.setType(NodeTypeEnum.Resource.getName()); - Either serializeExt = SerializationUtils.serializeExt(new Resource()); - a.setData(ByteBuffer.wrap(serializeExt.left().value())); - Mockito.when(componentCassandraDao.getComponent(Mockito.anyString())).thenReturn(Either.left(a)); - - result = testSubject.getComponentAndTime(componentUid, filterFieldsFunc); - } - - @Test - public void testGetComponentAndTimeNotFound() throws Exception { - - String componentUid = ""; - Function filterFieldsFunc = null; - Either, ActionStatus> result; - - // default test - Mockito.when(componentCassandraDao.getComponent(Mockito.anyString())).thenReturn(Either.right(ActionStatus.API_RESOURCE_NOT_FOUND)); - - result = testSubject.getComponentAndTime(componentUid, filterFieldsFunc); - } - - @Test - public void testGetComponentFromCacheDisabled() throws Exception { - String componentUid = ""; - Long lastModificationTime = null; - Function filterFieldsFunc = null; - Either, ActionStatus> result; - - // test 1 - lastModificationTime = null; - testSubject.setEnabled(false); - result = Deencapsulation.invoke(testSubject, "getComponentFromCache", - new Object[] { componentUid, Long.class, Function.class }); - } - - @Test - public void testDeleteComponentFromCacheFails() throws Exception { - - String id = ""; - ActionStatus result; - - // default test - - result = testSubject.deleteComponentFromCache(id); - } - - @Test - public void testDeleteComponentFromCacheDisabled() throws Exception { - - String id = ""; - ActionStatus result; - - // default test - testSubject.setEnabled(false); - result = testSubject.deleteComponentFromCache(id); - } - - @Test - public void testDeleteComponentFromCache() throws Exception { - - String id = ""; - ActionStatus result; - - // default test - Mockito.when(componentCassandraDao.deleteComponent(Mockito.anyString())).thenReturn(CassandraOperationStatus.OK); - result = testSubject.deleteComponentFromCache(id); - } + // default test + Mockito.when(componentCassandraDao.deleteComponent(Mockito.anyString())).thenReturn(CassandraOperationStatus.OK); + result = testSubject.deleteComponentFromCache(id); + } } \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java index 148e2377ef..5347bc0d76 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.be.model.cache.jobs; -import java.util.function.Function; - +import fj.data.Either; +import mockit.Deencapsulation; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Test; @@ -19,8 +19,7 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import fj.data.Either; -import mockit.Deencapsulation; +import java.util.function.Function; public class CheckAndUpdateJobTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/CategoryDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/CategoryDefinitionTest.java deleted file mode 100644 index cac17ef798..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/CategoryDefinitionTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.openecomp.sdc.be.model.category; - -import java.util.List; - -import org.junit.Test; - - -public class CategoryDefinitionTest { - - private CategoryDefinition createTestSubject() { - return new CategoryDefinition(); - } - - - @Test - public void testGetSubcategories() throws Exception { - CategoryDefinition testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getSubcategories(); - } - - - @Test - public void testSetSubcategories() throws Exception { - CategoryDefinition testSubject; - List subcategories = null; - - // default test - testSubject = createTestSubject(); - testSubject.setSubcategories(subcategories); - } - - - @Test - public void testAddSubCategory() throws Exception { - CategoryDefinition testSubject; - SubCategoryDefinition subcategory = null; - - // default test - testSubject = createTestSubject(); - testSubject.addSubCategory(subcategory); - } - - - @Test - public void testToString() throws Exception { - CategoryDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/SubCategoryDefinitionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/SubCategoryDefinitionTest.java deleted file mode 100644 index 4349ca24e3..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/category/SubCategoryDefinitionTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.openecomp.sdc.be.model.category; - -import java.util.List; - -import org.junit.Test; - - -public class SubCategoryDefinitionTest { - - private SubCategoryDefinition createTestSubject() { - return new SubCategoryDefinition(); - } - - - @Test - public void testGetGroupings() throws Exception { - SubCategoryDefinition testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGroupings(); - } - - - @Test - public void testSetGroupings() throws Exception { - SubCategoryDefinition testSubject; - List groupingDefinitions = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGroupings(groupingDefinitions); - } - - - @Test - public void testAddGrouping() throws Exception { - SubCategoryDefinition testSubject; - GroupingDefinition groupingDefinition = null; - - // default test - testSubject = createTestSubject(); - testSubject.addGrouping(groupingDefinition); - } - - - @Test - public void testToString() throws Exception { - SubCategoryDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java index 1215b5fc6f..e7210d404d 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan({"org.openecomp.sdc.be.model.jsontitan.operations","org.openecomp.sdc.be.model.jsontitan.utils"}) +@ComponentScan({"org.openecomp.sdc.be.dao.cassandra","org.openecomp.sdc.be.model.cache","org.openecomp.sdc.be.model.jsontitan.operations","org.openecomp.sdc.be.model.jsontitan.utils", "org.openecomp.sdc.be.model.operations.impl"}) public class ModelOperationsSpringConfig { } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java deleted file mode 100644 index aae9d6f2a0..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - - -public class NodeTypeTest { - - private NodeType createTestSubject() { - return new NodeType(); - } - - - @Test - public void testGetDerivedList() throws Exception { - NodeType testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedList(); - } - - - @Test - public void testSetDerivedList() throws Exception { - NodeType testSubject; - List derivedList = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedList(derivedList); - } - - - @Test - public void testGetDerivedFrom() throws Exception { - NodeType testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedFrom(); - } - - - @Test - public void testSetDerivedFrom() throws Exception { - NodeType testSubject; - List derivedFrom = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedFrom(derivedFrom); - } - - - @Test - public void testGetAttributes() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAttributes(); - } - - - @Test - public void testSetAttributes() throws Exception { - NodeType testSubject; - Map attributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAttributes(attributes); - } - - - @Test - public void testGetCapabilties() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabilties(); - } - - - @Test - public void testSetCapabilties() throws Exception { - NodeType testSubject; - Map capabilties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabilties(capabilties); - } - - - @Test - public void testGetRequirements() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRequirements(); - } - - - @Test - public void testSetRequirements() throws Exception { - NodeType testSubject; - Map requirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRequirements(requirements); - } - - - @Test - public void testGetCapabiltiesProperties() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabiltiesProperties(); - } - - - @Test - public void testSetCapabiltiesProperties() throws Exception { - NodeType testSubject; - Map capabiltiesProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabiltiesProperties(capabiltiesProperties); - } - - - @Test - public void testGetInterfaceArtifacts() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInterfaceArtifacts(); - } - - - @Test - public void testSetInterfaceArtifacts() throws Exception { - NodeType testSubject; - Map interfaceArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInterfaceArtifacts(interfaceArtifacts); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java deleted file mode 100644 index 0f1b91807d..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java +++ /dev/null @@ -1,414 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - - -public class TopologyTemplateTest { - - private TopologyTemplate createTestSubject() { - return new TopologyTemplate(); - } - - - @Test - public void testGetInputs() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInputs(); - } - - - @Test - public void testSetInputs() throws Exception { - TopologyTemplate testSubject; - Map inputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInputs(inputs); - } - - - @Test - public void testGetInstInputs() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstInputs(); - } - - - @Test - public void testSetInstInputs() throws Exception { - TopologyTemplate testSubject; - Map instInputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstInputs(instInputs); - } - - - @Test - public void testGetHeatParameters() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getHeatParameters(); - } - - - @Test - public void testSetHeatParameters() throws Exception { - TopologyTemplate testSubject; - Map heatParameters = null; - - // default test - testSubject = createTestSubject(); - testSubject.setHeatParameters(heatParameters); - } - - - @Test - public void testGetInstAttributes() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstAttributes(); - } - - - @Test - public void testSetInstAttributes() throws Exception { - TopologyTemplate testSubject; - Map instAttributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstAttributes(instAttributes); - } - - - @Test - public void testGetInstProperties() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstProperties(); - } - - - @Test - public void testSetInstProperties() throws Exception { - TopologyTemplate testSubject; - Map instProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstProperties(instProperties); - } - - - @Test - public void testGetGroups() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGroups(); - } - - - @Test - public void testSetGroups() throws Exception { - TopologyTemplate testSubject; - Map groups = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGroups(groups); - } - - - @Test - public void testGetInstGroups() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstGroups(); - } - - - @Test - public void testSetInstGroups() throws Exception { - TopologyTemplate testSubject; - Map instGroups = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstGroups(instGroups); - } - - - @Test - public void testGetServiceApiArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceApiArtifacts(); - } - - - @Test - public void testSetServiceApiArtifacts() throws Exception { - TopologyTemplate testSubject; - Map serviceApiArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceApiArtifacts(serviceApiArtifacts); - } - - - @Test - public void testGetCompositions() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCompositions(); - } - - - @Test - public void testSetCompositions() throws Exception { - TopologyTemplate testSubject; - Map compositions = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCompositions(compositions); - } - - - @Test - public void testGetCalculatedCapabilities() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedCapabilities(); - } - - - @Test - public void testSetCalculatedCapabilities() throws Exception { - TopologyTemplate testSubject; - Map calculatedCapabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedCapabilities(calculatedCapabilities); - } - - - @Test - public void testGetCalculatedRequirements() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedRequirements(); - } - - - @Test - public void testSetCalculatedRequirements() throws Exception { - TopologyTemplate testSubject; - Map calculatedRequirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedRequirements(calculatedRequirements); - } - - - @Test - public void testGetFullfilledCapabilities() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getFullfilledCapabilities(); - } - - - @Test - public void testSetFullfilledCapabilities() throws Exception { - TopologyTemplate testSubject; - Map fullfilledCapabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setFullfilledCapabilities(fullfilledCapabilities); - } - - - @Test - public void testGetFullfilledRequirements() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getFullfilledRequirements(); - } - - - @Test - public void testSetFullfilledRequirements() throws Exception { - TopologyTemplate testSubject; - Map fullfilledRequirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setFullfilledRequirements(fullfilledRequirements); - } - - - @Test - public void testGetInstDeploymentArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstDeploymentArtifacts(); - } - - - @Test - public void testSetInstDeploymentArtifacts() throws Exception { - TopologyTemplate testSubject; - Map instDeploymentArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstDeploymentArtifacts(instDeploymentArtifacts); - } - - - @Test - public void testGetCalculatedCapabilitiesProperties() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedCapabilitiesProperties(); - } - - - @Test - public void testSetCalculatedCapabilitiesProperties() throws Exception { - TopologyTemplate testSubject; - Map calculatedCapabilitiesProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedCapabilitiesProperties(calculatedCapabilitiesProperties); - } - - - @Test - public void testGetInstanceArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstanceArtifacts(); - } - - - @Test - public void testSetInstanceArtifacts() throws Exception { - TopologyTemplate testSubject; - Map instanceArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstanceArtifacts(instanceArtifacts); - } - - - - - - @Test - public void testGetComponentInstances() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstances(); - } - - - @Test - public void testSetComponentInstances() throws Exception { - TopologyTemplate testSubject; - Map instances = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstances(instances); - } - - - @Test - public void testGetRelations() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRelations(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java deleted file mode 100644 index a112c9e51e..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import org.junit.Test; - - -public class ToscaElementTypeEnumTest { - - private ToscaElementTypeEnum createTestSubject() { - return ToscaElementTypeEnum.TopologyTemplate; - } - - - - - - @Test - public void testGetValue() throws Exception { - ToscaElementTypeEnum testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java deleted file mode 100644 index b00b13e162..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.enums; - -import org.junit.Test; - - -public class JsonConstantKeysEnumTest { - - private JsonConstantKeysEnum createTestSubject() { - return JsonConstantKeysEnum.COMPOSITION; - } - - - @Test - public void testGetValue() throws Exception { - JsonConstantKeysEnum testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java new file mode 100644 index 0000000000..1b9da4dbc1 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java @@ -0,0 +1,486 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by yavivi on 21/03/2018. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ArchiveOperationTest extends ModelTestBase { + + private static final String CI_UID_RES1_CP = "cp_uid"; + private static final String CI_UID_RES2_VL = "vl_uid"; + private static final String CI_UID_SVC_PROXY = "svc_proxy_uid"; + + @Resource + private ArchiveOperation archiveOperation; + + @Resource + private TitanDao titanDao; + + private boolean isInitialized; + + private GraphVertex serviceVertex1; + private GraphVertex archivedVertex1; + + GraphVertex archiveVertex; + GraphVertex catalogVertex; + + private GraphVertex serviceVertex1_0; + private GraphVertex serviceVertex1_1; + private GraphVertex serviceVertex2_0; + private GraphVertex serviceVertex3_0; + private GraphVertex serviceVertex3_1; + + private GraphVertex serviceVertex0_1; + private GraphVertex serviceVertex0_2; + private GraphVertex serviceVertex0_3; + private GraphVertex serviceVertex0_4; + private GraphVertex serviceVertex0_5; + + //Composition Elements + private GraphVertex compositionService; + private GraphVertex compositionResource1; + private GraphVertex compositionResource2; + private GraphVertex compositionServiceProxy; + private GraphVertex compositionAnotherService; + + //For VSP Archive Notification + private GraphVertex vfResource0_1; + private GraphVertex vfResource0_2; + private GraphVertex vfResource1_0; + private String csarUuid = "123456789";; + + @BeforeClass + public static void initTest(){ + ModelTestBase.init(); + } + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(titanDao); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testArchiveComponentSingleVersion(){ + String componentId = serviceVertex1.getUniqueId(); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); + assertThat(actionStatus.isLeft()).isTrue(); + assertArchived(serviceVertex1.getUniqueId()); + } + + @Test + public void testArchiveComponentFailsWhenInCheckoutSingleVersion(){ + checkoutComponent(serviceVertex1); + String componentId = serviceVertex1.getUniqueId(); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); + assertThat(actionStatus.isLeft()).isFalse(); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); + } + + @Test + public void testArchiveWithWrongId() { + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent("fakeComponentId"); + assertThat(actionStatus.isLeft()).isFalse(); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + @Test + public void testAlreadyArchived() { + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(archivedVertex1.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactly(archivedVertex1.getUniqueId()); + } + + @Test + public void testScenario2_archive_1_0(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_0.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); + assertArchived(serviceVertex1_0.getUniqueId()); + assertArchived(serviceVertex1_1.getUniqueId()); + } + + @Test + public void testScenario2_archive_1_1(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_1.getUniqueId()); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); + assertArchived(serviceVertex1_0.getUniqueId()); + assertArchived(serviceVertex1_1.getUniqueId()); + } + + @Test + public void testScenario4_oneLowOneHighestVersion(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); + assertArchived(serviceVertex0_1.getUniqueId()); + assertArchived(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_3.getUniqueId()); + assertArchived(serviceVertex0_4.getUniqueId()); + assertArchived(serviceVertex0_5.getUniqueId()); + + actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); + } + + + /////////////// Continue Here ////////////////// + @Test + public void testScenario4_archiveFromNonHighest(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_1.getUniqueId()); + assertArchived(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_3.getUniqueId()); + assertArchived(serviceVertex0_4.getUniqueId()); + assertArchived(serviceVertex0_5.getUniqueId()); + + actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_3.getUniqueId()); + assertRestored(serviceVertex0_1.getUniqueId()); + assertRestored(serviceVertex0_2.getUniqueId()); + assertRestored(serviceVertex0_3.getUniqueId()); + assertRestored(serviceVertex0_4.getUniqueId()); + assertRestored(serviceVertex0_5.getUniqueId()); + } + + @Test + public void testArchiveFailsWhenHighestVersionIsInCheckoutState(){ + checkoutComponent(serviceVertex0_5); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); + } + + @Test + public void testScenario3_archive_3_0(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex3_0.getUniqueId()); + assertArchived(serviceVertex3_0.getUniqueId()); + assertArchived(serviceVertex3_1.getUniqueId()); + assertArchivedProps(serviceVertex2_0.getUniqueId()); + } + + @Test + public void testArchivedOriginsCalculation(){ + + //Archive the CP resource + this.archiveOperation.archiveComponent(this.compositionResource1.getUniqueId()); + this.archiveOperation.archiveComponent(this.compositionServiceProxy.getUniqueId()); + + List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); + + //Validate that method returns the CI of CP + assertThat(ciWithArchivedOrigins).containsExactlyInAnyOrder(CI_UID_RES1_CP, CI_UID_SVC_PROXY); + + Map compositionsJson = (Map) this.compositionService.getJson(); + + assertThat(compositionsJson).isNotNull(); + assertThat(compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue())).isNotNull(); + + CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + + //Get all component instances from composition + Map componentInstances = composition.getComponentInstances(); + for (ComponentInstanceDataDefinition ci : componentInstances.values()) { + //Verify that exactly 2 CIs are marked as archived + if (ci.getUniqueId().equals(CI_UID_RES1_CP) || ci.getUniqueId().equals(CI_UID_SVC_PROXY)) { + assertThat(ci.isOriginArchived()).isTrue(); + } + } + + } + + @Test + public void testNoArchivedOriginsCalculation(){ + List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); + + //Validate that method returns the CI of CP + assertThat(ciWithArchivedOrigins).isEmpty(); + } + + @Test + public void testOnVspArchivedAndRestored(){ + this.archiveOperation.onVspArchived(csarUuid); + //assertOnCommit(); + + assertOnVspArchived(true); + + this.archiveOperation.onVspRestored(csarUuid); + //assertOnCommit(); + assertOnVspArchived(false); + + //Not Found CSAR UUID + ActionStatus result = this.archiveOperation.onVspRestored("fakeUuid"); + //assertOnCommit(); + assertThat(result).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void assertOnVspArchived(boolean expectedValue) { + GraphVertex v = titanDao.getVertexById(vfResource0_1.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + + v = titanDao.getVertexById(vfResource0_2.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + + v = titanDao.getVertexById(vfResource1_0.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + } + + /************************** + * Utility Methods + *************************/ + + private void checkoutComponent(GraphVertex serviceVertex0_5) { + Either vE = titanDao.getVertexById(serviceVertex0_5.getUniqueId()); + GraphVertex v = vE.left().value(); + v.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + v.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + titanDao.updateVertex(v); + assertOnCommit(); + } + + private void assertOnCommit(){ + final TitanOperationStatus commit = this.titanDao.commit(); + assertThat(commit).isEqualTo(TitanOperationStatus.OK); + } + + private void assertArchived(String componentUniqueId) { + assertArchivedOrRestored(ArchiveOperation.Action.ARCHIVE, componentUniqueId); + } + + private void assertRestored(String componentUniqueId) { + assertArchivedOrRestored(ArchiveOperation.Action.RESTORE, componentUniqueId); + } + + private void assertArchivedOrRestored(ArchiveOperation.Action action, String componentUniqueId) { + GraphVertex v = titanDao.getVertexById(componentUniqueId).left().value(); + + EdgeLabelEnum requiredEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.ARCHIVE_ELEMENT : EdgeLabelEnum.CATALOG_ELEMENT; + EdgeLabelEnum otherEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.CATALOG_ELEMENT : EdgeLabelEnum.ARCHIVE_ELEMENT; + + GraphVertex parent = null; + Either otherLookup = null; + Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if (isHighest != null && isHighest) { + //Highest version are linked to Archive/Catalog Root + parent = titanDao.getParentVertex(v, requiredEdge, JsonParseFlagEnum.NoParse).left().value(); + otherLookup = titanDao.getParentVertex(v, otherEdge, JsonParseFlagEnum.NoParse); + assertThat(otherLookup.isRight()).isTrue(); //Verify that component is not linked to Catalog/Archive Root + assertThat(parent.getUniqueId()).isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? this.archiveVertex.getUniqueId() : this.catalogVertex.getUniqueId()); //Verify that parent is indeed Archive Root + } + + assertArchivedOrRestoredProps(action, v); + } + + private void assertArchivedProps(String uniqueId) { + GraphVertex v = + titanDao.getVertexById(uniqueId).left().value(); + assertArchivedOrRestoredProps(ArchiveOperation.Action.ARCHIVE, v); + } + + private void assertRestoredProps(String uniqueId) { + GraphVertex v = + titanDao.getVertexById(uniqueId).left().value(); + assertArchivedOrRestoredProps(ArchiveOperation.Action.RESTORE, v); + } + + private void assertArchivedOrRestoredProps(ArchiveOperation.Action action, GraphVertex v) { + Object isArchived = v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + Object archiveTime = v.getMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME); + assertThat(isArchived).isNotNull().isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? true : false); + assertThat(archiveTime).isNotNull(); + } + + /******************************* + * Preperation Methods + *******************************/ + private void initGraphForTest() { + //Create Catalog Root + this.catalogVertex = GraphTestUtils.createRootCatalogVertex(titanDao); + //Create Archive Root + this.archiveVertex = GraphTestUtils.createRootArchiveVertex(titanDao); + + createScenario1_SingleVersionNode(); + createScenario2_TwoHighestVersions(); + createScenario3_TwoHighestVersionsOneLowest(); + createMiscServices(); + createServiceCompositionForCalculatingArchivedOrigins(); + createScenario4_1Highest4LowestVersions(); + createResourcesForArchivedVsp(); + + assertOnCommit(); + } + + private void createScenario1_SingleVersionNode() { + //Create Service for Scenario 1 Tests (1 Service) + this.serviceVertex1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + + //Connect Service to Catalog Root + titanDao.createEdge(catalogVertex, serviceVertex1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario2_TwoHighestVersions() { + //Create Service for Scenario 2 Tests (1 Service) + this.serviceVertex1_0 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + this.serviceVertex1_1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + + titanDao.createEdge(serviceVertex1_0, serviceVertex1_1, EdgeLabelEnum.VERSION, null); + + //Connect 1.0 and 1.1 to Catalog Root + titanDao.createEdge(catalogVertex, serviceVertex1_0, EdgeLabelEnum.CATALOG_ELEMENT, null); + titanDao.createEdge(catalogVertex, serviceVertex1_1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario3_TwoHighestVersionsOneLowest() { + //Create Service for Scenario 1 Tests (1 Service) + this.serviceVertex2_0 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); //NonHighestVersion + this.serviceVertex3_0 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + this.serviceVertex3_1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + + //Connect version edges + titanDao.createEdge(serviceVertex2_0, serviceVertex3_0, EdgeLabelEnum.VERSION, null); + titanDao.createEdge(serviceVertex3_0, serviceVertex3_1, EdgeLabelEnum.VERSION, null); + + //Connect 3.0 and 3.1 to Catalog Root + titanDao.createEdge(catalogVertex, serviceVertex3_0, EdgeLabelEnum.CATALOG_ELEMENT, null); + titanDao.createEdge(catalogVertex, serviceVertex3_1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario4_1Highest4LowestVersions() { + //2 Lowest version only + this.serviceVertex0_1 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); + this.serviceVertex0_2 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); + this.serviceVertex0_3 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); + this.serviceVertex0_4 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); + this.serviceVertex0_5 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + + titanDao.createEdge(serviceVertex0_1, serviceVertex0_2, EdgeLabelEnum.VERSION, null); + titanDao.createEdge(serviceVertex0_2, serviceVertex0_3, EdgeLabelEnum.VERSION, null); + titanDao.createEdge(serviceVertex0_3, serviceVertex0_4, EdgeLabelEnum.VERSION, null); + titanDao.createEdge(serviceVertex0_4, serviceVertex0_5, EdgeLabelEnum.VERSION, null); + + titanDao.createEdge(catalogVertex, serviceVertex0_5, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createResourcesForArchivedVsp(){ + Map vfPropsNonHighest = propsForNonHighestVersion(); + Map vfPropsHighest = propsForNonHighestVersion(); + + vfPropsNonHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); + vfPropsNonHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); + vfPropsHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); + vfPropsHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); + + this.vfResource0_1 = GraphTestUtils.createResourceVertex(titanDao, vfPropsNonHighest, ResourceTypeEnum.VF); + this.vfResource0_2 = GraphTestUtils.createResourceVertex(titanDao, vfPropsNonHighest, ResourceTypeEnum.VF); + this.vfResource1_0 = GraphTestUtils.createResourceVertex(titanDao, vfPropsHighest, ResourceTypeEnum.VF); + + titanDao.createEdge(vfResource0_1, vfResource0_2, EdgeLabelEnum.VERSION, null); + titanDao.createEdge(vfResource0_2, vfResource1_0, EdgeLabelEnum.VERSION, null); + } + + private void createMiscServices() { + //Create Service for Scenario 1 Tests (1 Service) + this.archivedVertex1 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + + //Connect Service to Catalog Root + titanDao.createEdge(archiveVertex, archivedVertex1, EdgeLabelEnum.ARCHIVE_ELEMENT, null); + } + + private void createServiceCompositionForCalculatingArchivedOrigins(){ + //Service that point to another service in composition + this.compositionService = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + this.compositionAnotherService = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + + this.compositionResource1 = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.CP); + this.compositionResource2 = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.VL); + this.compositionServiceProxy = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.ServiceProxy); + + titanDao.createEdge(compositionService, compositionResource1, EdgeLabelEnum.INSTANCE_OF, null); + titanDao.createEdge(compositionService, compositionResource2, EdgeLabelEnum.INSTANCE_OF, null); + titanDao.createEdge(compositionService, compositionServiceProxy, EdgeLabelEnum.INSTANCE_OF, null); + titanDao.createEdge(compositionService, compositionAnotherService, EdgeLabelEnum.PROXY_OF, null); + + createAndAttachCompositionJson(compositionService); + } + + private void createAndAttachCompositionJson(GraphVertex compositionService) { + //Full composition json + Map compositions = new HashMap<>(); + //Single composition data + CompositionDataDefinition composition = new CompositionDataDefinition(); + //Instances Map + Map instances = new HashMap<>(); + + //Prepare Instances Map + ComponentInstanceDataDefinition instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_RES1_CP); + instance.setComponentUid(compositionResource1.getUniqueId()); + instances.put(CI_UID_RES1_CP, instance); + + instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_RES2_VL); + instance.setComponentUid(compositionResource2.getUniqueId()); + instances.put(CI_UID_RES2_VL, instance); + + instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_SVC_PROXY); + instance.setComponentUid(compositionServiceProxy.getUniqueId()); + instances.put(CI_UID_SVC_PROXY, instance); + + //Add Instances to Composition + composition.setComponentInstances(instances); + //Add to full composition + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); + //Add Full Json to vertex + compositionService.setJson(compositions); + //System.out.println(JsonParserUtils.toJson(compositions)); + titanDao.updateVertex(compositionService); + } + + private Map propsForHighestVersion(){ + Map props = new HashMap(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + return props; + } + + private Map propsForNonHighestVersion(){ + Map props = new HashMap(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + return props; + } + +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java index a8fb60999c..410cef9ae8 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java @@ -1,18 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.CALLS_REAL_METHODS; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -22,7 +10,12 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; public class ArtifactsOperationsTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java index efa4020d0c..e580fd51bb 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java @@ -1,14 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -24,10 +16,15 @@ import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; +import org.openecomp.sdc.be.model.operations.StorageException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; /** * Created by yavivi on 26/01/2018. @@ -36,6 +33,18 @@ import fj.data.Either; @ContextConfiguration("classpath:application-context-test.xml") public class ExternalReferencesOperationTest extends ModelTestBase { + private static final String COMPONENT_ID = "ci-MyComponentName"; + private static final String COMPONENT2_ID = "ci-MyComponentName2"; + private static final String MONITORING_OBJECT_TYPE = "monitoring"; + private static final String WORKFLOW_OBJECT_TYPE = "workflow"; + private static final String REF_1 = "ref1"; + private static final String REF_2 = "ref2"; + private static final String REF_3 = "ref3"; + private static final String REF_4 = "ref4"; + private static final String REF_5 = "ref5"; + //workflow + private static final String REF_6 = "ref6"; + @Resource private ExternalReferencesOperation externalReferenceOperation; @@ -45,20 +54,12 @@ public class ExternalReferencesOperationTest extends ModelTestBase { private boolean isInitialized; private GraphVertex serviceVertex; + private GraphVertex serviceVertex2; + private GraphVertex serviceVertex3; private String serviceVertexUuid; - private static final String COMPONENT_ID = "ci-MyComponentName"; - - private static final String MONITORING_OBJECT_TYPE = "monitoring"; - private static final String WORKFLOW_OBJECT_TYPE = "workflow"; - private static final String REF_1 = "ref1"; - private static final String REF_2 = "ref2"; - private static final String REF_3 = "ref3"; - private static final String REF_4 = "ref4"; - private static final String REF_5 = "ref5"; - - //workflow - private static final String REF_6 = "ref6"; + private String serviceVertex2Uuid; + private String serviceVertex3Uuid; private IdMapper idMapper; @@ -91,6 +92,44 @@ public class ExternalReferencesOperationTest extends ModelTestBase { assertThat(getServiceExternalRefs()).contains(REF_1, REF_2, REF_3, REF_4); } + @Test + public void testAddExternalReferences_success() { + Map> refsMap = Collections.singletonMap(MONITORING_OBJECT_TYPE, Arrays.asList(REF_1, REF_2)); + externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID, refsMap); + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isEqualTo(1); + assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); + externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID, refsMap); + Map> allExternalReferences2 = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID); + assertThat(allExternalReferences2.size()).isEqualTo(1); + assertThat(allExternalReferences2).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); + } + + @Test + public void testGetAllCIExternalRefs_success() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertexUuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isEqualTo(2); + assertThat(allExternalReferences).flatExtracting(WORKFLOW_OBJECT_TYPE).containsExactly(REF_6); + assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2, REF_3, REF_5); + } + + @Test + public void testGetAllCIExternalRefs_noRefsExist() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isZero(); + } + + @Test + public void testGetAllCIExternalRefs_noSuchComponentInstance() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, "FAKE"); + assertThat(allExternalReferences.size()).isZero(); + } + + @Test(expected=StorageException.class) + public void testGetAllCIExternalRefs_nonExitingService_throwsException() { + externalReferenceOperation.getAllExternalReferences("FAKE", COMPONENT_ID); + } + @Test public void testGetComponentInstanceExternalRef(){ assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5); @@ -155,13 +194,12 @@ public class ExternalReferencesOperationTest extends ModelTestBase { //Get List of references //final List externalRefsByObjectType = mapComponentInstanceExternalRefs.externalRefsByObjectType(objectType); - final List externalRefsByObjectType = mapComponentInstanceExternalRefs.getExternalRefsByObjectType(MONITORING_OBJECT_TYPE); - return externalRefsByObjectType; + return mapComponentInstanceExternalRefs.getExternalRefsByObjectType(MONITORING_OBJECT_TYPE); } private void initGraphForTest() { - //create a service and add 1 ref + //create a service this.serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); this.serviceVertexUuid = this.serviceVertex.getUniqueId(); @@ -174,6 +212,14 @@ public class ExternalReferencesOperationTest extends ModelTestBase { //workflow references externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); + //create a service without refs + serviceVertex2 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + serviceVertex2Uuid = serviceVertex2.getUniqueId(); + + //create a service for adding all references + serviceVertex3 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + serviceVertex3Uuid = serviceVertex3.getUniqueId(); + final TitanOperationStatus commit = this.titanDao.commit(); assertThat(commit).isEqualTo(TitanOperationStatus.OK); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java new file mode 100644 index 0000000000..191546d5c0 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java @@ -0,0 +1,102 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.config.TitanSpringConfig; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.List; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) +public class GroupsOperationTest extends ModelTestBase { + + @Autowired + private GroupsOperation groupsOperation; + + @Autowired + TitanDao titanDao; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + private Component container; + + @BeforeClass + public static void initClass() { + ModelTestBase.init(); + } + + @Before + public void setUp() throws Exception { + container = new Resource(); + container.setUniqueId(CONTAINER_ID); + Either createdCmpt = titanDao.createVertex(createBasicContainerGraphVertex()); + assertThat(createdCmpt.isLeft()).isTrue(); + + } + + @After + public void tearDown() throws Exception { + titanDao.rollback(); + } + + @Test + public void addGroups_whenContainerHasNoGroups_associateContainerWithGroup() { + GroupDefinition g1 = createGroupDefinition("g1"); + GroupDefinition g2 = createGroupDefinition("g2"); + Either, StorageOperationStatus> createGroups = groupsOperation.addGroups(container, asList(g1, g2)); + assertThat(createGroups.isLeft()).isTrue(); + + ComponentParametersView getGroupsFilter = new ComponentParametersView(true); + getGroupsFilter.setIgnoreGroups(false); + Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); + assertThat(cmptWithGroups.getGroups()) + .usingElementComparatorOnFields("name", "uniqueId") + .containsExactlyInAnyOrder(g1, g2); + } + + @Test + public void addGroups_whenContainerHasGroups_addTheGivenGroupsToTheGroupsList() { + GroupDefinition g1 = createGroupDefinition("g1"); + GroupDefinition g2 = createGroupDefinition("g2"); + groupsOperation.addGroups(container, asList(g1, g2)).left().value(); + + GroupDefinition g3 = createGroupDefinition("g3"); + GroupDefinition g4 = createGroupDefinition("g4"); + + groupsOperation.addGroups(container, asList(g3, g4)).left().value(); + + ComponentParametersView getGroupsFilter = new ComponentParametersView(true); + getGroupsFilter.setIgnoreGroups(false); + Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); + assertThat(cmptWithGroups.getGroups()) + .usingElementComparatorOnFields("name", "uniqueId") + .containsExactlyInAnyOrder(g1, g2, g3, g4); + + } + + private GroupDefinition createGroupDefinition(String id) { + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setUniqueId(id); + groupDefinition.setName("name" + id); + return groupDefinition; + } + + +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java index c3e8ce3eb6..f2aefa0aa3 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java @@ -3,11 +3,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -23,11 +19,7 @@ import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; @@ -42,11 +34,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -365,7 +357,7 @@ public class InterfacesOperationTest extends ModelTestBase{ Map capProps = new HashMap(); capProps.put("capName", dataToCreate); - Either res = nodeTypeOperation.assosiateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); + Either res = nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); List pathKeys = new ArrayList<>(); pathKeys.add("capName"); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java new file mode 100644 index 0000000000..ac8d8e7e8d --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java @@ -0,0 +1,239 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.config.TitanSpringConfig; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) +public class NodeTemplateOperationGraphTest extends ModelTestBase{ + @Resource + private TitanDao titanDao; + @Resource + private NodeTemplateOperation nodeTemplateOperation; + + private TitanGraph graphT; + private GraphVertex containerVertex; + private String containeId; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + @Before + public void before(){ + + Either graph = titanDao.getGraph(); + graphT = graph.left().value(); + + containerVertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + containeId = "containerId"; + containerVertex.setUniqueId(containeId); + Either createVertex = titanDao.createVertex(containerVertex); + assertTrue(createVertex.isLeft()); + } + + @After + public void after(){ + titanDao.rollback(); + + } + + + String outputDirectory = "C:\\Output"; + + @Test + public void testCreateInstanceEdge(){ + + Map> mapOriginToInstId = new HashMap<>(); + createIntancesFromSameResource(mapOriginToInstId, 1, 3); + createIntancesFromSameResource(mapOriginToInstId, 2, 4); + createIntancesFromSameResource(mapOriginToInstId, 3, 1); + +// exportGraphMl(graphT); + + validateOnGraph(mapOriginToInstId, 3); + } + + @Test + public void testRemoveInstanceEdge(){ + //create 3 instances from same resource orig1 + Map> mapOriginToInstId = new HashMap<>(); + String originId = createIntancesFromSameResource(mapOriginToInstId, 1, 3); + validateOnGraph(mapOriginToInstId, 1); + + //remove instance 2 + String instanceId = removeInstanceEdge(containerVertex, originId, 1, 1); + mapOriginToInstId.get(originId).remove(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + //create new instance from orig1 + instanceId = createInstanceEdge(containerVertex, originId, 1, 4, false, null); + mapOriginToInstId.get(originId).add(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + //create 1 instance from same resource orig2 + originId = createIntancesFromSameResource(mapOriginToInstId, 2, 1); + validateOnGraph(mapOriginToInstId, 2); + + //remove instance of orig 2 + instanceId = removeInstanceEdge(containerVertex, originId, 2, 1); + mapOriginToInstId.get(originId).remove(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + } + + @Test + public void testProxyInstanceEdge(){ + Map> mapOriginToInstId = new HashMap<>(); + String proxyId = createOrigin(2); + createIntancesFromSameResource(mapOriginToInstId, 1, 1, true, proxyId); + + validateOnGraph(mapOriginToInstId, 1); + } + private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount) { + validateOnGraph(mapOriginToInstId, expectedEdgeCount, false); + } + private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount, boolean validateProxy) { + Iterable vertices = graphT.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), containeId).vertices(); + assertNotNull(vertices); + Iterator iterator = vertices.iterator(); + assertTrue(iterator.hasNext()); + Vertex containerV = iterator.next(); + validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.INSTANCE_OF); + if ( validateProxy ){ + validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.PROXY_OF); + } + } + private void validatePerEdgeType(Map> mapOriginToInstId, int expectedEdgeCount, Vertex containerV, EdgeLabelEnum edgeLabel) { + Iterator edges = containerV.edges(Direction.OUT, edgeLabel.name()); + assertNotNull(edges); + + int counter = 0; + while (edges.hasNext()){ + Edge edge = edges.next(); + counter++; + validateEdge(edge, mapOriginToInstId); + } + assertEquals("check edge size", expectedEdgeCount, counter); + } + + + private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances) { + return createIntancesFromSameResource(mapOriginToInstId, originIndex, countInstances, false, null); + } + + private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances, boolean isProxy, String proxyId) { + + List exp = new ArrayList(); + String originId = createOrigin(originIndex); + + for ( int i = 0; i < countInstances; i++){ + String instanceId = createInstanceEdge(containerVertex, originId, originIndex, i+1, isProxy, proxyId); + exp.add(instanceId); + } + mapOriginToInstId.put(originId, exp); + if ( isProxy ){ + mapOriginToInstId.put(proxyId, exp); + } + return originId; + } + + private String createInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex, boolean isProxy, String proxyId) { + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); + componentInstance.setComponentUid(originId); + String instanceId = buildInstanceId(originIndex, insIndex); + componentInstance.setUniqueId(instanceId); + componentInstance.setIsProxy(isProxy); + componentInstance.setSourceModelUid(proxyId); + StorageOperationStatus edgeStatus = nodeTemplateOperation.createInstanceEdge(containerVertex, componentInstance); + assertEquals("assertion createInstanceEdge", StorageOperationStatus.OK, edgeStatus); + return instanceId; + } + + private String buildInstanceId(int originIndex, int insIndex) { + StringBuffer sb = new StringBuffer("instanceId_"); + sb.append(originIndex).append("-").append(insIndex); + return sb.toString(); + } + private String removeInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex) { + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); + componentInstance.setComponentUid(originId); + String instanceId = buildInstanceId(originIndex, insIndex); + componentInstance.setUniqueId(instanceId); + StorageOperationStatus edgeStatus = nodeTemplateOperation.removeInstanceEdge(containerVertex, componentInstance); + assertEquals("assertion removeInstanceEdge", StorageOperationStatus.OK, edgeStatus); + return instanceId; + } + + + private String createOrigin(int index) { + Either createVertex; + GraphVertex originVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); + String originId = "originId_" + index; + originVertex.setUniqueId(originId); + createVertex = titanDao.createVertex(originVertex); + assertTrue(createVertex.isLeft()); + return originId; + } + private void validateEdge(Edge edge, Map> mapOriginToInstId) { + List expextedInList; + + Vertex originV = edge.inVertex(); + String id = (String) titanDao.getProperty((TitanVertex)originV, GraphPropertyEnum.UNIQUE_ID.getProperty()); + expextedInList = mapOriginToInstId.get(id); + + List list = (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + assertThat(list).hasSameSizeAs(expextedInList); + assertThat(list).containsOnlyElementsOf(expextedInList); + } + + private String exportGraphMl(TitanGraph graph) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java index 65baa42e16..fcde5b2605 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java @@ -1,13 +1,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.common.collect.Lists; +import fj.data.Either; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -17,198 +11,181 @@ import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import com.google.common.collect.Lists; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; public class NodeTemplateOperationTest extends ModelTestBase { - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static Map fulfilledCapability; - private static Map fulfilledRequirement; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - private static TitanDao titanDao; - private static NodeTemplateOperation operation; - - @BeforeClass - public static void setup() { - init(); - titanDao = Mockito.mock(TitanDao.class); - operation = new NodeTemplateOperation(); - operation.setTitanDao(titanDao); - buildDataDefinition(); - } - - private static void buildDataDefinition() { - buildCapabiltyDataDefinition(); - buildRequirementDataDefinition(); - buildRelation(); - } - - @Test - public void testGetFulfilledCapabilityByRelationSuccess() { - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - GraphVertex dataVertex = new GraphVertex(); - dataVertex.setJson(fulfilledCapability); - Either childVertexRes = Either.left(dataVertex); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), - eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledCapabilityByRelation( - COMPONENT_ID, TO_INSTANCE_ID, relation, (rel, cap) -> isBelongingCapability(rel, cap)); - assertTrue(result.isLeft()); - assertTrue(result.left().value().equals(capability)); - } - - @Test - public void testGetFulfilledRequirementByRelationSuccess() { - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - GraphVertex dataVertex = new GraphVertex(); - dataVertex.setJson(fulfilledRequirement); - Either childVertexRes = Either.left(dataVertex); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), - eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledRequirementByRelation( - COMPONENT_ID, FROM_INSTANCE_ID, relation, (rel, req) -> isBelongingRequirement(rel, req)); - assertTrue(result.isLeft()); - assertTrue(result.left().value().equals(requirement)); - } - - @Test - public void testGetFulfilledCapabilityByRelationNotFoundFailure() { - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), - eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledCapabilityByRelation( - COMPONENT_ID, TO_INSTANCE_ID, relation, (rel, cap) -> isBelongingCapability(rel, cap)); - assertTrue(result.isRight()); - assertTrue(result.right().value() == StorageOperationStatus.NOT_FOUND); - } - - @Test - public void testGetFulfilledRequirementByRelationNotFoundFailure() { - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), - eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledRequirementByRelation( - COMPONENT_ID, FROM_INSTANCE_ID, relation, (rel, req) -> isBelongingRequirement(rel, req)); - assertTrue(result.isRight()); - assertTrue(result.right().value() == StorageOperationStatus.NOT_FOUND); - } - - private static void buildRequirementDataDefinition() { - buildRequirement(); - fulfilledRequirement = new HashMap<>(); - MapListRequirementDataDefinition mapListRequirementDataDefinition = new MapListRequirementDataDefinition(); - mapListRequirementDataDefinition.add(requirement.getCapability(), requirement); - fulfilledRequirement.put(FROM_INSTANCE_ID, mapListRequirementDataDefinition); - - } - - private static void buildRequirement() { - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - } - - private static void buildCapabiltyDataDefinition() { - buildCapability(); - fulfilledCapability = new HashMap<>(); - MapListCapabiltyDataDefinition mapListCapabiltyDataDefinition = new MapListCapabiltyDataDefinition(); - mapListCapabiltyDataDefinition.add(capability.getType(), capability); - fulfilledCapability.put(TO_INSTANCE_ID, mapListCapabiltyDataDefinition); - } - - private static void buildCapability() { - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - } - - private static void buildRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } - - private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { - return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) - && req.getName().equals(relationshipInfo.getRequirement()) - && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) - && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); - } - - private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { - return cap.getName().equals(relationshipInfo.getCapability()) - && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) - && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static Map fulfilledCapability; + private static Map fulfilledRequirement; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + private static TitanDao titanDao; + private static NodeTemplateOperation operation; + + @BeforeClass + public static void setup() { + init(); + titanDao = Mockito.mock(TitanDao.class); + operation = new NodeTemplateOperation(); + operation.setTitanDao(titanDao); + buildDataDefinition(); + } + + private static void buildDataDefinition() { + buildCapabiltyDataDefinition(); + buildRequirementDataDefinition(); + buildRelation(); + } + + @Test + public void testGetFulfilledCapabilityByRelationSuccess(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + GraphVertex dataVertex = new GraphVertex(); + dataVertex.setJson(fulfilledCapability); + Either childVertexRes = Either.left(dataVertex); + when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); + assertTrue(result.isLeft()); + assertEquals(result.left().value(), capability); + } + + @Test + public void testGetFulfilledRequirementByRelationSuccess(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + GraphVertex dataVertex = new GraphVertex(); + dataVertex.setJson(fulfilledRequirement); + Either childVertexRes = Either.left(dataVertex); + when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); + assertTrue(result.isLeft()); + assertEquals(result.left().value(), requirement); + } + + @Test + public void testGetFulfilledCapabilityByRelationNotFoundFailure(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); + when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); + assertTrue(result.isRight()); + assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); + } + + @Test + public void testGetFulfilledRequirementByRelationNotFoundFailure(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); + when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); + assertTrue(result.isRight()); + assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); + } + + private static void buildRequirementDataDefinition() { + buildRequirement(); + fulfilledRequirement = new HashMap<>(); + MapListRequirementDataDefinition mapListRequirementDataDefinition = new MapListRequirementDataDefinition(); + mapListRequirementDataDefinition.add(requirement.getCapability(), requirement); + fulfilledRequirement.put(FROM_INSTANCE_ID, mapListRequirementDataDefinition); + + } + + private static void buildRequirement() { + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + } + + private static void buildCapabiltyDataDefinition() { + buildCapability(); + fulfilledCapability = new HashMap<>(); + MapListCapabilityDataDefinition mapListCapabiltyDataDefinition = new MapListCapabilityDataDefinition(); + mapListCapabiltyDataDefinition.add(capability.getType(), capability); + fulfilledCapability.put(TO_INSTANCE_ID, mapListCapabiltyDataDefinition); + } + + private static void buildCapability() { + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + } + + private static void buildRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } + + private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && + req.getName().equals(relationshipInfo.getRequirement()) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + + private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + return cap.getName().equals(relationshipInfo.getCapability()) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); } private NodeTemplateOperation createTestSubject() { @@ -222,7 +199,7 @@ public class NodeTemplateOperationTest extends ModelTestBase { // default test result = NodeTemplateOperation.getDefaultHeatTimeout(); - } + } @@ -270,7 +247,7 @@ public class NodeTemplateOperationTest extends ModelTestBase { NodeTemplateOperation testSubject; Map capabilities = null; ComponentInstanceDataDefinition componentInstance = null; - MapListCapabiltyDataDefinition result; + MapListCapabilityDataDefinition result; // test 1 testSubject = createTestSubject(); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java index 6a257d33de..ee88e9a515 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java @@ -1,15 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.apache.commons.collections.ListUtils.union; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import fj.data.Either; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -35,7 +26,14 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.apache.commons.collections.ListUtils.union; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) @@ -80,7 +78,7 @@ public class PolicyOperationIntegrationTest extends ModelTestBase { titanDao.createVertex(resource); GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value(); topologyTemplateOperation.addToscaDataToToscaElement(loadedResource, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policy, JsonPresentationFields.UNIQUE_ID); - titanDao.commit(); +// titanDao.commit(); } @After @@ -118,7 +116,7 @@ public class PolicyOperationIntegrationTest extends ModelTestBase { componentParametersView.setIgnorePolicies(false); Either loadedCmptEither = topologyTemplateOperation.getToscaElement(CONTAINER_ID, componentParametersView); - assertThat(loadedCmptEither.isLeft()); + assertThat(loadedCmptEither.isLeft()).isTrue(); ToscaElement loadedCmpt = loadedCmptEither.left().value(); assertThat(loadedCmpt).isInstanceOf(TopologyTemplate.class); @SuppressWarnings("unchecked") List allProperties = union(updatedProperties, nonUpdatedPropeties); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java index 23b6b3153d..136f95b987 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collections; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +19,13 @@ import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class PolicyOperationTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java index 325b4c9ef8..1f30d27f8a 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java @@ -1,14 +1,5 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -19,7 +10,7 @@ import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.Component; @@ -32,12 +23,20 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTestBase { private static final String CONTAINER_ID = "id"; - private Map capabilitiesPropsMap; + private Map capabilitiesPropsMap; private List capabilitiesProperties; @Resource @@ -67,7 +66,7 @@ public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTes //capablities props == Map>> capabilitiesProperties.forEach(capabilitiesProperty -> { - capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabiltyProperty(new HashMap<>())) + capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabilityProperty(new HashMap<>())) .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>())) .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue()))); }); @@ -76,19 +75,17 @@ public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTes resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); titanDao.createVertex(resource); GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value(); - topologyTemplateOperation.assosiateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value(); - titanDao.commit(); - + topologyTemplateOperation.associateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value(); } @After - public void tearDown() throws Exception { + public void tearDown() { titanDao.rollback(); } @Test public void overrideCalculatedCapabilityProperties() { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap); capabilityProperty1.setPropValue("newVal1"); capabilityProperty3.setPropValue("newVal3"); @@ -96,7 +93,7 @@ public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTes setPropertyValue(capabilitiesPropsMap, capabilityProperty3); StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap); assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - Map updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + Map updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap); } @@ -106,7 +103,7 @@ public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTes assertCapabilityPropValue(capabilityProperty2, "val2"); assertCapabilityPropValue(capabilityProperty3, "val3"); - MapCapabiltyProperty instance1Props = capabilitiesPropsMap.get("instance1"); + MapCapabilityProperty instance1Props = capabilitiesPropsMap.get("instance1"); capabilityProperty1.setPropValue("newVal1"); setPropertyValue(capabilitiesPropsMap, capabilityProperty1); @@ -123,36 +120,36 @@ public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTes assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated } - private Map fetchCapabilitiesProps(String containerId) { + private Map fetchCapabilitiesProps(String containerId) { ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true); capabilityPropsFilter.setIgnoreCapabiltyProperties(false); return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties(); } - private void compareCapabilitiesProperties(List expected, Map actual) { + private void compareCapabilitiesProperties(List expected, Map actual) { expected.forEach(expectedCapabilityProp -> { assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName)) .isEqualTo(expectedCapabilityProp.propValue); }); } - private String getPropertyValue(Map capabilityPropertyMap, String instance, String capability, String prop) { + private String getPropertyValue(Map capabilityPropertyMap, String instance, String capability, String prop) { return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue(); } - private void setPropertyValue(Map capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) { + private void setPropertyValue(Map capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) { setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty); } - private void setPropertyValue(MapCapabiltyProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) { + private void setPropertyValue(MapCapabilityProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) { capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId()) .getMapToscaDataDefinition().get(capabilityProperty.getPropName()) .setValue(capabilityProperty.getPropValue()); } private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName()); assertThat(propertyValue).isEqualTo(expectedValue); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java deleted file mode 100644 index d7a698654e..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class TopologyTemplateOperationIntegrationTest extends ModelTestBase { - - private static final String CONTAINER_ID = "id"; - private Map capabilitiesPropsMap; - private List capabilitiesProperties; - - @Resource - private TopologyTemplateOperation topologyTemplateOperation; - - @Resource - private TitanDao titanDao; - private CapabilityPropertyDataObject capabilityProperty1; - private CapabilityPropertyDataObject capabilityProperty2; - private CapabilityPropertyDataObject capabilityProperty3; - - @BeforeClass - public static void setupBeforeClass() { - - ModelTestBase.init(); - } - - @Before - public void setUp() throws Exception { - - capabilitiesPropsMap = new HashMap<>(); - capabilityProperty1 = new CapabilityPropertyDataObject("instance1", "capability1", "prop1", "val1"); - capabilityProperty2 = new CapabilityPropertyDataObject("instance1", "capability2", "prop2", "val2"); - capabilityProperty3 = new CapabilityPropertyDataObject("instance2", "capability3", "prop3", "val3"); - capabilitiesProperties = Arrays.asList(capabilityProperty1, capabilityProperty2, capabilityProperty3); - - - //capablities props == Map>> - capabilitiesProperties.forEach(capabilitiesProperty -> { - capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabiltyProperty(new HashMap<>())) - .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>())) - .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue()))); - }); - - GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); - titanDao.createVertex(resource); - GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value(); - topologyTemplateOperation.assosiateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value(); - titanDao.commit(); - - } - - @After - public void tearDown() throws Exception { - titanDao.rollback(); - } - - @Test - public void overrideCalculatedCapabilityProperties() { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap); - capabilityProperty1.setPropValue("newVal1"); - capabilityProperty3.setPropValue("newVal3"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty1); - setPropertyValue(capabilitiesPropsMap, capabilityProperty3); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - Map updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap); - } - - @Test - public void updateToscaDataDeepElementsBlockToToscaElement() { - assertCapabilityPropValue(capabilityProperty1, "val1"); - assertCapabilityPropValue(capabilityProperty2, "val2"); - assertCapabilityPropValue(capabilityProperty3, "val3"); - - MapCapabiltyProperty instance1Props = capabilitiesPropsMap.get("instance1"); - capabilityProperty1.setPropValue("newVal1"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty1); - - capabilityProperty3.setPropValue("newVal3"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty3); - - Component component = new org.openecomp.sdc.be.model.Resource(); - component.setUniqueId(CONTAINER_ID); - StorageOperationStatus updateStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instance1Props, "instance1"); - - assertThat(updateStatus).isEqualTo(StorageOperationStatus.OK); - assertCapabilityPropValue(capabilityProperty1, "newVal1"); - assertCapabilityPropValue(capabilityProperty2, "val2"); - assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated - } - - private Map fetchCapabilitiesProps(String containerId) { - ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true); - capabilityPropsFilter.setIgnoreCapabiltyProperties(false); - return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties(); - } - - private void compareCapabilitiesProperties(List expected, Map actual) { - expected.forEach(expectedCapabilityProp -> { - assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName)) - .isEqualTo(expectedCapabilityProp.propValue); - }); - } - - private String getPropertyValue(Map capabilityPropertyMap, String instance, String capability, String prop) { - return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue(); - } - - private void setPropertyValue(Map capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) { - setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty); - - } - - private void setPropertyValue(MapCapabiltyProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) { - capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId()) - .getMapToscaDataDefinition().get(capabilityProperty.getPropName()) - .setValue(capabilityProperty.getPropValue()); - } - - private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName()); - assertThat(propertyValue).isEqualTo(expectedValue); - } - - - private PropertyDefinition createPropWithValue(String val) { - PropertyDefinition propertyDefinition = new PropertyDefinition(); - propertyDefinition.setValue(val); - return propertyDefinition; - } - - private static class CapabilityPropertyDataObject { - private String instanceId; - private String capabilityId; - private String propName; - private String propValue; - - CapabilityPropertyDataObject(String instanceId, String capabilityId, String propName, String propValue) { - this.instanceId = instanceId; - this.capabilityId = capabilityId; - this.propName = propName; - this.propValue = propValue; - } - - String getInstanceId() { - return instanceId; - } - - String getCapabilityId() { - return capabilityId; - } - - String getPropName() { - return propName; - } - - String getPropValue() { - return propValue; - } - - void setPropValue(String propValue) { - this.propValue = propValue; - } - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java index e8655b5036..6193c5d6b9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java @@ -1,13 +1,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -19,15 +13,19 @@ import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import com.thinkaurelius.titan.core.TitanVertex; +import java.util.Collections; +import java.util.HashMap; -import fj.data.Either; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) //error scenarios @@ -58,7 +56,7 @@ public class TopologyTemplateOperationTest { @Test public void updateToscaDataDeepElements_failedToFetchContainerVertex() { when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.INVALID_ID)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabiltyProperty(), ""); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID); } @@ -67,44 +65,44 @@ public class TopologyTemplateOperationTest { GraphVertex containerVertex = new GraphVertex(); when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex)); when(titanDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabiltyProperty(), ""); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); } - @Test + @Test public void addPolicyToToscaElementSuccessTest(){ - TitanOperationStatus status = TitanOperationStatus.OK; - StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); - assertThat(result).isEqualTo(StorageOperationStatus.OK); + TitanOperationStatus status = TitanOperationStatus.OK; + StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); + assertThat(result).isEqualTo(StorageOperationStatus.OK); } - @Test + @Test public void addPolicyToToscaElementFailureTest(){ - TitanOperationStatus status = TitanOperationStatus.ALREADY_EXIST; - StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); - assertThat(result).isEqualTo(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + TitanOperationStatus status = TitanOperationStatus.ALREADY_EXIST; + StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); + assertThat(result).isEqualTo(StorageOperationStatus.ENTITY_ALREADY_EXISTS); } - @SuppressWarnings("unchecked") - private StorageOperationStatus addPolicyToToscaElementWithStatus(TitanOperationStatus status) { - GraphVertex componentV = new GraphVertex(); - componentV.setVertex(Mockito.mock(TitanVertex.class)); - GraphVertex dataV = new GraphVertex(); - dataV.setVertex(Mockito.mock(TitanVertex.class)); - String componentName = "componentName"; - String componentId = UniqueIdBuilder.buildResourceUniqueId(); - String policyTypeName = "org.openecomp.policies.placement.valet.Affinity"; - componentV.setJsonMetadataField(JsonPresentationFields.NAME, componentName); - componentV.setUniqueId(componentId); - PolicyDefinition policy = new PolicyDefinition(); - policy.setPolicyTypeName(policyTypeName); - int counter = 0; - Either toscaDataVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(componentV), eq(EdgeLabelEnum.POLICIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(toscaDataVertexRes); - Either createVertex = Either.left(dataV); - when(titanDao.createVertex(any(GraphVertex.class))).thenReturn(createVertex); - when(titanDao.createEdge(any(TitanVertex.class), any(TitanVertex.class), any(EdgeLabelEnum.class), any(HashMap.class))).thenReturn(status); - return topologyTemplateOperation.addPolicyToToscaElement(componentV, policy, counter); - } + @SuppressWarnings("unchecked") + private StorageOperationStatus addPolicyToToscaElementWithStatus(TitanOperationStatus status) { + GraphVertex componentV = new GraphVertex(); + componentV.setVertex(Mockito.mock(TitanVertex.class)); + GraphVertex dataV = new GraphVertex(); + dataV.setVertex(Mockito.mock(TitanVertex.class)); + String componentName = "componentName"; + String componentId = UniqueIdBuilder.buildResourceUniqueId(); + String policyTypeName = "org.openecomp.policies.placement.valet.Affinity"; + componentV.setJsonMetadataField(JsonPresentationFields.NAME, componentName); + componentV.setUniqueId(componentId); + PolicyDefinition policy = new PolicyDefinition(); + policy.setPolicyTypeName(policyTypeName); + int counter = 0; + Either toscaDataVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); + when(titanDao.getChildVertex(eq(componentV), eq(EdgeLabelEnum.POLICIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(toscaDataVertexRes); + Either createVertex = Either.left(dataV); + when(titanDao.createVertex(any(GraphVertex.class))).thenReturn(createVertex); + when(titanDao.createEdge(any(TitanVertex.class), any(TitanVertex.class), any(EdgeLabelEnum.class), any(HashMap.class))).thenReturn(status); + return topologyTemplateOperation.addPolicyToToscaElement(componentV, policy, counter); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java new file mode 100644 index 0000000000..bffefd86cd --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java @@ -0,0 +1,73 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ToscaElementOperationCatalogTest { + + private ArrayList vertexList = new ArrayList<>(); + + @Mock + Vertex vertex; + @Mock + TitanDao titanDao; + @Mock + VertexProperty property; + + @InjectMocks + private ToscaElementOperation toscaOperation = new TopologyTemplateOperation(); + + @Before + public void setUp() { + vertexList.add(vertex); + when(titanDao.getCatalogOrArchiveVerticies(true)).thenReturn(Either.left(vertexList.iterator())); + when(titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse)) + .thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(vertex.property(GraphPropertiesDictionary.METADATA.getProperty())).thenReturn(property); + } + + @Test + public void getComponentFromCatalogWhenDeleteIsTrue() { + final String vertexJsonIsDeletedTrue = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":true,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedTrue); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertTrue(componentList.isEmpty()); + } + + @Test + public void getComponentFromCatalogWhenDeleteNotFound() { + final String vertexJsonIsDeletedNotFound = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedNotFound); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertEquals(1, componentList.size()); + } + + @Test + public void getComponentFromCatalogWhenDeleteIsFalse() { + final String vertexJsonIsDeletedFalse = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":false,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedFalse); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertEquals(1, componentList.size()); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java index 054e71a83e..9f8d015a44 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java @@ -1,14 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -28,7 +20,10 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Created by chaya on 6/12/2017. @@ -42,10 +37,10 @@ public class ToscaElementOperationTest extends ModelTestBase{ private boolean isInitialized = false; @javax.annotation.Resource - ToscaElementOperationTestImpl toscaElementOperation; + private ToscaElementOperationTestImpl toscaElementOperation; @javax.annotation.Resource - TitanDao titanDao; + private TitanDao titanDao; @BeforeClass public static void initTest(){ @@ -271,7 +266,7 @@ public class ToscaElementOperationTest extends ModelTestBase{ } private void initGraphForTest() { - GraphTestUtils.createRootCatalogVertex(titanDao); + GraphTestUtils.createRootCatalogVertex(titanDao); Map highstVerticesProps = new HashMap() { { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java index da3ae71399..27fbce4776 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java @@ -1,5 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; +import fj.data.Either; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -8,8 +9,6 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; - /** * Created by cb478c on 6/13/2017. */ diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java index 9b31b0bfd7..05688304d1 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java @@ -1,16 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - +import fj.data.Either; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -19,12 +9,8 @@ import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.config.TitanSpringConfig; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.ModelTestBase; @@ -35,14 +21,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) public class ToscaOperationFacadePoliciesTest extends ModelTestBase { - private static final String CONTAINER_ID = "containerId"; - private static final String CONTAINER_NAME = "containerName"; @Autowired private ToscaOperationFacade toscaOperationFacade; @Autowired @@ -126,11 +119,7 @@ public class ToscaOperationFacadePoliciesTest extends ModelTestBase { } private void createContainerVertexInDB() { - GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); - resource.addMetadataProperty(GraphPropertyEnum.NAME, CONTAINER_NAME); - resource.setJsonMetadataField(JsonPresentationFields.NAME, CONTAINER_NAME); - resource.setJsonMetadataField(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + GraphVertex resource = createBasicContainerGraphVertex(); Either container = titanDao.createVertex(resource); assertTrue(container.isLeft()); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java index 46ef5f39f0..851800def8 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java @@ -1,19 +1,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +8,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; @@ -37,7 +24,17 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ToscaOperationFacadeTest { @@ -106,73 +103,73 @@ public class ToscaOperationFacadeTest { @Test public void associatePolicyToComponentSuccessTest(){ - Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK); - assertTrue(result.isLeft()); + Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK); + assertTrue(result.isLeft()); } - @Test + @Test public void associatePolicyToComponentFailureTest(){ - Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); + Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); } @Test public void updatePolicyOfComponentSuccessTest(){ - Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK); - assertTrue(result.isLeft()); + Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK); + assertTrue(result.isLeft()); } - @Test + @Test public void updatePolicyOfComponentFailureTest(){ - Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); + Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); } @Test public void removePolicyFromComponentSuccessTest(){ - removePolicyFromComponentWithStatus(StorageOperationStatus.OK); + removePolicyFromComponentWithStatus(StorageOperationStatus.OK); } @Test public void removePolicyFromComponentFailureTest(){ - removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND); + removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND); } private Either associatePolicyToComponentWithStatus(StorageOperationStatus status) { - PolicyDefinition policy = new PolicyDefinition(); - String componentId = "componentId"; - int counter = 0; - GraphVertex vertex; - if(status == StorageOperationStatus.OK){ - vertex = getTopologyTemplateVertex(); - } else { - vertex = getNodeTypeVertex(); - } - Either getVertexEither = Either.left(vertex); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither); - when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status); - return testInstance.associatePolicyToComponent(componentId, policy, counter); + PolicyDefinition policy = new PolicyDefinition(); + String componentId = "componentId"; + int counter = 0; + GraphVertex vertex; + if(status == StorageOperationStatus.OK){ + vertex = getTopologyTemplateVertex(); + } else { + vertex = getNodeTypeVertex(); + } + Either getVertexEither = Either.left(vertex); + when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither); + when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status); + return testInstance.associatePolicyToComponent(componentId, policy, counter); } private Either updatePolicyOfComponentWithStatus(StorageOperationStatus status) { - PolicyDefinition policy = new PolicyDefinition(); - String componentId = "componentId"; - GraphVertex vertex = getTopologyTemplateVertex(); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex)); - when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status); - return testInstance.updatePolicyOfComponent(componentId, policy); - } - - private void removePolicyFromComponentWithStatus(StorageOperationStatus status) { - String componentId = "componentId"; - String policyId = "policyId"; - GraphVertex vertex = getTopologyTemplateVertex(); - Either getVertexEither = Either.left(vertex); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither); - when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status); - StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId); - assertTrue(result == status); - } + PolicyDefinition policy = new PolicyDefinition(); + String componentId = "componentId"; + GraphVertex vertex = getTopologyTemplateVertex(); + when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex)); + when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status); + return testInstance.updatePolicyOfComponent(componentId, policy); + } + + private void removePolicyFromComponentWithStatus(StorageOperationStatus status) { + String componentId = "componentId"; + String policyId = "policyId"; + GraphVertex vertex = getTopologyTemplateVertex(); + Either getVertexEither = Either.left(vertex); + when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither); + when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status); + StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId); + assertSame(result, status); + } private List getMockVertices(int numOfVertices) { return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList()); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java new file mode 100644 index 0000000000..acb9af6a33 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java @@ -0,0 +1,183 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; +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.UserAdminOperation; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class UpgradeOperationTest extends ModelTestBase { + + private boolean isInitialized; + @Resource + private TitanDao titanDao; + @Resource + private UpgradeOperation upgradeOperation; + @Resource + private TopologyTemplateOperation topologyTemplateOperation; + @Resource + private NodeTemplateOperation nodeTemplateOperation; + @Resource + private UserAdminOperation userAdminOperation; + @javax.annotation.Resource + private IElementOperation elementOperation; + + private User user; + + private CategoryDefinition resourceCategory; + private CategoryDefinition serviceCategory; + + + @BeforeClass + public static void initTest() { + ModelTestBase.init(); + } + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(titanDao); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testGetSimpleDependency() { + + TopologyTemplate vf = createVf("vf1"); + + TopologyTemplate service = createServiceWitnInstance("service1", vf); + + + Either, StorageOperationStatus> result = upgradeOperation.getComponentDependencies(vf.getUniqueId()); + assertThat(result.isLeft()).isTrue(); + List dependencies = result.left().value(); + assertThat(dependencies).hasSize(1); + + ComponentDependency dependency = dependencies.get(0); + assertThat(dependency.getName()).isEqualTo(vf.getName()); + assertThat(dependency.getVersion()).isEqualTo(vf.getVersion()); + assertThat(dependency.getDependencies()).hasSize(1); + + ComponentDependency container = dependency.getDependencies().get(0); + assertThat(container.getName()).isEqualTo(service.getName()); + assertThat(container.getVersion()).isEqualTo(service.getVersion()); + assertThat(container.getDependencies()).isNull(); + + } + + /******************************* + * Preperation Methods + *******************************/ + private void initGraphForTest() { + + user = new User("Jim", "Tom", "jt123a", "1@mail.com", "DESIGNER", System.currentTimeMillis()); + Either saveUserData = userAdminOperation.saveUserData(user); + assertThat(saveUserData.isLeft()).isTrue(); + + GraphTestUtils.createRootCatalogVertex(titanDao); + resourceCategory = createResourceCategories(); + serviceCategory = createServiceCategory(); + + } + + private TopologyTemplate createServiceWitnInstance(String name, TopologyTemplate createdVf) { + + TopologyTemplate serviceNew = createTopologyTemplate(ComponentTypeEnum.SERVICE, name); + List categoriesService = new ArrayList<>(); + categoriesService.add(serviceCategory); + serviceNew.setCategories(categoriesService); + + Either createService = topologyTemplateOperation.createTopologyTemplate(serviceNew); + assertThat(createService.isLeft()).isTrue(); + + ComponentInstance vfInstance = new ComponentInstance(); + vfInstance.setUniqueId(createdVf.getUniqueId() + createdVf.getName()); + vfInstance.setComponentUid(createdVf.getUniqueId()); + vfInstance.setName(createdVf.getName()); + Either, StorageOperationStatus> addInstance = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(serviceNew, createdVf, "0", vfInstance, false, user); + assertThat(addInstance.isLeft()).isTrue(); + return serviceNew; + } + + private CategoryDefinition createServiceCategory() { + CategoryDefinition categoryService = new CategoryDefinition(); + categoryService.setName("servicecategory"); + categoryService.setNormalizedName("servicecategory"); + categoryService.setUniqueId("servicecategory"); + Either createCategory = elementOperation.createCategory(categoryService , NodeTypeEnum.ServiceNewCategory); + + assertThat(createCategory.isLeft()).isTrue(); + return categoryService; + } + + private TopologyTemplate createVf(String name) { + + TopologyTemplate resource = createTopologyTemplate(ComponentTypeEnum.RESOURCE, name); + + resource.setResourceType(ResourceTypeEnum.VF); + List categories = new ArrayList<>(); + categories.add(resourceCategory); + resource.setCategories(categories); + Either createVf = topologyTemplateOperation.createTopologyTemplate(resource); + assertThat( createVf.isLeft()).isTrue(); + return resource; + } + + private CategoryDefinition createResourceCategories() { + CategoryDefinition category = new CategoryDefinition(); + category.setName("category1"); + category.setNormalizedName("category1"); + category.setUniqueId("category1"); + Either createCategory = elementOperation.createCategory(category , NodeTypeEnum.ResourceNewCategory); + assertThat(createCategory.isLeft()).isTrue(); + + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + + subCategory.setName("subcategory1"); + subCategory.setNormalizedName("subcategory1"); + subCategory.setUniqueId("subcategory1"); + elementOperation.createSubCategory(createCategory.left().value().getUniqueId(), subCategory, NodeTypeEnum.ResourceSubcategory); + category.addSubCategory(subCategory); + return category; + } + + private TopologyTemplate createTopologyTemplate(ComponentTypeEnum type, String name) { + TopologyTemplate template = new TopologyTemplate(); + template.setUniqueId(IdBuilderUtils.generateUniqueId()); + template.setComponentType(type); + template.setHighestVersion(true); + template.setLifecycleState(LifecycleStateEnum.CERTIFIED); + template.setMetadataValue(JsonPresentationFields.NAME, name); + template.setMetadataValue(JsonPresentationFields.VERSION, "1.0"); + template.setCreatorUserId(user.getUserId()); + return template; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java index 72919b6136..71dd472a1c 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java @@ -20,14 +20,9 @@ package org.openecomp.sdc.be.model.jsontitan.utils; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.io.IoCore; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -38,18 +33,29 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; public final class GraphTestUtils { - public static void createRootCatalogVertex(TitanDao titanDao) { - GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); - catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - titanDao.createVertex(catalogRootVertex); - } + public static GraphVertex createRootCatalogVertex(TitanDao titanDao) { + GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); + catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); + return titanDao.createVertex(catalogRootVertex) + .either(v -> v, s -> null); + } + + public static GraphVertex createRootArchiveVertex(TitanDao titanDao) { + GraphVertex archiveRootVertex = new GraphVertex(VertexTypeEnum.ARCHIVE_ROOT); + archiveRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); + return titanDao.createVertex(archiveRootVertex) + .either(v -> v, s -> null); + } public static GraphVertex createResourceVertex(TitanDao titanDao, Map metadataProps, ResourceTypeEnum type) { GraphVertex vertex = new GraphVertex(); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java index 9a7ccc7f26..9d44232cd0 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.model.jsontitan.utils; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import org.junit.Test; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.Resource; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class InterfaceUtilsTest { private InterfaceUtils createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java index b3476529e8..a201b30fd9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java @@ -20,57 +20,56 @@ package org.openecomp.sdc.be.model.operations; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.ArrayList; - +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.UploadArtifactInfo; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.ArrayList; + +import static org.junit.Assert.assertEquals; public class JsonObjectTest { - private ObjectMapper mapper; - UploadResourceInfo inputObjectRef; - private final String INPUT_RESOURCE_STRING = "{ \"payloadData\" : \"My Test Object\", \"payloadName\" : \"TestName\", " + " \"description\":\"my_description\",\"tags\":[\"tag1\"], " - + "\"artifactList\" : [ { \"artifactName\" : \"myArtifact0\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", " + " \"artifactDescription\" : \"This is Description\", \"artifactData\" : null }, " - + "{ \"artifactName\" : \"myArtifact1\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", \"artifactDescription\" : \"This is Description\", " - + " \"artifactData\" : null } ], \"contactId\" : null, \"name\" : null, \"resourceIconPath\" : null, \"vendorName\" : null, \"vendorRelease\" : null , \"resourceType\" : \"VFC\" }"; + private ObjectMapper mapper; + UploadResourceInfo inputObjectRef; + private final String INPUT_RESOURCE_STRING = "{ \"payloadData\" : \"My Test Object\", \"payloadName\" : \"TestName\", " + " \"description\":\"my_description\",\"tags\":[\"tag1\"], " + + "\"artifactList\" : [ { \"artifactName\" : \"myArtifact0\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", " + " \"artifactDescription\" : \"This is Description\", \"artifactData\" : null }, " + + "{ \"artifactName\" : \"myArtifact1\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", \"artifactDescription\" : \"This is Description\", " + + " \"artifactData\" : null } ], \"contactId\" : null, \"name\" : null, \"resourceIconPath\" : null, \"vendorName\" : null, \"vendorRelease\" : null , \"resourceType\" : \"VFC\" }"; - @Before - public void setup() { - mapper = new ObjectMapper(); - ArrayList artifactList = new ArrayList(); - for (int i = 0; i < 2; i++) { - UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/", ArtifactTypeEnum.PUPPET, "This is Description"); - artifactList.add(artifactInfo); - } - ArrayList tags = new ArrayList<>(); - tags.add("tag1"); - inputObjectRef = new UploadResourceInfo("My Test Object", "TestName", "my_description", null, tags, artifactList); + @Before + public void setup() { + mapper = new ObjectMapper(); + ArrayList artifactList = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/", ArtifactTypeEnum.PUPPET, "This is Description"); + artifactList.add(artifactInfo); + } + ArrayList tags = new ArrayList<>(); + tags.add("tag1"); + inputObjectRef = new UploadResourceInfo("My Test Object", "TestName", "my_description", null, tags, artifactList); - } + } - @Test - public void testStringToUploadResourceInfo() throws JsonParseException, JsonMappingException, IOException { - UploadResourceInfo resourceObjectTest = mapper.readValue(INPUT_RESOURCE_STRING, UploadResourceInfo.class); - assertEquals(inputObjectRef, resourceObjectTest); + @Test + public void testStringToUploadResourceInfo() throws JsonParseException, JsonMappingException, IOException { + UploadResourceInfo resourceObjectTest = mapper.readValue(INPUT_RESOURCE_STRING, UploadResourceInfo.class); + assertEquals(inputObjectRef, resourceObjectTest); - } + } - // @Test - public void testUploadResourceInfoToString() throws JsonParseException, JsonMappingException, IOException { - String refAsString = mapper.writeValueAsString(inputObjectRef); - String unFormattedString = refAsString.replace("\n", "").replace("\t", "").replace(" ", ""); + // @Test + public void testUploadResourceInfoToString() throws JsonParseException, JsonMappingException, IOException { + String refAsString = mapper.writeValueAsString(inputObjectRef); + String unFormattedString = refAsString.replace("\n", "").replace("\t", "").replace(" ", ""); - assertEquals(unFormattedString, INPUT_RESOURCE_STRING.replace("\n", "").replace("\t", "").replace(" ", "")); + assertEquals(unFormattedString, INPUT_RESOURCE_STRING.replace("\n", "").replace("\t", "").replace(" ", "")); - } + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java index f68da59681..d59b810b9e 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertTrue; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -35,56 +33,59 @@ import org.openecomp.sdc.be.resources.data.UserData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class AdditionalInformationOperationTest extends ModelTestBase { - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; + private static String USER_ID = "muUserId"; + private static String CATEGORY_NAME = "category/mycategory"; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; - @javax.annotation.Resource(name = "additional-information-operation") - private IAdditionalInformationOperation additionalInformationOperation; + @javax.annotation.Resource(name = "additional-information-operation") + private IAdditionalInformationOperation additionalInformationOperation; - @Before - public void createUserAndCategory() { - deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); - } + } - @BeforeClass - public static void setupBeforeClass() { + @BeforeClass + public static void setupBeforeClass() { - ModelTestBase.init(); + ModelTestBase.init(); - } + } - @Test - public void testDummy() { + @Test + public void testDummy() { - assertTrue(additionalInformationOperation != null); + assertNotNull(additionalInformationOperation); - } + } - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); - return userData; - } + return userData; + } - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - } + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java new file mode 100644 index 0000000000..9a3c66689e --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java @@ -0,0 +1,197 @@ +package org.openecomp.sdc.be.model.operations.impl; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.model.AnnotationTypeDefinition; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.utils.TypeUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class AnnotationTypeOperationsTest extends ModelTestBase { + + static final String TYPE = "org.openecomp.annotations.source"; + static final String NEW_TYPE = "org.openecomp.annotations.Source"; + static final String DESCRIPTION = "description"; + static final String NEW_DESCRIPTION = "new description"; + + @Resource + private TitanGenericDao titanGenericDao; + + @Resource + private CommonTypeOperations commonTypeOperations; + + @Resource + private AnnotationTypeOperations annotationTypeOperations; + + private PropertyDefinition prop1, prop2; + private AnnotationTypeDefinition initialAnnotationDefinition; + + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + } + + @Before + public void initTestData() { + removeGraphVertices(titanGenericDao.getGraph()); + prop1 = createSimpleProperty("val1", "prop1", "string"); + } + + @After + public void tearDown() { + titanGenericDao.rollback(); + } + + @SuppressWarnings("unchecked") + @Test + public void testAddType() { + prepareInitialType(); + AnnotationTypeDefinition result = annotationTypeOperations.addType(initialAnnotationDefinition); + assertThat(result.getUniqueId()).isNotEmpty(); + assertThat(result) + .isEqualToComparingOnlyGivenFields(initialAnnotationDefinition, "description", "type"); + assertThat(result.getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type") + .containsExactlyInAnyOrder(prop1); + assertThat(result.isHighestVersion()).isTrue(); + } + + @Test + public void testGetLatestType_TypeDoesntExist_shouldReturnNull() { + AnnotationTypeDefinition latestType = annotationTypeOperations.getLatestType(TYPE); + assertThat(latestType).isNull(); + } + + @Test + public void testGetLatestType_TypeExists_shouldReturnIt() { + addAnnotationType(); + AnnotationTypeDefinition latestType = annotationTypeOperations.getLatestType(TYPE); + assertThat(latestType.getType()).isEqualTo(TYPE); + } + + public void addAnnotationType() { + prepareInitialType(); + annotationTypeOperations.addType(initialAnnotationDefinition); + titanGenericDao.commit(); + } + + @Test + public void compareTypes_same_shouldReturnTrue() { + AnnotationTypeDefinition type1 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + AnnotationTypeDefinition type2 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + assertThat(annotationTypeOperations.isSameType(type1, type2)).isTrue(); + } + + @Test + public void compareTypes_sameExceptVersions_shouldReturnTrue() { + AnnotationTypeDefinition type1 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + AnnotationTypeDefinition type2 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + type1.setVersion("1"); + type2.setVersion("2"); + assertThat(annotationTypeOperations.isSameType(type1, type2)).isTrue(); + } + + @Test + public void compareTypes_differentType_shouldReturnFalse() { + AnnotationTypeDefinition type1 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + AnnotationTypeDefinition type2 = buildAnnotationDefinition(DESCRIPTION, NEW_TYPE, prop1); + assertThat(annotationTypeOperations.isSameType(type1, type2)).isFalse(); + } + + @Test + public void compareTypes_differentDescription_shouldReturnFalse() { + AnnotationTypeDefinition type1 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + AnnotationTypeDefinition type2 = buildAnnotationDefinition(NEW_DESCRIPTION, TYPE, prop1); + assertThat(annotationTypeOperations.isSameType(type1, type2)).isFalse(); + } + + @Test + public void compareTypes_differentProperty_shouldReturnFalse() { + AnnotationTypeDefinition type1 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop1); + prop2 = createSimpleProperty("val2", "prop2", "string"); + AnnotationTypeDefinition type2 = buildAnnotationDefinition(DESCRIPTION, TYPE, prop2); + assertThat(annotationTypeOperations.isSameType(type1, type2)).isFalse(); + } + + @Test + public void testUpdateType_propertyAdded_shouldSucceed() { + addAnnotationType(); + prop2 = createSimpleProperty("val2", "prop2", "string"); + AnnotationTypeDefinition advancedDefinition = buildAnnotationDefinition(NEW_DESCRIPTION, TYPE, prop1, prop2); + AnnotationTypeDefinition updatedType = annotationTypeOperations.updateType(initialAnnotationDefinition, advancedDefinition); + assertThat(updatedType.getDescription()).isEqualTo(NEW_DESCRIPTION); + assertThat(updatedType.getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type") + .containsExactlyInAnyOrder(prop1, prop2); + } + + @Test + public void testUpdateType_propertyDefaultValueModification_shouldSucceed() { + addAnnotationType(); + prop2 = createSimpleProperty("val3", "prop1", "string"); + AnnotationTypeDefinition advancedDefinition = buildAnnotationDefinition(DESCRIPTION, TYPE, prop2); + AnnotationTypeDefinition updatedType = annotationTypeOperations.updateType(initialAnnotationDefinition, advancedDefinition); + assertThat(updatedType.getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type") + .containsExactlyInAnyOrder(prop2); + } + + @Test + public void testUpdateType_propertyDescriptionModification_shouldSucceed() { + addAnnotationType(); + prop2 = createSimpleProperty("val1", "prop1", "string"); + prop2.setDescription("bla"); + AnnotationTypeDefinition advancedDefinition = buildAnnotationDefinition(DESCRIPTION, TYPE, prop2); + AnnotationTypeDefinition updatedType = annotationTypeOperations.updateType(initialAnnotationDefinition, advancedDefinition); + assertThat(updatedType.getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type", "description") + .containsExactlyInAnyOrder(prop2); + } + + @Test(expected = StorageException.class) + public void testUpdateType_propertyTypeModification_shouldFail() { + addAnnotationType(); + prop2 = createSimpleProperty("val1", "prop1", "int"); + AnnotationTypeDefinition advancedDefinition = buildAnnotationDefinition(DESCRIPTION, TYPE, prop2); + annotationTypeOperations.updateType(initialAnnotationDefinition, advancedDefinition); + } + + @Test(expected = StorageException.class) + public void testUpdateType_propertyRemoved_shouldFail() { + addAnnotationType(); + prop2 = createSimpleProperty("val1", "prop2", "int"); + AnnotationTypeDefinition advancedDefinition = buildAnnotationDefinition(DESCRIPTION, TYPE, prop2); + annotationTypeOperations.updateType(initialAnnotationDefinition, advancedDefinition); + } + + private void prepareInitialType() { + initialAnnotationDefinition = buildAnnotationDefinition(DESCRIPTION, + TYPE, + prop1); + initialAnnotationDefinition.setVersion(TypeUtils.FIRST_CERTIFIED_VERSION_VERSION); + } + + private AnnotationTypeDefinition buildAnnotationDefinition(String description, String type, PropertyDefinition ... properties) { + AnnotationTypeDefinition annotationTypeDefinition = new AnnotationTypeDefinition(); + annotationTypeDefinition.setDescription(description); + annotationTypeDefinition.setType(type); + annotationTypeDefinition.setHighestVersion(true); + annotationTypeDefinition.setProperties(asList(properties)); + return annotationTypeDefinition; + } + +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java index cd4433a462..8e92549f4f 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java @@ -32,20 +32,12 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.HeatParameterData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.be.resources.data.*; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,7 +49,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -66,439 +58,346 @@ import static org.junit.Assert.assertTrue; @ContextConfiguration("classpath:application-context-test.xml") public class ArtifactOperationTest extends ModelTestBase { - private static final String ARTIFACT_NAME = "myHeatArtifact"; + private static final String ARTIFACT_NAME = "myHeatArtifact"; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; - @javax.annotation.Resource(name = "tosca-operation-facade") - private ToscaOperationFacade toscaOperationFacade; + @javax.annotation.Resource(name = "tosca-operation-facade") + private ToscaOperationFacade toscaOperationFacade; - @javax.annotation.Resource - private ArtifactOperation artifactOperation; + @javax.annotation.Resource + private ArtifactOperation artifactOperation; - private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class); - private static String RESOURCE_ID = "resourceId"; - private static String RESOURCE_ID_2 = "resourceId2"; + private static String RESOURCE_ID = "resourceId"; + private static String RESOURCE_ID_2 = "resourceId2"; - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; + private static String USER_ID = "muUserId"; + private static String CATEGORY_NAME = "category/mycategory"; - @BeforeClass - public static void setupBeforeClass() { + @BeforeClass + public static void setupBeforeClass() { - ModelTestBase.init(); - } + ModelTestBase.init(); + } - @Before - public void createUserAndCategory() { - deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); - } + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); + } - @Test - @Ignore - public void testAddArtifactToServiceVersionAndUUIDNotNull() { - CategoryDefinition category = new CategoryDefinition(); - category.setName(CATEGORY_NAME); + @Test + public void testCreateDeleteArtifactWithHeatParams() { - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); + List heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); - assertEquals("add informational artifact version : " + artifactInfo.getArtifactVersion(), "1", artifactInfo.getArtifactVersion()); + Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + assertTrue(removeArifact.isLeft()); - assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(), artifactInfo.getArtifactUUID()); + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterDelete.isRight()); - Either service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); + Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); - Map artifacts = service.left().value().getArtifacts(); - for (Map.Entry entry : artifacts.entrySet()) { - String artifactId = entry.getValue().getUniqueId(); - String description = entry.getValue().getDescription(); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + } - artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); - } - service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); + @Test + public void testUpdateArtifactWithHeatParams() { - artifacts = service.left().value().getArtifacts(); - assertEquals(0, artifacts.size()); + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - Either serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); + List heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); - assertTrue(byCriteria.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); - - toscaOperationFacade.deleteToscaComponent(serviceId); - - } - - @Test - @Ignore - public void testUpdateArtifactToServiceVersionNotChanged() { - CategoryDefinition category = new CategoryDefinition(); - category.setName(CATEGORY_NAME); - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); - - ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); - - String version = artifactInfo.getArtifactVersion(); - String artUuid = artifactInfo.getArtifactUUID(); - assertEquals("add informational artifact version : " + version, "1", version); - - artifactInfo.setDescription("jghlsk new desfnjdh"); - - Either artifact = artifactOperation.updateArifactOnResource(artifactInfo, serviceId, artifactInfo.getUniqueId(), NodeTypeEnum.Service, false); - String newVersion = artifact.left().value().getArtifactVersion(); - String newArtUuid = artifactInfo.getArtifactUUID(); - assertEquals("add informational artifact version : " + newVersion, newVersion, version); - assertEquals("add informational artifact uuid : " + newArtUuid, newArtUuid, artUuid); - - Either service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); - - Map artifacts = service.left().value().getArtifacts(); - for (Map.Entry entry : artifacts.entrySet()) { - String artifactId = entry.getValue().getUniqueId(); - String description = entry.getValue().getDescription(); - - artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); - } - service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); - - artifacts = service.left().value().getArtifacts(); - assertEquals(0, artifacts.size()); - - Either serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); - - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); - assertTrue(byCriteria.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); - - toscaOperationFacade.deleteToscaComponent(serviceAfterSave.getUniqueId()); - - } - - @Test - public void testCreateDeleteArtifactWithHeatParams() { - - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - - List heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNode.isLeft()); - - Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - assertTrue(removeArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(artifactAfterDelete.isRight()); - - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isRight()); - - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - } - - @Test - public void testUpdateArtifactWithHeatParams() { - - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - - List heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNode.isLeft()); - - // update to artifact without params - ArtifactDefinition artifactNoParams = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); - artifactNoParams.setUniqueId(artifactWithHeat.getUniqueId()); - artifactNoParams.setArtifactType("HEAT"); - artifactNoParams.setArtifactVersion("2"); - artifactNoParams.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - Either updateArifact = artifactOperation.updateArifactOnResource(artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); - assertTrue(updateArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(artifactAfterUpdate.isLeft()); - ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); - assertTrue(artifactNoParams.getArtifactVersion().equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion())); - - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isRight()); - - artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); - } - - @Test - public void testUpdateArtifactMetadataWithHeatParams() { - - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - - List heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNode.isLeft()); - - // update to artifact without params - artifactWithHeat.setArtifactVersion("2"); - artifactWithHeat.setArtifactChecksum(null); - artifactWithHeat.setPayloadData(null); - - Either updateArifact = artifactOperation.updateArifactOnResource(artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); - assertTrue(updateArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(artifactAfterUpdate.isLeft()); - ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); - assertTrue(artifactWithHeat.getArtifactVersion().equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion())); - - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isLeft()); - - Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); - removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); - - } - - @Test - public void updateHeatArtifactWithTwoResources() { - ArtifactDefinition artifactWithHeat = createResourceWithHeat(); - - ResourceMetadataData resource2 = createResource(RESOURCE_ID_2); - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); - Either createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); - assertTrue(createRelation.isLeft()); - - List heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNode.isLeft()); - - ArtifactDefinition atifactToUpdate = new ArtifactDefinition(artifactWithHeat); - - // update to artifact without params - atifactToUpdate.setArtifactVersion("2"); - atifactToUpdate.setArtifactChecksum(null); - atifactToUpdate.setPayloadData(null); - - HeatParameterDefinition heatParamUpdate = new HeatParameterDefinition(parameter); - List heatParametersUpdated = new ArrayList(); - heatParamUpdate.setCurrentValue("55"); - heatParametersUpdated.add(heatParamUpdate); - atifactToUpdate.setListHeatParameters(heatParametersUpdated); - - Either updateArifact = artifactOperation.updateArifactOnResource(atifactToUpdate, RESOURCE_ID_2, atifactToUpdate.getUniqueId(), NodeTypeEnum.Resource, false); - assertTrue(updateArifact.isLeft()); - - // verify old artifact and parameter still exist - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(origArtifact.isLeft()); - ArtifactData origArtifactData = origArtifact.left().value(); - assertTrue(artifactWithHeat.getArtifactVersion().equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion())); - - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isLeft()); - - // verify new artifact and new parameter - ArtifactDefinition artifactDefinitionUpdated = updateArifact.left().value(); - ArtifactData artifactDataUpdated = new ArtifactData(artifactDefinitionUpdated); - Either updatedArtifact = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); - assertTrue(updatedArtifact.isLeft()); - ArtifactData updatedArtifactData = updatedArtifact.left().value(); - assertTrue(atifactToUpdate.getArtifactVersion().equals(updatedArtifactData.getArtifactDataDefinition().getArtifactVersion())); - assertFalse(((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId())); - - List heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters(); - assertNotNull(heatParametersAfterUpdate); - assertTrue(heatParametersAfterUpdate.size() == 1); - HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); - assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); - Either parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterUpdate.isLeft()); - - // delete new artifact - Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, artifactDefinitionUpdated.getUniqueId(), NodeTypeEnum.Resource, true, false); - assertTrue(removeArifact.isLeft()); - - // verify old artifact and parameter still exist - origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(origArtifact.isLeft()); - origArtifactData = origArtifact.left().value(); - assertTrue(artifactWithHeat.getArtifactVersion().equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion())); - - parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isLeft()); - - // verify new artifact is deleted - Either artifactAfterDelete = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); - assertTrue(artifactAfterDelete.isRight()); - - parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isRight()); - - artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); - } - - private ArtifactDefinition createResourceWithHeat() { - ResourceMetadataData resource = createResource(RESOURCE_ID); - ArtifactDefinition artifactDefinition = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); - artifactDefinition.setArtifactType("HEAT"); - artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - List heatParams = new ArrayList(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactDefinition.setListHeatParameters(heatParams); - - Either artifact = artifactOperation.addArifactToComponent(artifactDefinition, RESOURCE_ID, NodeTypeEnum.Resource, true, false); - assertTrue(artifact.isLeft()); - ArtifactDefinition artifactWithHeat = artifact.left().value(); - return artifactWithHeat; - } - - private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { - ArtifactDefinition artifactInfo = createArtifactDefinition(userId, serviceId, artifactName); - - Either artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); - assertTrue(artifact.isLeft()); - return artifact.left().value(); - } - - private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".sh"); - artifactInfo.setArtifactType("SHELL"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(artifactName); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); - return artifactInfo; - } - - public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion, boolean isHighestVersion) { - - Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); - - service.setHighestVersion(isHighestVersion); - - Either result = toscaOperationFacade.createToscaComponent(service); - - log.info(result.toString()); - assertTrue(result.isLeft()); - Service resultService = result.left().value(); - - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState()); - - return resultService; - } - - private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName, String serviceVersion) { - - Service service = new Service(); - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setDescription("description 1"); - - service.setCreatorUserId(userId); - service.setContactId("contactId@sdc.com"); - List categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - service.setTags(tags); - return service; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - if (role != null && !role.isEmpty()) { - userData.setRole(role); - } else { - userData.setRole("ADMIN"); - } - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } - - public ResourceMetadataData createResource(String resourceName) { - - ResourceMetadataData serviceData1 = new ResourceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); - Either createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class); - - assertTrue("check resource created", createNode.isLeft()); - return createNode.left().value(); - } + // update to artifact without params + ArtifactDefinition artifactNoParams = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + artifactNoParams.setUniqueId(artifactWithHeat.getUniqueId()); + artifactNoParams.setArtifactType("HEAT"); + artifactNoParams.setArtifactVersion("2"); + artifactNoParams.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + Either updateArifact = artifactOperation.updateArifactOnResource(artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertEquals(artifactNoParams.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() + .getArtifactVersion()); + + Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); + + artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + } + + @Test + public void testUpdateArtifactMetadataWithHeatParams() { + + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + List heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + // update to artifact without params + artifactWithHeat.setArtifactVersion("2"); + artifactWithHeat.setArtifactChecksum(null); + artifactWithHeat.setPayloadData(null); + + Either updateArifact = artifactOperation.updateArifactOnResource(artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertEquals(artifactWithHeat.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() + .getArtifactVersion()); + + Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); + removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + + } + + @Test + public void updateHeatArtifactWithTwoResources() { + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + ResourceMetadataData resource2 = createResource(RESOURCE_ID_2); + Map props = new HashMap<>(); + props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); + Either createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); + assertTrue(createRelation.isLeft()); + + List heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + ArtifactDefinition atifactToUpdate = new ArtifactDefinition(artifactWithHeat); + + // update to artifact without params + atifactToUpdate.setArtifactVersion("2"); + atifactToUpdate.setArtifactChecksum(null); + atifactToUpdate.setPayloadData(null); + + HeatParameterDefinition heatParamUpdate = new HeatParameterDefinition(parameter); + List heatParametersUpdated = new ArrayList<>(); + heatParamUpdate.setCurrentValue("55"); + heatParametersUpdated.add(heatParamUpdate); + atifactToUpdate.setListHeatParameters(heatParametersUpdated); + + Either updateArifact = artifactOperation.updateArifactOnResource(atifactToUpdate, RESOURCE_ID_2, atifactToUpdate.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + // verify old artifact and parameter still exist + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(origArtifact.isLeft()); + ArtifactData origArtifactData = origArtifact.left().value(); + assertEquals(artifactWithHeat.getArtifactVersion(), origArtifactData.getArtifactDataDefinition() + .getArtifactVersion()); + + Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + // verify new artifact and new parameter + ArtifactDefinition artifactDefinitionUpdated = updateArifact.left().value(); + ArtifactData artifactDataUpdated = new ArtifactData(artifactDefinitionUpdated); + Either updatedArtifact = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + assertTrue(updatedArtifact.isLeft()); + ArtifactData updatedArtifactData = updatedArtifact.left().value(); + assertEquals(atifactToUpdate.getArtifactVersion(), updatedArtifactData.getArtifactDataDefinition() + .getArtifactVersion()); + assertFalse(((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId())); + + List heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters(); + assertNotNull(heatParametersAfterUpdate); + assertEquals(1, heatParametersAfterUpdate.size()); + HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); + assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); + Either parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterUpdate.isLeft()); + + // delete new artifact + Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, artifactDefinitionUpdated.getUniqueId(), NodeTypeEnum.Resource, true, false); + assertTrue(removeArifact.isLeft()); + + // verify old artifact and parameter still exist + origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(origArtifact.isLeft()); + origArtifactData = origArtifact.left().value(); + assertEquals(artifactWithHeat.getArtifactVersion(), origArtifactData.getArtifactDataDefinition() + .getArtifactVersion()); + + parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + // verify new artifact is deleted + Either artifactAfterDelete = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterDelete.isRight()); + + parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); + + artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + } + + private ArtifactDefinition createResourceWithHeat() { + ResourceMetadataData resource = createResource(RESOURCE_ID); + ArtifactDefinition artifactDefinition = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + artifactDefinition.setArtifactType("HEAT"); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + List heatParams = new ArrayList<>(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactDefinition.setListHeatParameters(heatParams); + + Either artifact = artifactOperation.addArifactToComponent(artifactDefinition, RESOURCE_ID, NodeTypeEnum.Resource, true, false); + assertTrue(artifact.isLeft()); + return artifact.left().value(); + } + + private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = createArtifactDefinition(userId, serviceId, artifactName); + + Either artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); + assertTrue(artifact.isLeft()); + return artifact.left().value(); + } + + private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".sh"); + artifactInfo.setArtifactType("SHELL"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + artifactInfo.setUserIdCreator(userId); + String fullName = "Jim H"; + artifactInfo.setUpdaterFullName(fullName); + long time = System.currentTimeMillis(); + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(userId); + artifactInfo.setArtifactLabel(artifactName); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); + return artifactInfo; + } + + public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion, boolean isHighestVersion) { + + Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); + + service.setHighestVersion(isHighestVersion); + + Either result = toscaOperationFacade.createToscaComponent(service); + + log.info(result.toString()); + assertTrue(result.isLeft()); + Service resultService = result.left().value(); + + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState()); + + return resultService; + } + + private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName, String serviceVersion) { + + Service service = new Service(); + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setDescription("description 1"); + + service.setCreatorUserId(userId); + service.setContactId("contactId@sdc.com"); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setIcon("images/my.png"); + List tags = new ArrayList<>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + return service; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + if (role != null && !role.isEmpty()) { + userData.setRole(role); + } else { + userData.setRole("ADMIN"); + } + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + public ResourceMetadataData createResource(String resourceName) { + + ResourceMetadataData serviceData1 = new ResourceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); + Either createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class); + + assertTrue("check resource created", createNode.isLeft()); + return createNode.left().value(); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java index 79af87bc10..79c2d9bf43 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java @@ -20,12 +20,19 @@ package org.openecomp.sdc.be.model.operations.impl; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.PropertyConstraint; @@ -35,246 +42,465 @@ import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.CapabilityTypeData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class CapabilityTypeOperationTest extends ModelTestBase { - @Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; - @Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; + @Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; - @BeforeClass - public static void setupBeforeClass() { - ModelTestBase.init(); + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + } + + @Before + public void cleanUp() { + TitanGenericDao titanGenericDao = capabilityTypeOperation.titanGenericDao; + Either graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); - } + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } - @Test - public void testDummy() { + } + titanGenericDao.commit(); + } - assertTrue(capabilityTypeOperation != null); + @Test + public void testDummy() { + assertNotNull(capabilityTypeOperation); + } - } + @Test + public void testAddCapabilityType() { - @Test - public void testAddCapabilityType() { + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType("tosca.capabilities.Container1"); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setDescription("desc1"); - capabilityTypeDefinition.setType("tosca.capabilities.Container1"); + Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertTrue("check capability type added", addCapabilityType1.isLeft()); - Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - assertEquals("check capability type added", true, addCapabilityType1.isLeft()); + CapabilityTypeDefinition capabilityTypeAdded = addCapabilityType1.left().value(); + compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded); - CapabilityTypeDefinition capabilityTypeAdded = addCapabilityType1.left().value(); - compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded); + Either capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); + compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); - Either capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); - compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); + Either addCapabilityType2 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertTrue("check capability type failed", addCapabilityType2.isRight()); + assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION, addCapabilityType2.right().value()); - Either addCapabilityType2 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - assertEquals("check capability type failed", true, addCapabilityType2.isRight()); - assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION, addCapabilityType2.right().value()); + } - } + @Test + public void testAddDerviedCapabilityType() { - @Test - public void testAddDerviedCapabilityType() { + CapabilityTypeDefinition capabilityTypeDefinition = createCapabilityTypeDef("tosca.capabilities.Container2", "desc1", "derivedFrom"); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setDescription("desc1"); - capabilityTypeDefinition.setType("tosca.capabilities.Container2"); - capabilityTypeDefinition.setDerivedFrom("derivedFrom"); + Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertEquals("check capability type parent not exist", StorageOperationStatus.NOT_FOUND, addCapabilityType1.right().value()); + } - Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - assertEquals("check capability type parent not exist", StorageOperationStatus.INVALID_ID, addCapabilityType1.right().value()); - } + public CapabilityTypeDefinition createCapability(String capabilityTypeName) { - public CapabilityTypeDefinition createCapability(String capabilityTypeName) { + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType(capabilityTypeName); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setDescription("desc1"); - capabilityTypeDefinition.setType(capabilityTypeName); + Map properties = new HashMap<>(); - Map properties = new HashMap(); + String propName1 = "disk_size"; + String propName2 = "num_cpus"; - String propName1 = "disk_size"; - String propName2 = "num_cpus"; + PropertyDefinition property1 = buildProperty1(); - PropertyDefinition property1 = buildProperty1(); + properties.put(propName1, property1); - properties.put(propName1, property1); + PropertyDefinition property2 = buildProperty2(); - PropertyDefinition property2 = buildProperty2(); + properties.put(propName2, property2); - properties.put(propName2, property2); + capabilityTypeDefinition.setProperties(properties); - capabilityTypeDefinition.setProperties(properties); + Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true); + assertTrue("check capability type fetched", capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); - CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); - Either capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true); - assertEquals("check capability type fetched", true, capabilityType.isLeft()); - CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + Map fetchedProps = fetchedCTD.getProperties(); - Map fetchedProps = fetchedCTD.getProperties(); + compareProperties(fetchedProps, properties); - compareProperties(fetchedProps, properties); + return fetchedCTD; - return fetchedCTD; + } - } + @Test + public void testAddCapabilityTypeWithProperties() { - @Test - public void testAddCapabilityTypeWithProperties() { + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType("tosca.capabilities.Container3"); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setDescription("desc1"); - capabilityTypeDefinition.setType("tosca.capabilities.Container3"); + Map properties = new HashMap<>(); - Map properties = new HashMap(); + String propName1 = "disk_size"; + String propName2 = "num_cpus"; - String propName1 = "disk_size"; - String propName2 = "num_cpus"; + PropertyDefinition property1 = buildProperty1(); - PropertyDefinition property1 = buildProperty1(); + properties.put(propName1, property1); - properties.put(propName1, property1); + PropertyDefinition property2 = buildProperty2(); - PropertyDefinition property2 = buildProperty2(); + properties.put(propName2, property2); - properties.put(propName2, property2); + capabilityTypeDefinition.setProperties(properties); - capabilityTypeDefinition.setProperties(properties); + Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId()); + assertTrue("check capability type fetched", capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); - CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); - Either capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId()); - assertEquals("check capability type fetched", true, capabilityType.isLeft()); - CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + Map fetchedProps = fetchedCTD.getProperties(); - Map fetchedProps = fetchedCTD.getProperties(); + compareProperties(fetchedProps, properties); + } - compareProperties(fetchedProps, properties); - } + private void compareProperties(Map first, Map second) { - private void compareProperties(Map first, Map second) { + assertTrue("check properties are full or empty", ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertEquals("check properties size", first.size(), second.size()); - assertTrue("check properties are full or empty", ((first == null && second == null) || (first != null && second != null))); - if (first != null) { - assertEquals("check properties size", first.size(), second.size()); + for (Entry entry : first.entrySet()) { - for (Entry entry : first.entrySet()) { + String propName = entry.getKey(); + PropertyDefinition secondPD = second.get(propName); + assertNotNull("Cannot find property " + propName + " in " + second, secondPD); - String propName = entry.getKey(); - PropertyDefinition secondPD = second.get(propName); - assertNotNull("Cannot find property " + propName + " in " + second, secondPD); + PropertyDefinition firstPD = entry.getValue(); - PropertyDefinition firstPD = entry.getValue(); + comparePropertyDefinition(firstPD, secondPD); + } - comparePropertyDefinition(firstPD, secondPD); - } + } - } + } - } + @Test + public void testGetCapabilityTypeNotFound() { - @Test - public void testGetCapabilityTypeNotFound() { + Either capabilityType = capabilityTypeOperation.getCapabilityType("not_exists"); + assertEquals("check not found is returned", StorageOperationStatus.NOT_FOUND, capabilityType.right().value()); - Either capabilityType = capabilityTypeOperation.getCapabilityType("not_exists"); - assertEquals("check not found is returned", StorageOperationStatus.NOT_FOUND, capabilityType.right().value()); + } + + + + @Test + public void updateCapabilityType_returnNotFoundErrorIfTryingToUpdateANonExistingType() { + CapabilityTypeDefinition currType = createCapabilityTypeDef(); + CapabilityTypeDefinition updatedType = createCapabilityTypeDef(); + Either updateCapabilityTypeRes = capabilityTypeOperation.updateCapabilityType(updatedType, currType); + assertThat(updateCapabilityTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + } - } + @Test + public void updateCapabilityType_basicFields() { + CapabilityTypeDefinition createdType = createCapabilityTypeDef("type1", "description1"); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(createdType); - private void comparePropertyDefinition(PropertyDefinition first, PropertyDefinition second) { + CapabilityTypeDefinition updatedType = createCapabilityTypeDef("type1", "description2"); + capabilityTypeOperation.updateCapabilityType(updatedType, currCapabilityType.left().value()); - assertTrue("check objects are full or empty", ((first == null && second == null) || (first != null && second != null))); - if (first != null) { - assertTrue("check property default value", compareValue(first.getDefaultValue(), second.getDefaultValue())); - assertTrue("check property description", compareValue(first.getDescription(), second.getDescription())); - assertTrue("check property type", compareValue(first.getType(), second.getType())); - compareList(first.getConstraints(), second.getConstraints()); - } + Either fetchedUpdatedType = capabilityTypeOperation.getCapabilityType(createdType.getType()); + CapabilityTypeDefinition fetchedCapabilityType = fetchedUpdatedType.left().value(); + assertThat(fetchedCapabilityType.getProperties()).isNullOrEmpty(); + assertThat(fetchedCapabilityType.getDerivedFrom()).isNullOrEmpty(); + assertEquals(fetchedCapabilityType.getCreationTime(), updatedType.getCreationTime()); + assertEquals(fetchedCapabilityType.getType(), updatedType.getType()); + assertEquals(fetchedCapabilityType.getDescription(), updatedType.getDescription()); + assertEquals(fetchedCapabilityType.getValidSourceTypes(), updatedType.getValidSourceTypes()); + assertEquals(fetchedCapabilityType.getVersion(), updatedType.getVersion()); + } - } - - private void compareList(List first, List second) { - - assertTrue("check lists are full or empty", ((first == null && second == null) || (first != null && second != null))); - if (first != null) { - assertEquals("check list size", first.size(), second.size()); - } - } - - private PropertyDefinition buildProperty2() { - PropertyDefinition property2 = new PropertyDefinition(); - property2.setDefaultValue("2"); - property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); - property2.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints3 = new ArrayList(); - List range = new ArrayList(); - range.add("1"); - range.add("4"); - - InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); - constraints3.add(propertyConstraint3); - // property2.setConstraints(constraints3); - property2.setConstraints(constraints3); - return property2; - } - - private PropertyDefinition buildProperty1() { - PropertyDefinition property1 = new PropertyDefinition(); - property1.setDefaultValue("10"); - property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property1.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - constraints.add(propertyConstraint1); - - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - constraints.add(propertyConstraint2); - - property1.setConstraints(constraints); - return property1; - } - - private void compareBetweenCreatedToSent(CapabilityTypeDefinition x, CapabilityTypeDefinition y) { - - assertTrue(compareValue(x.getDerivedFrom(), y.getDerivedFrom())); - assertTrue(compareValue(x.getType(), y.getType())); - assertTrue(compareValue(x.getDescription(), y.getDescription())); - - } - - public boolean compareValue(String first, String second) { - - if (first == null && second == null) { - return true; - } - if (first != null) { - return first.equals(second); - } else { - return false; - } - } + @Test + public void updateCapabilityType_updatePropertiesFailedDueTypeChange() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + CapabilityTypeDefinition capabilityType = createCapabilityTypeDef(asMap(prop1)); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(updatedProp1, prop3)); + + Either updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertTrue(updatedCapabilityTypeRes.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedCapabilityTypeRes.right().value()); + + Either fetchedUpdatedType = capabilityTypeOperation.getCapabilityType(capabilityType.getType()); + assertEquals(fetchedUpdatedType.left().value().getProperties(), asMap(prop1)); + + } + + @Test + public void updateCapabilityType_updatePropertiesFailedDueDeletedProp() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + CapabilityTypeDefinition capabilityType = createCapabilityTypeDef(asMap(prop1)); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(prop3)); + + Either updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertTrue(updatedCapabilityTypeRes.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedCapabilityTypeRes.right().value()); + + Either fetchedUpdatedType = capabilityTypeOperation.getCapabilityType(capabilityType.getType()); + assertEquals(fetchedUpdatedType.left().value().getProperties(), asMap(prop1)); + + } + + @Test + public void updateCapabilityType_updateProperties() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + CapabilityTypeDefinition capabilityType = createCapabilityTypeDef(asMap(prop1)); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "string"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(updatedProp1, prop3)); + + Either updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + assertTrue(updatedCapabilityTypeRes.isLeft()); + + Either fetchedUpdatedType = capabilityTypeOperation.getCapabilityType(capabilityType.getType()); + assertEquals(fetchedUpdatedType.left().value().getProperties(), asMap(updatedProp1, prop3)); + + } + + @Test + public void updateCapabilityType_derivedFrom_whenNoPrevDerivedFrom_updateToNewDerivedFrom() { + CapabilityTypeDefinition rootCapabilityType = createCapabilityTypeDef(); + CapabilityTypeDefinition capabilityType1 = createCapabilityTypeDef("type1", "descr"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef("type1", "descr", rootCapabilityType.getType()); + capabilityTypeOperation.addCapabilityType(rootCapabilityType); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + Either latestCapabilityType = capabilityTypeOperation.getCapabilityType(capabilityType1.getType()); + assertThat(latestCapabilityType.left().value().getDerivedFrom()).isEqualTo(rootCapabilityType.getType()); + verifyDerivedFromNodeEqualsToRootCapabilityType(rootCapabilityType, latestCapabilityType.left().value().getUniqueId()); + } + + @Test + public void updateCapabilityType_derivedFrom_updateToNullDerivedFrom_Failed() { + CapabilityTypeDefinition rootCapabilityType = createCapabilityTypeDef(); + CapabilityTypeDefinition capabilityType1 = createCapabilityTypeDef("type1", "descr", rootCapabilityType.getType()); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef("type1", "descr", null, new HashMap<>()); + capabilityTypeOperation.addCapabilityType(rootCapabilityType); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + Either updateRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertThat(updateRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + + Either latestCapabilityType = capabilityTypeOperation.getCapabilityType(capabilityType1.getType()); + assertThat(latestCapabilityType.left().value().getDerivedFrom()).isEqualTo(rootCapabilityType.getType()); + } + + @Test + public void updateCapabilityType_updateDerivedFrom() { + CapabilityTypeDefinition rootCapabilityType = createCapabilityTypeDef(); + CapabilityTypeDefinition derivedType1 = createCapabilityTypeDef("derivedType1", "descr", rootCapabilityType.getType()); + CapabilityTypeDefinition capabilityType1 = createCapabilityTypeDef("type1", "descr", rootCapabilityType.getType()); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef("type1", "descr", derivedType1.getType()); + + capabilityTypeOperation.addCapabilityType(rootCapabilityType); + capabilityTypeOperation.addCapabilityType(derivedType1); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + Either latestCapabilityType = capabilityTypeOperation.getCapabilityType(capabilityType1.getType()); + assertThat(latestCapabilityType.left().value().getDerivedFrom()).isEqualTo(derivedType1.getType()); + verifyDerivedFromNodeEqualsToRootCapabilityType(derivedType1, latestCapabilityType.left().value().getUniqueId()); + } + + @Test + public void updateCapabilityType_updateDerivedFrom_Failed_NewParentIsNotChildOfOldOne() { + CapabilityTypeDefinition rootCapabilityType = createCapabilityTypeDef(); + CapabilityTypeDefinition notDerivedType = createCapabilityTypeDef("derivedType1", "descr"); + CapabilityTypeDefinition capabilityType1 = createCapabilityTypeDef("type1", "descr", rootCapabilityType.getType()); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef("type1", "descr", notDerivedType.getType()); + + capabilityTypeOperation.addCapabilityType(rootCapabilityType); + capabilityTypeOperation.addCapabilityType(notDerivedType); + Either currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + Either result = capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + assertThat(result.right().value()).isEqualTo(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY); + + Either latestCapabilityType = capabilityTypeOperation.getCapabilityType(capabilityType1.getType()); + assertThat(latestCapabilityType.left().value().getDerivedFrom()).isEqualTo(rootCapabilityType.getType()); + verifyDerivedFromNodeEqualsToRootCapabilityType(rootCapabilityType, latestCapabilityType.left().value().getUniqueId()); + } + + private CapabilityTypeDefinition createCapabilityTypeDef() { + return createCapabilityTypeDef("tosca.capabilities.Root", "The TOSCA root Capability Type all other TOSCA base Capability Types derived from", null, new HashMap<>()); + } + + private CapabilityTypeDefinition createCapabilityTypeDef(Map properties) { + return createCapabilityTypeDef("tosca.capabilities.Root", + "The TOSCA root Capability Type all other TOSCA base Capability Types derived from", null, properties); + } + + private CapabilityTypeDefinition createCapabilityTypeDef(String type, String description) { + return createCapabilityTypeDef(type, description, null, null); + } + + private CapabilityTypeDefinition createCapabilityTypeDef(String type, String description, String derivedFrom) { + return createCapabilityTypeDef(type, description, derivedFrom, null); + } + + + private CapabilityTypeDefinition createCapabilityTypeDef(String type, String description, String derivedFrom, Map properties) { + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription(description); + capabilityTypeDefinition.setType(type); + capabilityTypeDefinition.setDerivedFrom(derivedFrom); + capabilityTypeDefinition.setVersion("1.0"); + capabilityTypeDefinition.setValidSourceTypes(null); + if (properties != null) { + capabilityTypeDefinition.setProperties(properties); + } + return capabilityTypeDefinition; + } + + private PropertyDefinition duplicateProperty(PropertyDefinition prop1, String updatedValue, String updatedType) { + PropertyDefinition updatedProp1 = new PropertyDefinition(prop1); + updatedProp1.setDefaultValue(updatedValue); + updatedProp1.setType(updatedType); + return updatedProp1; + } + + private static Map asMap(PropertyDefinition ... props) { + return Stream.of(props).collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + } + + private void verifyDerivedFromNodeEqualsToRootCapabilityType(CapabilityTypeDefinition rootCapabilityType, String parentCapabilityId) { + Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), parentCapabilityId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + assertThat(derivedFromRelation.left().value().getLeft().getCapabilityTypeDataDefinition()) + .isEqualToComparingFieldByField(rootCapabilityType); + } + + + private void comparePropertyDefinition(PropertyDefinition first, PropertyDefinition second) { + + assertTrue("check objects are full or empty", ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertTrue("check property default value", compareValue(first.getDefaultValue(), second.getDefaultValue())); + assertTrue("check property description", compareValue(first.getDescription(), second.getDescription())); + assertTrue("check property type", compareValue(first.getType(), second.getType())); + compareList(first.getConstraints(), second.getConstraints()); + } + + } + + private void compareList(List first, List second) { + + assertTrue("check lists are full or empty", ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertEquals("check list size", first.size(), second.size()); + } + } + + private PropertyDefinition buildProperty2() { + PropertyDefinition property2 = new PropertyDefinition(); + property2.setDefaultValue("2"); + property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); + property2.setType(ToscaType.INTEGER.name().toLowerCase()); + List constraints3 = new ArrayList<>(); + List range = new ArrayList<>(); + range.add("1"); + range.add("4"); + + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints3.add(propertyConstraint3); + // property2.setConstraints(constraints3); + property2.setConstraints(constraints3); + return property2; + } + + private PropertyDefinition buildProperty1() { + PropertyDefinition property1 = new PropertyDefinition(); + property1.setDefaultValue("10"); + property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property1.setType(ToscaType.INTEGER.name().toLowerCase()); + List constraints = new ArrayList<>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + constraints.add(propertyConstraint1); + + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + constraints.add(propertyConstraint2); + + property1.setConstraints(constraints); + return property1; + } + + private void compareBetweenCreatedToSent(CapabilityTypeDefinition x, CapabilityTypeDefinition y) { + assertTrue(compareValue(x.getDerivedFrom(), y.getDerivedFrom())); + assertTrue(compareValue(x.getType(), y.getType())); + assertTrue(compareValue(x.getDescription(), y.getDescription())); + + } + + private boolean compareValue(String first, String second) { + + if (first == null && second == null) { + return true; + } + if (first != null) { + return first.equals(second); + } else { + return false; + } + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java index 321bc422af..4e97dc58e5 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java @@ -1,12 +1,11 @@ package org.openecomp.sdc.be.model.operations.impl; +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; - public class ComponentInstanceOperationTest { private ComponentInstanceOperation createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java index b28641cba5..9b2a5d93c9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.T; import org.junit.BeforeClass; import org.junit.Test; @@ -48,53 +42,58 @@ import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class ElementOperationTest extends ModelTestBase { - @javax.annotation.Resource(name = "element-operation") - private ElementOperation elementOperation; + @javax.annotation.Resource(name = "element-operation") + private ElementOperation elementOperation; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; - private static String CATEGORY = "category"; - private static String SUBCATEGORY = "subcategory"; + private static String CATEGORY = "category"; + private static String SUBCATEGORY = "subcategory"; - @BeforeClass - public static void setupBeforeClass() { - // ExternalConfiguration.setAppName("catalog-model"); - // String appConfigDir = "src/test/resources/config/catalog-model"; - // ConfigurationSource configurationSource = new - // FSConfigurationSource(ExternalConfiguration.getChangeListener(), - // appConfigDir); + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); - ModelTestBase.init(); + ModelTestBase.init(); - } + } - @Test - public void testGetArtifactsTypes() { + @Test + public void testGetArtifactsTypes() { - List artifactTypesCfg = new ArrayList(); - artifactTypesCfg.add("type1"); - artifactTypesCfg.add("type2"); - artifactTypesCfg.add("type3"); - artifactTypesCfg.add("type4"); - configurationManager.getConfiguration().setArtifactTypes(artifactTypesCfg); - Either, ActionStatus> allArtifactTypes = elementOperation.getAllArtifactTypes(); - assertTrue(allArtifactTypes.isLeft()); - assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); + List artifactTypesCfg = new ArrayList<>(); + artifactTypesCfg.add("type1"); + artifactTypesCfg.add("type2"); + artifactTypesCfg.add("type3"); + artifactTypesCfg.add("type4"); + configurationManager.getConfiguration().setArtifactTypes(artifactTypesCfg); + Either, ActionStatus> allArtifactTypes = elementOperation.getAllArtifactTypes(); + assertTrue(allArtifactTypes.isLeft()); + assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); - artifactTypesCfg.remove(0); - allArtifactTypes = elementOperation.getAllArtifactTypes(); - assertTrue(allArtifactTypes.isLeft()); - assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); + artifactTypesCfg.remove(0); + allArtifactTypes = elementOperation.getAllArtifactTypes(); + assertTrue(allArtifactTypes.isLeft()); + assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); - artifactTypesCfg.add("type5"); - } + artifactTypesCfg.add("type5"); + } @Test public void testAllDeploymentArtifactTypes() { @@ -111,23 +110,22 @@ public class ElementOperationTest extends ModelTestBase { } - // @Test - public void testGetResourceAndServiceCategoty() { - String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, titanDao); + // @Test + public void testGetResourceAndServiceCategoty() { + String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, titanDao); - Either res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory, - id); - assertTrue(res.isLeft()); - CategoryDefinition categoryDefinition = (CategoryDefinition) res.left().value(); - assertEquals(CATEGORY, categoryDefinition.getName()); - assertEquals(SUBCATEGORY, categoryDefinition.getSubcategories().get(0).getName()); + Either res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory, id); + assertTrue(res.isLeft()); + CategoryDefinition categoryDefinition = (CategoryDefinition) res.left().value(); + assertEquals(CATEGORY, categoryDefinition.getName()); + assertEquals(SUBCATEGORY, categoryDefinition.getSubcategories().get(0).getName()); - id = OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY, titanDao); + id = OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY, titanDao); - res = elementOperation.getCategory(NodeTypeEnum.ServiceNewCategory, id); - assertTrue(res.isLeft()); - categoryDefinition = (CategoryDefinition) res.left().value(); - assertEquals(CATEGORY, categoryDefinition.getName()); + res = elementOperation.getCategory(NodeTypeEnum.ServiceNewCategory, id); + assertTrue(res.isLeft()); + categoryDefinition = (CategoryDefinition) res.left().value(); + assertEquals(CATEGORY, categoryDefinition.getName()); } private ElementOperation createTestSubject() { @@ -496,5 +494,5 @@ public class ElementOperationTest extends ModelTestBase { testSubject = createTestSubject(); name = ""; result = testSubject.getNewCategoryData(name, type, null); - } + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java index 15c5e6497f..94e22e651f 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java @@ -1,32 +1,22 @@ package org.openecomp.sdc.be.model.operations.impl; -import static com.google.common.collect.Sets.newHashSet; -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.resources.data.CapabilityTypeData; @@ -34,12 +24,24 @@ import org.openecomp.sdc.be.resources.data.GroupTypeData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class GroupTypeOperationTest extends ModelTestBase { + private static final String TOSCA_GROUPS_ROOT = "tosca.groups.Root"; + private static final String NULL_STRING = null; @Resource(name = "titan-generic-dao") private TitanGenericDao titanDao; @@ -58,6 +60,7 @@ public class GroupTypeOperationTest extends ModelTestBase { @After public void tearDown() { titanDao.rollback(); + cleanUp(); } @Test @@ -71,7 +74,7 @@ public class GroupTypeOperationTest extends ModelTestBase { List allGroupTypesNoExclusion = groupTypeOperation.getAllGroupTypes(null); assertThat(allGroupTypesNoExclusion) - .usingElementComparatorOnFields("type") + .usingElementComparatorOnFields("type", "icon", "name") .containsExactlyInAnyOrder(rootGroupDefinition, type1, type2); } @@ -91,7 +94,7 @@ public class GroupTypeOperationTest extends ModelTestBase { } @Test - public void groupTypeWithoutCapabilityTypeCreated() { + public void groupTypeWithoutCapabilityCreated() { GroupTypeData rootNode = getOrCreateRootGroupTypeNode(); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -108,12 +111,12 @@ public class GroupTypeOperationTest extends ModelTestBase { groupTypeDefinition.setProperties(properties ); - Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, false); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); addGroupTypeResult = groupTypeOperation.getGroupTypeByTypeAndVersion("org.openecomp.groups.NetworkCollection", "1.0"); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); @@ -123,19 +126,65 @@ public class GroupTypeOperationTest extends ModelTestBase { validate(edgeResult); } + @Test + public void groupTypeWithCapabilityAndPropsButCapTypeWithoutProps() { + getOrCreateRootGroupTypeNode(); + + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(null); + Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + extractVal(capabilityTypeResult); + + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); + groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setDescription("groups l3-networks in network collection"); + groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map mapCapabilities = new HashMap<>(); + + ComponentInstanceProperty property = new ComponentInstanceProperty( + buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance")); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(property)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + + + List properties = asList( + buildProperty("vfc_instance_group_role", null, "role of this VFC group"), + buildProperty("vfc_parent_port_role", null, "common role of parent ports of VFCs in this group"), + buildProperty("network_collection_role", null, "network collection role assigned to this group"), + buildProperty("subinterface_role", null, "common role of subinterfaces of VFCs in this group, criteria the group is created")); + + groupTypeDefinition.setProperties(properties ); + + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); + assertTrue(addGroupTypeResult.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, addGroupTypeResult.right().value()); + } + @Test public void groupTypeWithCapabilityTypeAndEdgeCreated() { GroupTypeData rootNode = getOrCreateRootGroupTypeNode(); - CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(); + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", + buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance")); + + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); - CapabilityTypeData capabilityTypeNode = extractVal(capabilityTypeResult); + extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); groupTypeDefinition.setDescription("groups l3-networks in network collection"); groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); - groupTypeDefinition.setCapabilityTypes(asList(capabilityTypeDef)); + + Map mapCapabilities = new HashMap<>(); + ComponentInstanceProperty property = new ComponentInstanceProperty( + buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance")); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(property)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + List properties = asList( buildProperty("vfc_instance_group_role", null, "role of this VFC group"), @@ -146,88 +195,276 @@ public class GroupTypeOperationTest extends ModelTestBase { groupTypeDefinition.setProperties(properties ); Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); GroupTypeData groupTypeNode = extractVal(groupTypeResult); - Either edgeCapTypeResult = titanDao.getEdgeByNodes(groupTypeNode, capabilityTypeNode, GraphEdgeLabels.GROUP_TYPE_CAPABILITY_TYPE); - validate(edgeCapTypeResult); + Either groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); + assertTrue(groupTypeDefResult.isLeft()); + GroupTypeDefinition groupTypeDefinitionRetrieved = groupTypeDefResult.left().value(); + assertNotNull(groupTypeDefinitionRetrieved); + Map capabilityDefs = groupTypeDefinitionRetrieved.getCapabilities(); + assertNotNull(capabilityDefs); + assertEquals(1, capabilityDefs.size()); + assertTrue(capabilityDefs.containsKey("vlan_assignment")); + CapabilityDefinition updatedCapabilityDef = capabilityDefs.get("vlan_assignment"); + assertEquals(2, updatedCapabilityDef.getProperties().size()); Either edgeDerivedFromResult = titanDao.getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM); validate(edgeDerivedFromResult); } @Test - public void testUpgradeGroupTypeWithDerrivedFromEdge() { + public void groupTypeWithCapabilityTypeAndEdgeCreated_OverrideDefaultCapabilityTypeValue() { + getOrCreateRootGroupTypeNode(); + + PropertyDefinition property = buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance"); + + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + extractVal(capabilityTypeResult); + + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); + groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setDescription("groups l3-networks in network collection"); + groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map mapCapabilities = new HashMap<>(); + property.setValue("new_value"); + ComponentInstanceProperty capDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(capDefProperty)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + + + List properties = asList( + buildProperty("vfc_instance_group_role", null, "role of this VFC group"), + buildProperty("vfc_parent_port_role", null, "common role of parent ports of VFCs in this group"), + buildProperty("network_collection_role", null, "network collection role assigned to this group"), + buildProperty("subinterface_role", null, "common role of subinterfaces of VFCs in this group, criteria the group is created")); + + groupTypeDefinition.setProperties(properties ); + + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); + assertTrue("check group type added", addGroupTypeResult.isLeft()); + compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); + + Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); + GroupTypeData groupTypeNode = extractVal(groupTypeResult); + + Either groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); + assertTrue(groupTypeDefResult.isLeft()); + GroupTypeDefinition groupTypeDefinitionRetrieved = groupTypeDefResult.left().value(); + assertNotNull(groupTypeDefinitionRetrieved); + Map capabilityDefs = groupTypeDefinitionRetrieved.getCapabilities(); + assertNotNull(capabilityDefs); + assertEquals(1, capabilityDefs.size()); + assertTrue(capabilityDefs.containsKey("vlan_assignment")); + + CapabilityDefinition capDefinition = capabilityDefs.get("vlan_assignment"); + assertEquals("new_value", capDefinition.getProperties().get(0).getValue()); + assertEquals(2, capDefinition.getProperties().size()); + } + + + @Test + public void updateGroupTypeWithCapability_FailedDueToCapabilityDeleteAttempt() { + createRootGroupTypeNode(); + + PropertyDefinition property = buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance"); + + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + extractVal(capabilityTypeResult); + + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); + groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setDescription("groups l3-networks in network collection"); + groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map mapCapabilities = new HashMap<>(); + property.setValue("new_value"); + ComponentInstanceProperty capDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(capDefProperty)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition); + assertTrue(addGroupTypeResult.isLeft()); + + GroupTypeDefinition newGroupTypeDefinition = new GroupTypeDefinition(); + newGroupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + newGroupTypeDefinition.setDescription("groups l3-networks in network collection"); + newGroupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + Either updateGroupTypeResult = groupTypeOperation.updateGroupType(newGroupTypeDefinition, addGroupTypeResult.left().value()); + assertTrue(updateGroupTypeResult.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updateGroupTypeResult.right().value()); + } + + @Test + public void updateGroupTypeWithCapability_FailedDueToCapabilityChangeTypeAttempt() { + createRootGroupTypeNode(); + + PropertyDefinition property = buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance"); + + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + extractVal(capabilityTypeResult); + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setDescription("groups l3-networks in network collection"); + groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map mapCapabilities = new HashMap<>(); + property.setValue("new_value"); + ComponentInstanceProperty capDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(capDefProperty)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition); + assertTrue(addGroupTypeResult.isLeft()); + + GroupTypeDefinition newGroupTypeDefinition = new GroupTypeDefinition(); + newGroupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + newGroupTypeDefinition.setDescription("groups l3-networks in network collection"); + newGroupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map updatedMapCapabilities = new HashMap<>(); + property.setValue("new_value"); + ComponentInstanceProperty newCapDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition updatedCapabilityDef = buildCapabilityDefintion(asList(newCapDefProperty)); + updatedCapabilityDef.setType("Another type"); + updatedMapCapabilities.put("vlan_assignment", updatedCapabilityDef); + newGroupTypeDefinition.setCapabilities(updatedMapCapabilities); + + Either updateGroupTypeResult = groupTypeOperation.updateGroupType(newGroupTypeDefinition, addGroupTypeResult.left().value()); + assertTrue(updateGroupTypeResult.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updateGroupTypeResult.right().value()); + } + + @Test + public void updateGroupTypeWithCapability_Success() { + createRootGroupTypeNode(); + + PropertyDefinition property = buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance"); + + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + extractVal(capabilityTypeResult); + + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); + groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setDescription("groups l3-networks in network collection"); + groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map mapCapabilities = new HashMap<>(); + property.setValue("new_value"); + ComponentInstanceProperty capDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition capabilityDef = buildCapabilityDefintion(asList(capDefProperty)); + mapCapabilities.put("vlan_assignment", capabilityDef); + groupTypeDefinition.setCapabilities(mapCapabilities); + + Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition); + assertTrue(addGroupTypeResult.isLeft()); + + GroupTypeDefinition newGroupTypeDefinition = new GroupTypeDefinition(); + newGroupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); + newGroupTypeDefinition.setDescription("groups l3-networks in network collection"); + newGroupTypeDefinition.setType("org.openecomp.groups.NetworkCollection"); + + Map updatedMapCapabilities = new HashMap<>(); + property.setValue("another_value"); + ComponentInstanceProperty newCapDefProperty = new ComponentInstanceProperty(property); + CapabilityDefinition updatedCapabilityDef = buildCapabilityDefintion(asList(newCapDefProperty)); + updatedMapCapabilities.put("vlan_assignment", updatedCapabilityDef); + newGroupTypeDefinition.setCapabilities(updatedMapCapabilities); + + Either updateGroupTypeResult = groupTypeOperation.updateGroupType(newGroupTypeDefinition, addGroupTypeResult.left().value()); + assertTrue(updateGroupTypeResult.isLeft()); + } + + @Test + public void testUpdateGroupTypeWithDerivedFromEdge() { + createRootGroupTypeNode(); + + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDescription("groups l2-networks in network collection"); groupTypeDefinition.setType("org.openecomp.groups.PrivateCollection"); groupTypeDefinition.setVersion("1.0"); - + List properties = singletonList( buildProperty("network_collection_type", "l2-network", "network collection type, defined with default value")); groupTypeDefinition.setProperties(properties ); Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); addGroupTypeResult = groupTypeOperation.getGroupTypeByTypeAndVersion("org.openecomp.groups.PrivateCollection", "1.0"); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); - Either upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, groupTypeDefinition); assertNotNull(upgradeResult); assertTrue(upgradeResult.isLeft()); } @Test - public void testUpgradeNonExistingGroupType() { + public void testUpdateNonExistingGroupType() { GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT); groupTypeDefinition.setDescription("groups l2-networks in network collection"); groupTypeDefinition.setType("org.openecomp.groups.MyCollection"); groupTypeDefinition.setVersion("1.0"); - Either upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, groupTypeDefinition); assertNotNull(upgradeResult); assertTrue(upgradeResult.isRight()); } @Test - public void testUpgradeNotDerivedGroupType() { + public void testUpdateNotDerivedGroupType() { GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDescription("groups social-networks in school"); groupTypeDefinition.setType("org.openecomp.groups.Teachers"); groupTypeDefinition.setVersion("1.0"); Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); - Either upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, groupTypeDefinition); assertNotNull(upgradeResult); assertTrue(upgradeResult.isLeft()); - assertEquals(groupTypeDefinition, upgradeResult.left().value()); + assertThat(groupTypeDefinition).isEqualToIgnoringGivenFields(upgradeResult.left().value(), "properties", "capabilities"); } @Test - public void testUpgradeGroupTypeWithNonExistingParent() { + public void testUpdateGroupTypeWithNonExistingParent() { GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDescription("groups social-networks in work"); groupTypeDefinition.setType("org.openecomp.groups.Cowokers"); groupTypeDefinition.setVersion("1.0"); Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); groupTypeDefinition.setDerivedFrom("Non.existing.parent"); - Either upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, groupTypeDefinition); assertNotNull(upgradeResult); assertTrue(upgradeResult.isRight()); } @@ -240,23 +477,25 @@ public class GroupTypeOperationTest extends ModelTestBase { groupTypeDefinition.setVersion("1.0"); Either addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); GroupTypeDefinition parentGroupTypeDefinition = new GroupTypeDefinition(); parentGroupTypeDefinition.setDescription("groups social-networks in university"); parentGroupTypeDefinition.setType("org.openecomp.groups.Parents"); parentGroupTypeDefinition.setVersion("1.0"); + parentGroupTypeDefinition.setHighestVersion(true); + Either addParentGroupTypeResult = groupTypeOperation.addGroupType(parentGroupTypeDefinition, true); - assertEquals("check group type added", true, addParentGroupTypeResult.isLeft()); + assertTrue("check group type added", addParentGroupTypeResult.isLeft()); compareBetweenCreatedToSent(parentGroupTypeDefinition, addParentGroupTypeResult.left().value()); groupTypeDefinition.setDerivedFrom("org.openecomp.groups.Parents"); - Either upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, addGroupTypeResult.left().value()); assertNotNull(upgradeResult); assertTrue(upgradeResult.isLeft()); - assertEquals(groupTypeDefinition, upgradeResult.left().value()); + assertThat(groupTypeDefinition).isEqualToIgnoringGivenFields(upgradeResult.left().value(), "properties", "capabilities"); } @@ -271,8 +510,8 @@ public class GroupTypeOperationTest extends ModelTestBase { private GroupTypeData createRootGroupTypeNode() { GroupTypeDefinition rootGroupDefinition = createRootGroupDefinition(); - Either addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + Either addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, false); + assertTrue("check group type added", addGroupTypeResult.isLeft()); Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), rootGroupDefinition.getType(), GroupTypeData.class); return extractVal(groupTypeResult); @@ -282,6 +521,7 @@ public class GroupTypeOperationTest extends ModelTestBase { GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDescription("The TOSCA Group Type all other TOSCA Group Types derive from"); groupTypeDefinition.setType(TOSCA_GROUPS_ROOT); + groupTypeDefinition.setHighestVersion(true); return groupTypeDefinition; } @@ -289,23 +529,41 @@ public class GroupTypeOperationTest extends ModelTestBase { GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); groupTypeDefinition.setDescription("description for type " + type); groupTypeDefinition.setType(type); + groupTypeDefinition.setName(type + "name"); + groupTypeDefinition.setIcon(type + "icon"); return groupTypeDefinition; } - private CapabilityTypeDefinition createCapabilityType() { + private CapabilityTypeDefinition createCapabilityType(Map properties) { + CapabilityTypeDefinition rootCapabilityTypeDefinition = new CapabilityTypeDefinition(); + rootCapabilityTypeDefinition.setType("tosca.capabilities.Root"); + rootCapabilityTypeDefinition.setDescription("Dummy root type"); + rootCapabilityTypeDefinition.setVersion("1.0"); + capabilityTypeOperation.addCapabilityType(rootCapabilityTypeDefinition, true); + + + CapabilityTypeDefinition parentCapabilityTypeDefinition = new CapabilityTypeDefinition(); + parentCapabilityTypeDefinition.setType("tosca.capabilities.Parent"); + parentCapabilityTypeDefinition.setDescription("Dummy parent type"); + parentCapabilityTypeDefinition.setDerivedFrom("tosca.capabilities.Root"); + parentCapabilityTypeDefinition.setVersion("1.0"); + PropertyDefinition property = buildProperty("parentProp", "any", "Description"); + Map capTypeProperties = new HashMap<>(); + capTypeProperties.put("parent_prop", property); + parentCapabilityTypeDefinition.setProperties(capTypeProperties); + capabilityTypeOperation.addCapabilityType(parentCapabilityTypeDefinition, true); + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); capabilityTypeDefinition.setDescription("ability to expose routing information of the internal network"); capabilityTypeDefinition.setType("org.openecomp.capabilities.VLANAssignment"); capabilityTypeDefinition.setVersion("1.0"); - - Map properties = new HashMap<>(); - properties.put("vfc_instance_group_reference", - buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance")); - + capabilityTypeDefinition.setDerivedFrom("tosca.capabilities.Parent"); + capabilityTypeDefinition.setProperties(properties); Either addCapabilityTypeResult = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - assertEquals("check capability type added", true, addCapabilityTypeResult.isLeft()); + assertTrue("check capability type added", addCapabilityTypeResult.isLeft()); CapabilityTypeDefinition capabilityTypeAdded = addCapabilityTypeResult.left().value(); compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded); @@ -313,6 +571,15 @@ public class GroupTypeOperationTest extends ModelTestBase { return capabilityTypeDefinition; } + private CapabilityDefinition buildCapabilityDefintion(List properties) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setName("vlan_assignment"); + capabilityDefinition.setDescription("ability to expose routing information of the internal network"); + capabilityDefinition.setType("org.openecomp.capabilities.VLANAssignment"); + capabilityDefinition.setProperties(properties); + return capabilityDefinition; + } + private PropertyDefinition buildProperty(String name, String defaultValue, String description) { PropertyDefinition property = new PropertyDefinition(); property.setName(name); @@ -346,5 +613,201 @@ public class GroupTypeOperationTest extends ModelTestBase { return t; } + + private void cleanUp() { + Either graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanDao.commit(); + } + + + @Test + public void updateGroupType_returnNotFoundErrorIfTryingToUpdateANonExistingType() { + GroupTypeDefinition currType = createGroupTypeDef(); + GroupTypeDefinition updatedType = createGroupTypeDef(); + Either updatedGroupTypeRes = groupTypeOperation.updateGroupType(updatedType, currType); + assertThat(updatedGroupTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + } + + @Test + public void updateGroupType_basicFields() { + GroupTypeDefinition createdType = createGroupTypeDef("type1", "description1", NULL_STRING); + Either currGroupType = groupTypeOperation.addGroupType(createdType); + + GroupTypeDefinition updatedType = createGroupTypeDef("type1", "description2", NULL_STRING); + updatedType.setName("newName"); + updatedType.setIcon("icon"); + groupTypeOperation.updateGroupType(updatedType, currGroupType.left().value()); + + Either fetchedUpdatedType = groupTypeOperation.getLatestGroupTypeByType(createdType.getType()); + GroupTypeDefinition fetchedGroupType = fetchedUpdatedType.left().value(); + assertThat(fetchedGroupType.getProperties()).isEmpty(); + assertThat(fetchedGroupType) + .isEqualToIgnoringGivenFields(updatedType, "properties", "capabilities"); + + } + + @Test + public void updateGroupType_updatePropertiesType_FailedDueAttemptToChangePropertyType() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + GroupTypeDefinition groupType = createGroupTypeDef(prop1); + Either currGroupType = groupTypeOperation.addGroupType(groupType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + GroupTypeDefinition updatedGroupType = createGroupTypeDef(updatedProp1, prop3); + + Either updatedGroupTypeRetrieved = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedGroupTypeRetrieved.right().value()); + } + + @Test + public void validateGroupType_FailedDueAttempToCreateGroupTypeWithPropertyWhichTypeIsDifferentFromTypeOfParentPropertyWithTheSameName() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + Either rootGroupTypeRes = groupTypeOperation.addGroupType(rootGroupType); + assertTrue(rootGroupTypeRes.isLeft()); + + PropertyDefinition prop = createSimpleProperty("val1", "prop", "string"); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr1", rootGroupType.getType(), prop); + Either groupType1Res = groupTypeOperation.addGroupType(groupType1); + assertTrue(groupType1Res.isLeft()); + + PropertyDefinition prop1 = createSimpleProperty("33", "prop", "int"); + PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); + GroupTypeDefinition groupType2 = createGroupTypeDef("type2", "descr", groupType1.getType(), prop1, prop2); + + Either updatedGroupTypeRetrieved = groupTypeOperation.validateUpdateProperties(groupType2); + assertEquals(StorageOperationStatus.PROPERTY_NAME_ALREADY_EXISTS, updatedGroupTypeRetrieved.right().value()); + } + + @Test + public void updateGroupType_derivedFrom_whenNoPrevDerivedFrom_updateToNewDerivedFrom() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr", NULL_STRING); + GroupTypeDefinition updatedGroupType = createGroupTypeDef("type1", "descr", rootGroupType.getType()); + groupTypeOperation.addGroupType(rootGroupType); + Either currGroupType = groupTypeOperation.addGroupType(groupType1); + groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + + Either latestGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType1.getType()); + assertThat(latestGroupType.left().value().getDerivedFrom()).isEqualTo(rootGroupType.getType()); + verifyDerivedFromNodeEqualsToRootGroupType(rootGroupType, latestGroupType.left().value().getUniqueId()); + } + + @Test + public void updateGroupType_derivedFrom_updateToNullDerivedFrom_derivedFromDeleted_Failed() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr", rootGroupType.getType()); + GroupTypeDefinition updatedGroupType = createGroupTypeDef("type1", "descr", null, new PropertyDefinition[]{}); + groupTypeOperation.addGroupType(rootGroupType); + Either currGroupType = groupTypeOperation.addGroupType(groupType1); + + Either updateGroupTypeRes = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertThat(updateGroupTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + + Either latestGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType1.getType()); + assertThat(latestGroupType.left().value().getDerivedFrom()).isEqualTo(rootGroupType.getType()); + } + + @Test + public void updateGroupType_updateDerivedFrom() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + GroupTypeDefinition derivedType1 = createGroupTypeDef("derivedType1", "descr", rootGroupType.getType()); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr", rootGroupType.getType()); + GroupTypeDefinition updatedGroupType = createGroupTypeDef("type1", "descr", derivedType1.getType()); + + groupTypeOperation.addGroupType(rootGroupType); + groupTypeOperation.addGroupType(derivedType1); + Either currGroupType = groupTypeOperation.addGroupType(groupType1); + + groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + + Either latestGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType1.getType()); + assertThat(latestGroupType.left().value().getDerivedFrom()).isEqualTo(derivedType1.getType()); + } + @Test + public void updateGroupType_updateDerivedFrom_CauseEndlessRecursion() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + GroupTypeDefinition derivedType1 = createGroupTypeDef("derivedType1", "descr", rootGroupType.getType()); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr", derivedType1.getType()); + GroupTypeDefinition updatedGroupType = createGroupTypeDef("derivedType1", "descr", groupType1.getType()); + + groupTypeOperation.addGroupType(rootGroupType); + Either currGroupType = groupTypeOperation.addGroupType(derivedType1); + groupTypeOperation.addGroupType(groupType1); + + Either updateResult = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertThat(updateResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + + Either latestGroupType = groupTypeOperation.getLatestGroupTypeByType(updatedGroupType.getType()); + assertThat(latestGroupType.left().value().getDerivedFrom()).isEqualTo(rootGroupType.getType()); + } + + private PropertyDefinition duplicateProperty(PropertyDefinition prop1, String updatedValue, String updatedType) { + PropertyDefinition updatedProp1 = new PropertyDefinition(prop1); + updatedProp1.setUniqueId(null); + updatedProp1.setDefaultValue(updatedValue); + updatedProp1.setType(updatedType); + return updatedProp1; + } + + private void verifyDerivedFromNodeEqualsToRootGroupType(GroupTypeDefinition rootGroupType, String parentGroupId) { + Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.GroupType, GroupTypeData.class); + assertThat(derivedFromRelation.left().value().getLeft().getGroupTypeDataDefinition()) + .isEqualToComparingFieldByField(rootGroupType); + } + + private void verifyDerivedFromRelationDoesntExist(String parentGroupId) { + Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.GroupType, GroupTypeData.class); + assertThat(derivedFromRelation.right().value()) + .isEqualTo(TitanOperationStatus.NOT_FOUND); + } + + private GroupTypeDefinition createGroupTypeDef() { + return createGroupTypeDef("tosca.groups.Root", "description: The TOSCA Group Type all other TOSCA Group Types derive from", null, new PropertyDefinition[]{}); + } + + private GroupTypeDefinition createGroupTypeDef(PropertyDefinition ... props) { + return createGroupTypeDef("tosca.groups.Root", null, props); + } + + private GroupTypeDefinition createGroupTypeDef(String type, String derivedFrom, PropertyDefinition ... props) { + GroupTypeDefinition groupType = createGroupTypeDef(type, "description: The TOSCA Group Type all other TOSCA Group Types derive from", derivedFrom); + groupType.setProperties(asList(props)); + return groupType; + } + + private GroupTypeDefinition createGroupTypeDef(String type, String description, String derivedFrom) { + return createGroupTypeDef(type, description, derivedFrom, null); + } + + private GroupTypeDefinition createGroupTypeDef(String type, String description, String derivedFrom, PropertyDefinition ... props) { + GroupTypeDataDefinition groupTypeDataDefinition = new GroupTypeDataDefinition(); + groupTypeDataDefinition.setDescription(description); + groupTypeDataDefinition.setType(type); + groupTypeDataDefinition.setName(type + "name"); + groupTypeDataDefinition.setIcon(type + "icon"); + groupTypeDataDefinition.setDerivedFrom(derivedFrom); + GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(groupTypeDataDefinition); + groupTypeDefinition.setHighestVersion(true); + groupTypeDefinition.setVersion("1.0"); + if (props != null) { + groupTypeDefinition.setProperties(asList(props)); + } + return groupTypeDefinition; + } + } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java index 46db317707..61504db727 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java @@ -20,18 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -48,199 +37,204 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.HeatParameterData; import org.openecomp.sdc.be.resources.data.HeatParameterValueData; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; public class HeatParametersOperationTest extends ModelTestBase { - HeatParametersOperation heatParametersOperation = new HeatParametersOperation(); + HeatParametersOperation heatParametersOperation = new HeatParametersOperation(); - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - @Before - public void setup() { - heatParametersOperation.setTitanGenericDao(titanGenericDao); + @Before + public void setup() { + heatParametersOperation.setTitanGenericDao(titanGenericDao); - } + } - @Test - public void addPropertyToResourceTest() { + @Test + public void addPropertyToResourceTest() { - String propName = "myProp"; - HeatParameterDefinition property = buildHeatPropertyDefinition(); + String propName = "myProp"; + HeatParameterDefinition property = buildHeatPropertyDefinition(); - HeatParameterData propertyData = new HeatParameterData(property); + HeatParameterData propertyData = new HeatParameterData(property); - Either either = Either.left(propertyData); + Either either = Either.left(propertyData); - GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); + GraphRelation graphRelation = new GraphRelation(); + Either relationResult = Either.left(graphRelation); - when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), (GraphNode) any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); + when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); - Either result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + Either result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); - assertTrue(result.isLeft()); + assertTrue(result.isLeft()); - } + } - @Test - public void addPropertyListToResourceTest() { + @Test + public void addPropertyListToResourceTest() { - HeatParameterDefinition property = buildHeatPropertyDefinition(); - HeatParameterDefinition property2 = buildHeatPropertyDefinition(); - property2.setName("p2"); + HeatParameterDefinition property = buildHeatPropertyDefinition(); + HeatParameterDefinition property2 = buildHeatPropertyDefinition(); + property2.setName("p2"); - List parameters = new ArrayList(); - parameters.add(property); - parameters.add(property2); + List parameters = new ArrayList<>(); + parameters.add(property); + parameters.add(property2); - HeatParameterData propertyData = new HeatParameterData(property); + HeatParameterData propertyData = new HeatParameterData(property); - Either either = Either.left(propertyData); + Either either = Either.left(propertyData); - GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); + GraphRelation graphRelation = new GraphRelation(); + Either relationResult = Either.left(graphRelation); - when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), (GraphNode) any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); + when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); - StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); - assertEquals(StorageOperationStatus.OK, result); + assertEquals(StorageOperationStatus.OK, result); - } + } - @Test - public void testStringValues() { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.STRING, "50aaa")); - } + @Test + public void testStringValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.STRING, "50aaa")); + } - @Test - public void testNumberValues() { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50")); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50.5")); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "0x11")); + @Test + public void testNumberValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50")); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50.5")); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "0x11")); - assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "aaa")); - assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "?>!")); - } + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "aaa")); + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "?>!")); + } - @Test - public void testJsonValues() { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.JSON, "{ \"member\" : \"50\"}")); - HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.JSON.getType(), "{ \"member\" : \"50\"}"); - StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals(HeatParameterType.JSON.getType(), propertyDefinition.getType()); + @Test + public void testJsonValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.JSON, "{ \"member\" : \"50\"}")); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.JSON.getType(), "{ \"member\" : \"50\"}"); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals(HeatParameterType.JSON.getType(), propertyDefinition.getType()); - } + } - @Test - public void testListValues() { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.COMMA_DELIMITED_LIST, "one, two")); - HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.COMMA_DELIMITED_LIST.getType(), "one, two"); - StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals(HeatParameterType.COMMA_DELIMITED_LIST.getType(), propertyDefinition.getType()); - assertEquals("one, two", propertyDefinition.getDefaultValue()); - } + @Test + public void testListValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.COMMA_DELIMITED_LIST, "one, two")); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.COMMA_DELIMITED_LIST.getType(), "one, two"); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals(HeatParameterType.COMMA_DELIMITED_LIST.getType(), propertyDefinition.getType()); + assertEquals("one, two", propertyDefinition.getDefaultValue()); + } - @Test - public void testBooleanValues() { + @Test + public void testBooleanValues() { - String[] trueArray = { "true", "t", "1", "on", "y", "yes" }; - String[] falseArray = { "false", "f", "0", "off", "n", "no" }; + String[] trueArray = { "true", "t", "1", "on", "y", "yes" }; + String[] falseArray = { "false", "f", "0", "off", "n", "no" }; - for (int i = 0; i < trueArray.length; i++) { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); - HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i]); - StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("true", propertyDefinition.getDefaultValue()); + for (int i = 0; i < trueArray.length; i++) { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i]); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); - propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toUpperCase()); - operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("true", propertyDefinition.getDefaultValue()); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toUpperCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); - propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toLowerCase()); - operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("true", propertyDefinition.getDefaultValue()); - } + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toLowerCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); + } - for (int i = 0; i < falseArray.length; i++) { - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); - HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i]); - StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("false", propertyDefinition.getDefaultValue()); + for (int i = 0; i < falseArray.length; i++) { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i]); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); - propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toUpperCase()); - operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("false", propertyDefinition.getDefaultValue()); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toUpperCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); - assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); - propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toLowerCase()); - operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); - assertEquals(StorageOperationStatus.OK, operationStatus); - assertEquals("false", propertyDefinition.getDefaultValue()); - } + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toLowerCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); + } - assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "blabla")); - assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "2")); - } + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "blabla")); + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "2")); + } - private HeatParameterDefinition buildHeatPropertyDefinition() { - HeatParameterDefinition parameter = new HeatParameterDefinition(); - - parameter.setName("p1"); - parameter.setType("string"); - parameter.setDefaultValue("def"); - parameter.setCurrentValue("current"); - parameter.setDescription("description"); - - return parameter; - } - - private HeatParameterDefinition buildHeatBooleanPropertyDefinition(String type, String boolValue) { - HeatParameterDefinition parameter = new HeatParameterDefinition(); - - parameter.setName("parameter1"); - parameter.setType(type); - parameter.setDefaultValue(boolValue); - parameter.setDescription("description"); - - return parameter; - } - - @Test - public void addPropertyToResourceInstanceTest() { - - HeatParameterDefinition property = buildHeatPropertyDefinition(); - - HeatParameterValueData propertyData = new HeatParameterValueData(); - propertyData.setUniqueId("bla"); - propertyData.setValue("value1"); - - Either either = Either.left(propertyData); - - GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); - - when(titanGenericDao.createNode(any(HeatParameterValueData.class), eq(HeatParameterValueData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_IMPL), isNull())).thenReturn(relationResult); - - Either result = heatParametersOperation.addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId"); - - assertTrue(result.isLeft()); - - } + private HeatParameterDefinition buildHeatPropertyDefinition() { + HeatParameterDefinition parameter = new HeatParameterDefinition(); + + parameter.setName("p1"); + parameter.setType("string"); + parameter.setDefaultValue("def"); + parameter.setCurrentValue("current"); + parameter.setDescription("description"); + + return parameter; + } + + private HeatParameterDefinition buildHeatBooleanPropertyDefinition(String type, String boolValue) { + HeatParameterDefinition parameter = new HeatParameterDefinition(); + + parameter.setName("parameter1"); + parameter.setType(type); + parameter.setDefaultValue(boolValue); + parameter.setDescription("description"); + + return parameter; + } + + @Test + public void addPropertyToResourceInstanceTest() { + + HeatParameterDefinition property = buildHeatPropertyDefinition(); + + HeatParameterValueData propertyData = new HeatParameterValueData(); + propertyData.setUniqueId("bla"); + propertyData.setValue("value1"); + + Either either = Either.left(propertyData); + + GraphRelation graphRelation = new GraphRelation(); + Either relationResult = Either.left(graphRelation); + + when(titanGenericDao.createNode(any(HeatParameterValueData.class), eq(HeatParameterValueData.class))).thenReturn(either); + when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult); + when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_IMPL), isNull())).thenReturn(relationResult); + + Either result = heatParametersOperation.addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId"); + + assertTrue(result.isLeft()); + + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java index ae7944096a..a50435b30c 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertTrue; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -40,215 +40,215 @@ import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class InterfaceOperationTest { - private static Logger log = LoggerFactory.getLogger(InterfaceOperationTest.class.getName()); - private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger log = LoggerFactory.getLogger(InterfaceOperationTest.class); + private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; - // InterfaceLifecycleOperation interfaceOperation = new - // InterfaceLifecycleOperation(); + private static String USER_ID = "muUserId"; + private static String CATEGORY_NAME = "category/mycategory"; + // InterfaceLifecycleOperation interfaceOperation = new + // InterfaceLifecycleOperation(); - // TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + // TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; - @javax.annotation.Resource(name = "interface-operation") - private InterfaceLifecycleOperation interfaceOperation; + @javax.annotation.Resource(name = "interface-operation") + private InterfaceLifecycleOperation interfaceOperation; - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; - // @Resource(name = "artifact-operation") - // private ArtifactOperation artifactOperation; + // @Resource(name = "artifact-operation") + // private ArtifactOperation artifactOperation; - @Before - public void createUserAndCategory() { - deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); - } + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + } - @BeforeClass - public static void setupBeforeClass() { - // ExternalConfiguration.setAppName("catalog-model"); - // String appConfigDir = "src/test/resources/config/catalog-model"; - // ConfigurationSource configurationSource = new - // FSConfigurationSource(ExternalConfiguration.getChangeListener(), - // appConfigDir); + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); - ModelTestBase.init(); + ModelTestBase.init(); - } + } - @Test - public void testDummy() { + @Test + public void testDummy() { - assertTrue(interfaceOperation != null); + assertNotNull(interfaceOperation); - } + } -/* @Test - public void addInterfaceToResourceTest() { +/* @Test + public void addInterfaceToResourceTest() { - String capabilityTypeName = "mycapability1"; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute1"; - String rootName = "Root100"; - String softwareCompName = "tosca.nodes.SoftwareComponent"; - String computeNodeName = "tosca.nodes.Compute"; - String myResourceVersion = "300.0"; - String reqRelationship = "myrelationship"; + String capabilityTypeName = "mycapability1"; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute1"; + String rootName = "Root100"; + String softwareCompName = "tosca.nodes.SoftwareComponent"; + String computeNodeName = "tosca.nodes.Compute"; + String myResourceVersion = "300.0"; + String reqRelationship = "myrelationship"; - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, true, true); + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, true, true); - String interfaceName = "standard"; - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); + String interfaceName = "standard"; + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Operation op = buildOperationDefinition(); - Map operations = new HashMap(); - operations.put("Create", op); - interfaceDefinition.setOperations(operations); + Operation op = buildOperationDefinition(); + Map operations = new HashMap(); + operations.put("Create", op); + interfaceDefinition.setOperations(operations); - Either result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + Either result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - assertTrue(result.isLeft()); - log.debug("{}", result.left().value()); + assertTrue(result.isLeft()); + log.debug("{}", result.left().value()); - Either getResourceRes = resourceOperation.getResource(rootResource.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); + Either getResourceRes = resourceOperation.getResource(rootResource.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); - } + } - @Test - public void updateInterfaceToResourceTest() { + @Test + public void updateInterfaceToResourceTest() { - String reqName = "host"; - String rootName = "Root200"; - String softwareCompName = "tosca.nodes.SoftwareComponent"; + String reqName = "host"; + String rootName = "Root200"; + String softwareCompName = "tosca.nodes.SoftwareComponent"; - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, true, true); + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, true, true); - String interfaceName = "standard"; - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); + String interfaceName = "standard"; + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Operation op = buildOperationDefinition(); - Map operations = new HashMap(); - operations.put("create", op); - interfaceDefinition.setOperations(operations); + Operation op = buildOperationDefinition(); + Map operations = new HashMap(); + operations.put("create", op); + interfaceDefinition.setOperations(operations); - Either result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + Either result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); + Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); - assertTrue(fetchRootResource.isLeft()); - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "400.0", rootResource.getName(), true, true); + assertTrue(fetchRootResource.isLeft()); + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "400.0", rootResource.getName(), true, true); - assertTrue(result.isLeft()); - log.debug("{}", result.left().value()); + assertTrue(result.isLeft()); + log.debug("{}", result.left().value()); - addImplementationToOperation(op); - // String resourceId, String interfaceName, String - // operationName,Operation interf + addImplementationToOperation(op); + // String resourceId, String interfaceName, String + // operationName,Operation interf - Either opResult = interfaceOperation.updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op); - // PrintGraph pg = new PrintGraph(); - // System.out.println(pg.buildGraphForWebgraphWiz(titanDao.getGraph().left().value())); - assertTrue(opResult.isLeft()); - log.debug("{}", opResult.left().value()); + Either opResult = interfaceOperation.updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op); + // PrintGraph pg = new PrintGraph(); + // System.out.println(pg.buildGraphForWebgraphWiz(titanDao.getGraph().left().value())); + assertTrue(opResult.isLeft()); + log.debug("{}", opResult.left().value()); - Either getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); - Operation operation = interfaceDefinition2.getOperations().get("create"); - assertNotNull(operation); - assertNotNull(operation.getImplementation()); - } + Either getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); + Operation operation = interfaceDefinition2.getOperations().get("create"); + assertNotNull(operation); + assertNotNull(operation.getImplementation()); + } */ - private void addImplementationToOperation(Operation op) { - ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); - artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); - artifactDataDef.setArtifactName("create_myRoot.sh"); - artifactDataDef.setArtifactLabel("create_myRoot"); - artifactDataDef.setArtifactType("SHELL"); - artifactDataDef.setDescription("good description"); - artifactDataDef.setEsId("esId"); - artifactDataDef.setUniqueId(op.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); - ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); - op.setImplementation(artifactDef); - } - - private InterfaceDefinition buildInterfaceDefinition() { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setType("tosca.interfaces.standard"); - interfaceDefinition.setCreationDate(new Long(101232)); - - return interfaceDefinition; - } - - private Operation buildOperationDefinition() { - Operation op = new Operation(); - op.setCreationDate(new Long(101232)); - op.setDescription("asda"); - - return op; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - - /* - * CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * titanDao.deleteNode(categoryData, CategoryData.class); Either createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); - */ - - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } + private void addImplementationToOperation(Operation op) { + ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); + artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); + artifactDataDef.setArtifactName("create_myRoot.sh"); + artifactDataDef.setArtifactLabel("create_myRoot"); + artifactDataDef.setArtifactType("SHELL"); + artifactDataDef.setDescription("good description"); + artifactDataDef.setEsId("esId"); + artifactDataDef.setUniqueId(op.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); + ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); + op.setImplementation(artifactDef); + } + + private InterfaceDefinition buildInterfaceDefinition() { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + interfaceDefinition.setCreationDate(new Long(101232)); + + return interfaceDefinition; + } + + private Operation buildOperationDefinition() { + Operation op = new Operation(); + op.setCreationDate(new Long(101232)); + op.setDescription("asda"); + + return op; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + + /* + * CategoryData categoryData = new CategoryData(); categoryData.setName(category); + * + * titanDao.deleteNode(categoryData, CategoryData.class); Either createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); + */ + + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java index 355155561e..64856c8d38 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java @@ -20,16 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import static com.google.common.collect.Sets.newHashSet; -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Iterator; -import java.util.List; -import java.util.stream.Stream; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; @@ -45,153 +38,155 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.PolicyTypeData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Stream; -import fj.data.Either; +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class PolicyTypeOperationTest extends ModelTestBase { - private static final String NULL_STRING = null; - @Autowired - private PolicyTypeOperation policyTypeOperation; - - @Autowired - private TitanGenericDao titanGenericDao; - - @BeforeClass - public static void setupBeforeClass() { - ModelTestBase.init(); - - } - - @Before - public void cleanUp() { - TitanGenericDao titanGenericDao = policyTypeOperation.titanGenericDao; - Either graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - vertex.remove(); - } - - } - titanGenericDao.commit(); - } - - @Test - public void testAddPolicyType() { - - PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef(); - assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId())); - Either addPolicyType = policyTypeOperation.addPolicyType(policyTypePreCreate); - assertTrue(addPolicyType.isLeft()); - PolicyTypeDefinition policyTypePostCreate = addPolicyType.left().value(); - assertEquals(policyTypePostCreate.getType(), policyTypePreCreate.getType()); - assertEquals(policyTypePostCreate.getDescription(), policyTypePreCreate.getDescription()); - - assertTrue(!StringUtils.isEmpty(policyTypePostCreate.getUniqueId())); - } - - @Test - public void testGetLatestPolicyTypeByType() { - PolicyTypeDefinition policyTypeCreated = policyTypeOperation.addPolicyType(createPolicyTypeDef()).left().value(); - Either eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyTypeCreated.getType()); - assertTrue(eitherPolicyTypeFetched.isLeft()); - PolicyTypeDefinition policyTypeFetched = eitherPolicyTypeFetched.left().value(); - assertEquals(policyTypeFetched.toString(), policyTypeCreated.toString()); - } - - @Test - public void testGetLatestPolicyTypeByType_derivedFromFetchedCorrectly() { - PolicyTypeDefinition rootPolicyType = createRootPolicyTypeOnGraph(); - String derivedFromRootType = rootPolicyType.getType(); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", derivedFromRootType); - policyTypeOperation.addPolicyType(policyType1); - Either eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); - assertThat(eitherPolicyTypeFetched.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); - } - - @Test - public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain_policyTypeHasNoDirectProps() { - PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); - PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", null, prop1, prop2); - PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc3", policyType1.getType(), null); - addPolicyTypesToDB(policyType1, policyType2); - Either latestPolicyType2 = policyTypeOperation.getLatestPolicyTypeByType(policyType2.getType()); - assertThat(latestPolicyType2.isLeft()); - assertThat(latestPolicyType2.left().value().getProperties()) - .usingElementComparatorOnFields("defaultValue", "name", "type") - .containsExactlyInAnyOrder(prop1, prop2); - } - - @Test - public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain() { - PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); - PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); - PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); - - PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(prop1); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", rootPolicyType.getType(), null); - PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc2", policyType1.getType(), prop2); - PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.type3", "desc3", policyType2.getType(), null); - PolicyTypeDefinition policyType4 = createPolicyTypeDef("tosca.policies.type4", "desc4", policyType3.getType(), prop3); - - addPolicyTypesToDB(rootPolicyType, policyType1, policyType2, policyType3, policyType4); - - Either latestPolicyType3 = policyTypeOperation.getLatestPolicyTypeByType(policyType4.getType()); - assertThat(latestPolicyType3.isLeft()); - assertThat(latestPolicyType3.left().value().getProperties()) - .usingElementComparatorOnFields("defaultValue", "name", "type") - .containsExactlyInAnyOrder(prop1, prop2, prop3); - } - - @Test - public void getAllPolicyTypes_noPolicies() { - Either, StorageOperationStatus> allPolicyTypes = policyTypeOperation.getAllPolicyTypes(null); - assertThat(allPolicyTypes.isRight()); - assertThat(allPolicyTypes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); - } - - @Test - public void getAllPolicyTypes() { - PolicyTypeDefinition policyType1 = createPolicyTypeDef(); - PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root"); - addPolicyTypesToDB(policyType1, policyType2); - Either, StorageOperationStatus> allPolicyTypesWithNoExcluded = policyTypeOperation.getAllPolicyTypes(null); - assertThat(allPolicyTypesWithNoExcluded.left().value()).hasSize(2); - assertThat(allPolicyTypesWithNoExcluded.left().value()).usingElementComparatorOnFields("uniqueId", "description", "version", "type") - .containsExactlyInAnyOrder(policyType1, policyType2); - } - - @Test - public void getAllPolicyTypes_whenPassingExcludedTypeList_dontReturnExcludedTypes() { - PolicyTypeDefinition policyType1 = createPolicyTypeDef(); - PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root"); - PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.test2", "desc2", "tosca.policies.Root"); - policyTypeOperation.addPolicyType(policyType1); - policyTypeOperation.addPolicyType(policyType2); - policyTypeOperation.addPolicyType(policyType3); - Either, StorageOperationStatus> allPolicyTypes = policyTypeOperation.getAllPolicyTypes(newHashSet("tosca.policies.test1", "tosca.policies.test2")); - assertThat(allPolicyTypes.left().value()).hasSize(1); - assertThat(allPolicyTypes.left().value()).usingElementComparatorOnFields("type") - .containsExactly(policyType1); - } - - @Test + private static final String NULL_STRING = null; + @Autowired + private PolicyTypeOperation policyTypeOperation; + + @Autowired + private TitanGenericDao titanGenericDao; + + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + + } + + @Before + public void cleanUp() { + TitanGenericDao titanGenericDao = policyTypeOperation.titanGenericDao; + Either graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanGenericDao.commit(); + } + + @Test + public void testAddPolicyType() { + PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef(); + assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId())); + Either addPolicyType = policyTypeOperation.addPolicyType(policyTypePreCreate); + assertTrue(addPolicyType.isLeft()); + PolicyTypeDefinition policyTypePostCreate = addPolicyType.left().value(); + assertThat(policyTypePostCreate.getUniqueId()).isNotEmpty(); + assertThat(policyTypePostCreate) + .isEqualToComparingOnlyGivenFields(policyTypePreCreate, "name", "icon", "description", "type"); + } + + @Test + public void testGetLatestPolicyTypeByType() { + PolicyTypeDefinition policyTypeCreated = policyTypeOperation.addPolicyType(createPolicyTypeDef()).left().value(); + Either eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyTypeCreated.getType()); + assertTrue(eitherPolicyTypeFetched.isLeft()); + PolicyTypeDefinition policyTypeFetched = eitherPolicyTypeFetched.left().value(); + assertEquals(policyTypeFetched.toString(), policyTypeCreated.toString()); + } + + @Test + public void testGetLatestPolicyTypeByType_derivedFromFetchedCorrectly() { + PolicyTypeDefinition rootPolicyType = createRootPolicyTypeOnGraph(); + String derivedFromRootType = rootPolicyType.getType(); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", derivedFromRootType); + policyTypeOperation.addPolicyType(policyType1); + Either eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); + assertThat(eitherPolicyTypeFetched.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); + } + + @Test + public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain_policyTypeHasNoDirectProps() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", null, prop1, prop2); + PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc3", policyType1.getType(), null); + addPolicyTypesToDB(policyType1, policyType2); + Either latestPolicyType2 = policyTypeOperation.getLatestPolicyTypeByType(policyType2.getType()); + assertThat(latestPolicyType2.isLeft()).isTrue(); + assertThat(latestPolicyType2.left().value().getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type") + .containsExactlyInAnyOrder(prop1, prop2); + } + + @Test + public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + + PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(prop1); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", rootPolicyType.getType(), null); + PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc2", policyType1.getType(), prop2); + PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.type3", "desc3", policyType2.getType(), null); + PolicyTypeDefinition policyType4 = createPolicyTypeDef("tosca.policies.type4", "desc4", policyType3.getType(), prop3); + + addPolicyTypesToDB(rootPolicyType, policyType1, policyType2, policyType3, policyType4); + + Either latestPolicyType3 = policyTypeOperation.getLatestPolicyTypeByType(policyType4.getType()); + assertThat(latestPolicyType3.isLeft()).isTrue(); + assertThat(latestPolicyType3.left().value().getProperties()) + .usingElementComparatorOnFields("defaultValue", "name", "type") + .containsExactlyInAnyOrder(prop1, prop2, prop3); + } + + @Test(expected = StorageException.class) + public void getAllPolicyTypes_noPolicies() { + policyTypeOperation.getAllPolicyTypes(null); + } + + @Test + public void getAllPolicyTypes() { + PolicyTypeDefinition policyType1 = createPolicyTypeDef(); + PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root"); + addPolicyTypesToDB(policyType1, policyType2); + List allPolicyTypesWithNoExcluded = policyTypeOperation.getAllPolicyTypes(null); + assertThat(allPolicyTypesWithNoExcluded).hasSize(2); + assertThat(allPolicyTypesWithNoExcluded).usingElementComparatorOnFields("uniqueId", "description", "version", "type") + .containsExactlyInAnyOrder(policyType1, policyType2); + } + + @Test + public void getAllPolicyTypes_whenPassingExcludedTypeList_dontReturnExcludedTypes() { + PolicyTypeDefinition policyType1 = createPolicyTypeDef(); + PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root"); + PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.test2", "desc2", "tosca.policies.Root"); + policyTypeOperation.addPolicyType(policyType1); + policyTypeOperation.addPolicyType(policyType2); + policyTypeOperation.addPolicyType(policyType3); + List allPolicyTypes = policyTypeOperation.getAllPolicyTypes(newHashSet("tosca.policies.test1", "tosca.policies.test2")); + assertThat(allPolicyTypes).hasSize(1); + assertThat(allPolicyTypes).usingElementComparatorOnFields("type") + .containsExactly(policyType1); + } + + @Test public void addPolicyType_whenDerivedFromNodeNotExist_returnNotFound() { PolicyTypeDefinition type1 = createPolicyTypeDef("tosca.policies.type1", "desc1", "derivedFrom"); Either addedPolicyTypeResult = policyTypeOperation.addPolicyType(type1); @@ -199,7 +194,7 @@ public class PolicyTypeOperationTest extends ModelTestBase { } @Test//bug379696 - public void addPolicyType_derivedFromAddedCorrectly() { + public void addPolicyType_derivedFromAddedCorrectly() { PolicyTypeDefinition rootPolicyType = createRootPolicyTypeOnGraph(); String derivedFromRootType = rootPolicyType.getType(); PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", derivedFromRootType); @@ -207,174 +202,171 @@ public class PolicyTypeOperationTest extends ModelTestBase { assertThat(addedPolicyTypeResult.isLeft()).isTrue(); Either fetchedPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); - PolicyTypeDefinition fetchedPolicyTypeVal = fetchedPolicyType.left().value(); - assertThat(fetchedPolicyTypeVal.getDerivedFrom()).isEqualTo(derivedFromRootType); - verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, fetchedPolicyTypeVal.getUniqueId()); - - } - - @Test - public void updatePolicyType_returnNotFoundErrorIfTryingToUpdateANonExistingType() { - PolicyTypeDefinition currType = createPolicyTypeDef(); - PolicyTypeDefinition updatedType = createPolicyTypeDef(); - Either updatePolicyTypeRes = policyTypeOperation.updatePolicyType(updatedType, currType); - assertThat(updatePolicyTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); - } - - @Test - public void updatePolicyType_basicFields() { - PolicyTypeDefinition createdType = createPolicyTypeDef("type1", "description1", NULL_STRING); - Either currPolicyType = policyTypeOperation.addPolicyType(createdType); - - PolicyTypeDefinition updatedType = createPolicyTypeDef("type1", "description2", NULL_STRING); - policyTypeOperation.updatePolicyType(updatedType, currPolicyType.left().value()); - - Either fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(createdType.getType()); - PolicyTypeDefinition fetchedPolicyType = fetchedUpdatedType.left().value(); - assertThat(fetchedPolicyType.getProperties()).isEmpty(); - assertThat(fetchedPolicyType) - .isEqualToIgnoringGivenFields(updatedType, "properties"); - - } - - @Test - public void updatePolicyType_updateProperties() { - PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); - PolicyTypeDefinition policyType = createPolicyTypeDef(prop1); - Either currPolicyType = policyTypeOperation.addPolicyType(policyType); - - PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); - PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); - PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef(updatedProp1, prop2); - - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(policyType.getType()); - assertThat(fetchedUpdatedType.left().value().getProperties()) - .usingElementComparatorOnFields("name", "defaultValue", "type") - .containsExactlyInAnyOrder(updatedProp1, prop2); - - } - - @Test - public void updatePolicyType_derivedFrom_whenNoPrevDerivedFrom_updateToNewDerivedFrom() { - PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", NULL_STRING); - PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); - policyTypeOperation.addPolicyType(rootPolicyType); - Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); - assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); - verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId()); - } - - @Test - public void updatePolicyType_derivedFrom_updateToNullDerivedFrom_derivedFromDeleted() { - PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); - PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", null, new PropertyDefinition[]{}); - policyTypeOperation.addPolicyType(rootPolicyType); - Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); - - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); - assertThat(latestPolicyType.left().value().getDerivedFrom()).isNull(); - verifyDerivedFromRelationDoesntExist(latestPolicyType.left().value().getUniqueId()); - } - - @Test - public void updatePolicyType_updateDerivedFrom() { - PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); - PolicyTypeDefinition derivedType1 = createPolicyTypeDef("derivedType1", "descr", NULL_STRING); - PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", derivedType1.getType()); - PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); - - policyTypeOperation.addPolicyType(rootPolicyType); - policyTypeOperation.addPolicyType(derivedType1); - Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); - - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); - assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); - verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId()); - } - - private PropertyDefinition duplicateProperty(PropertyDefinition prop1, String updatedValue, String updatedType) { - PropertyDefinition updatedProp1 = new PropertyDefinition(prop1); - updatedProp1.setUniqueId(null); - updatedProp1.setDefaultValue(updatedValue); - updatedProp1.setType(updatedType); - return updatedProp1; - } - - private PropertyDefinition createSimpleProperty(String defaultValue, String name, String type) { - PropertyDefinition prop1 = new PropertyDefinition(); - prop1.setDefaultValue(defaultValue); - prop1.setName(name); - prop1.setType(type); - return prop1; - } - - private void verifyDerivedFromNodeEqualsToRootPolicyType(PolicyTypeDefinition rootPolicyType, String parentPolicyId) { - Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.PolicyType, PolicyTypeData.class); - assertThat(derivedFromRelation.left().value().getLeft().getPolicyTypeDataDefinition()) - .isEqualToComparingFieldByField(rootPolicyType); - } - - private void verifyDerivedFromRelationDoesntExist(String parentPolicyId) { - Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.PolicyType, PolicyTypeData.class); - assertThat(derivedFromRelation.right().value()) - .isEqualTo(TitanOperationStatus.NOT_FOUND); - } - - private PolicyTypeDefinition createRootPolicyTypeOnGraph() { + PolicyTypeDefinition fetchedPolicyTypeVal = fetchedPolicyType.left().value(); + assertThat(fetchedPolicyTypeVal.getDerivedFrom()).isEqualTo(derivedFromRootType); + verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, fetchedPolicyTypeVal.getUniqueId()); + + } + + @Test + public void updatePolicyType_returnNotFoundErrorIfTryingToUpdateANonExistingType() { + PolicyTypeDefinition currType = createPolicyTypeDef(); + PolicyTypeDefinition updatedType = createPolicyTypeDef(); + Either updatePolicyTypeRes = policyTypeOperation.updatePolicyType(updatedType, currType); + assertThat(updatePolicyTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + } + + @Test + public void updatePolicyType_basicFields() { + PolicyTypeDefinition createdType = createPolicyTypeDef("type1", "description1", NULL_STRING); + Either currPolicyType = policyTypeOperation.addPolicyType(createdType); + + PolicyTypeDefinition updatedType = createPolicyTypeDef("type1", "description2", NULL_STRING); + updatedType.setName("newName"); + updatedType.setIcon("icon"); + policyTypeOperation.updatePolicyType(updatedType, currPolicyType.left().value()); + + Either fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(createdType.getType()); + PolicyTypeDefinition fetchedPolicyType = fetchedUpdatedType.left().value(); + assertThat(fetchedPolicyType.getProperties()).isEmpty(); + assertThat(fetchedPolicyType) + .isEqualToIgnoringGivenFields(updatedType, "properties"); + + } + + @Test + public void updatePolicyType_updateProperties() { + PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string"); + PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string"); + PolicyTypeDefinition policyType = createPolicyTypeDef(prop1); + Either currPolicyType = policyTypeOperation.addPolicyType(policyType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef(updatedProp1, prop3); + + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(policyType.getType()); + assertThat(fetchedUpdatedType.left().value().getProperties()) + .usingElementComparatorOnFields("name", "defaultValue", "type") + .containsExactlyInAnyOrder(updatedProp1, prop3); + + } + + @Test + public void updatePolicyType_derivedFrom_whenNoPrevDerivedFrom_updateToNewDerivedFrom() { + PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", NULL_STRING); + PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); + policyTypeOperation.addPolicyType(rootPolicyType); + Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); + assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); + verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId()); + } + + @Test + public void updatePolicyType_derivedFrom_updateToNullDerivedFrom_derivedFromDeleted() { + PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); + PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", null, new PropertyDefinition[]{}); + policyTypeOperation.addPolicyType(rootPolicyType); + Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); + + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); + assertThat(latestPolicyType.left().value().getDerivedFrom()).isNull(); + verifyDerivedFromRelationDoesntExist(latestPolicyType.left().value().getUniqueId()); + } + + @Test + public void updatePolicyType_updateDerivedFrom() { + PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); + PolicyTypeDefinition derivedType1 = createPolicyTypeDef("derivedType1", "descr", NULL_STRING); + PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", derivedType1.getType()); + PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType()); + + policyTypeOperation.addPolicyType(rootPolicyType); + policyTypeOperation.addPolicyType(derivedType1); + Either currPolicyType = policyTypeOperation.addPolicyType(policyType1); + + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType()); + assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType()); + verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId()); + } + + private PropertyDefinition duplicateProperty(PropertyDefinition prop1, String updatedValue, String updatedType) { + PropertyDefinition updatedProp1 = new PropertyDefinition(prop1); + updatedProp1.setUniqueId(null); + updatedProp1.setDefaultValue(updatedValue); + updatedProp1.setType(updatedType); + return updatedProp1; + } + + private void verifyDerivedFromNodeEqualsToRootPolicyType(PolicyTypeDefinition rootPolicyType, String parentPolicyId) { + Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.PolicyType, PolicyTypeData.class); + assertThat(derivedFromRelation.left().value().getLeft().getPolicyTypeDataDefinition()) + .isEqualToComparingFieldByField(rootPolicyType); + } + + private void verifyDerivedFromRelationDoesntExist(String parentPolicyId) { + Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.PolicyType, PolicyTypeData.class); + assertThat(derivedFromRelation.right().value()) + .isEqualTo(TitanOperationStatus.NOT_FOUND); + } + + private PolicyTypeDefinition createRootPolicyTypeOnGraph() { PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(); policyTypeOperation.addPolicyType(rootPolicyType); return rootPolicyType; } - private PolicyTypeDefinition createPolicyTypeDef() { - return createPolicyTypeDef("tosca.policies.Root", "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", null, new PropertyDefinition[]{}); - } - - private PolicyTypeDefinition createPolicyTypeDef(PropertyDefinition ... props) { - return createPolicyTypeDef("tosca.policies.Root", null, props); - } - - private PolicyTypeDefinition createPolicyTypeDef(String type, String derivedFrom, PropertyDefinition ... props) { - PolicyTypeDefinition policyType = createPolicyTypeDef(type, "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", derivedFrom); - policyType.setProperties(asList(props)); - return policyType; - } - - private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom) { - return createPolicyTypeDef(type, description, derivedFrom, null); - } - - private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom, PropertyDefinition ... props) { - PolicyTypeDataDefinition policyTypeDataDefinition = new PolicyTypeDataDefinition(); - policyTypeDataDefinition.setDescription(description); - policyTypeDataDefinition.setType(type); - policyTypeDataDefinition.setDerivedFrom(derivedFrom); - PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeDataDefinition); - policyTypeDefinition.setHighestVersion(true); - policyTypeDefinition.setVersion("1.0"); - if (props != null) { - policyTypeDefinition.setProperties(asList(props)); - } - return policyTypeDefinition; - } - - private void addPolicyTypesToDB(PolicyTypeDefinition ... policyTypeDefinitions) { - Stream.of(policyTypeDefinitions).forEach(policyTypeOperation::addPolicyType); - } + private PolicyTypeDefinition createPolicyTypeDef() { + return createPolicyTypeDef("tosca.policies.Root", "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", null, new PropertyDefinition[]{}); + } + + private PolicyTypeDefinition createPolicyTypeDef(PropertyDefinition ... props) { + return createPolicyTypeDef("tosca.policies.Root", null, props); + } + + private PolicyTypeDefinition createPolicyTypeDef(String type, String derivedFrom, PropertyDefinition ... props) { + PolicyTypeDefinition policyType = createPolicyTypeDef(type, "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", derivedFrom); + policyType.setProperties(asList(props)); + return policyType; + } + + private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom) { + return createPolicyTypeDef(type, description, derivedFrom, null); + } + + private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom, PropertyDefinition ... props) { + PolicyTypeDataDefinition policyTypeDataDefinition = new PolicyTypeDataDefinition(); + policyTypeDataDefinition.setDescription(description); + policyTypeDataDefinition.setType(type); + policyTypeDataDefinition.setName(type + "name"); + policyTypeDataDefinition.setIcon(type + "icon"); + policyTypeDataDefinition.setDerivedFrom(derivedFrom); + PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeDataDefinition); + policyTypeDefinition.setHighestVersion(true); + policyTypeDefinition.setVersion("1.0"); + if (props != null) { + policyTypeDefinition.setProperties(asList(props)); + } + return policyTypeDefinition; + } + + private void addPolicyTypesToDB(PolicyTypeDefinition ... policyTypeDefinitions) { + Stream.of(policyTypeDefinitions).forEach(policyTypeOperation::addPolicyType); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java index 612dd7bf21..17d0586e32 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java @@ -20,19 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Assert; import org.junit.Before; @@ -44,12 +33,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.ToscaType; @@ -60,490 +44,469 @@ import org.openecomp.sdc.be.resources.data.DataTypeData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.be.resources.data.PropertyValueData; -import com.thinkaurelius.titan.core.TitanVertex; +import java.util.*; -import fj.data.Either; +import static org.junit.Assert.*; public class PropertyOperationTest extends ModelTestBase { - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - - PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao, null); - - @Before - public void setup() { - propertyOperation.setTitanGenericDao(titanGenericDao); - - } - - /* - * @Test public void addPropertyToResourceTest() { - * - * String propName = "myProp"; PropertyDefinition property = - * buildPropertyDefinition(); List constraints = - * buildConstraints(); property.setConstraints(constraints); - * - * PropertyData propertyData = new PropertyData(property, - * propertyOperation.convertConstraintsToString(constraints)); - * - * Either either = - * Either.left(propertyData); - * //when(propertyDao.create((GraphNeighbourTable)anyObject(), - * eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); - * GraphRelation graphRelation = new GraphRelation(); Either relationResult = Either.left(graphRelation); - * - * when(titanGenericDao.createNode((PropertyData)anyObject(), - * eq(PropertyData.class))).thenReturn(either); - * when(titanGenericDao.createRelation((GraphNode)anyObject(), - * (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY), - * anyMap())).thenReturn(relationResult); - * - * Either result = - * propertyOperation.addPropertyToResource(propName, property, - * NodeTypeEnum.Resource, "my-resource.1.0"); - * - * assertTrue(result.isLeft()); System.out.println(result.left().value()); - * PropertyDefinition propertyDefinition = result.left().value(); - * - * List originalConstraints = property.getConstraints(); - * List propertyConstraintsResult = - * propertyDefinition.getConstraints(); - * assertEquals(propertyConstraintsResult.size(), - * originalConstraints.size()); - * - * } - */ - private PropertyDefinition buildPropertyDefinition() { - PropertyDefinition property = new PropertyDefinition(); - property.setDefaultValue("10"); - property.setDescription( - "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property.setType(ToscaType.INTEGER.name().toLowerCase()); - return property; - } - - @Test - public void addPropertiesToGraphTableTest() { - - // Map properties = new HashMap(); - // String propName = "myProp"; - // PropertyDefinition property = buildPropertyDefinition(); - // - // List constraints = buildConstraints(); - // property.setConstraints(constraints); - // - // properties.put(propName, property); - // - // GraphNeighbourTable graphNeighbourTable = new GraphNeighbourTable(); - // ResourceData resourceData = new ResourceData(); - // String resourceName = "my-resource"; - // String resourceVersion = "1.0"; - // String resourceId = resourceName + "." + resourceVersion; - // resourceData.setUniqueId(resourceId); - // int resourceIndex = graphNeighbourTable.addNode(resourceData); - // - // heatParametersOperation.addPropertiesToGraphTable(properties, - // graphNeighbourTable, resourceIndex, resourceId); - // - // assertEquals(2, graphNeighbourTable.getNodes().size()); - // assertEquals(1, graphNeighbourTable.getDirectedEdges().size()); - // List nodes = graphNeighbourTable.getNodes(); - // boolean nodeFound = false; - // for (GraphNode neo4jNode : nodes) { - // if (neo4jNode instanceof PropertyData) { - // PropertyData propertyData = (PropertyData)neo4jNode; - // assertEquals("check property unique id", resourceId + "." + propName, - // propertyData.getUniqueId()); - // assertEquals(property.getDescription(), - // propertyData.getPropertyDataDefinition().getDescription()); - // nodeFound = true; - // } - // } - // assertEquals("looking for PropertyData object in table", true, - // nodeFound); - // - // NodeRelation nodeRelation = - // graphNeighbourTable.getDirectedEdges().get(0); - // assertEquals("check from index to index edge", 0, - // nodeRelation.getFromIndex()); - // assertEquals("check from index to index edge", 1, - // nodeRelation.getToIndex()); - // assertEquals("check edge type", - // GraphEdgePropertiesDictionary.PROPERTY, - // nodeRelation.getEdge().getEdgeType()); - // assertEquals("check propert name on edge", true, - // nodeRelation.getEdge().getProperties().values().contains(propName)); - } - - @Test - public void convertConstraintsTest() { - - List constraints = buildConstraints(); - List convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints); - assertEquals("constraints size", constraints.size(), convertedStringConstraints.size()); - - List convertedConstraints = propertyOperation - .convertConstraints(convertedStringConstraints); - assertEquals("check size of constraints", constraints.size(), convertedConstraints.size()); - - Set constraintsClasses = new HashSet(); - for (PropertyConstraint propertyConstraint : constraints) { - constraintsClasses.add(propertyConstraint.getClass().getName()); - } - - for (PropertyConstraint propertyConstraint : convertedConstraints) { - assertTrue("check all classes generated", - constraintsClasses.contains(propertyConstraint.getClass().getName())); - } - } - - @Test - public void testIsPropertyDefaultValueValid_NoDefault() { - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.BOOLEAN.getType()); - assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); - } - - @Test - public void testIsPropertyDefaultValueValid_ValidDefault() { - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("50"); - assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); - } - - @Test - public void testIsPropertyDefaultValueValid_InvalidDefault() { - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.BOOLEAN.getType()); - property.setDefaultValue("50"); - assertFalse(propertyOperation.isPropertyDefaultValueValid(property, null)); - } - - private List buildConstraints() { - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - List range = new ArrayList(); - range.add("0"); - range.add("100"); - InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); - constraints.add(propertyConstraint1); - constraints.add(propertyConstraint2); - constraints.add(propertyConstraint3); - return constraints; - } - - @Test - public void findPropertyValueBestMatch1() { - - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - instanceIdToValue.put("node1", instanceProperty1); - - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); - instanceIdToValue.put("node2", instanceProperty2); - - ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); - instanceProperty3.setValue("v1node3"); - instanceIdToValue.put("node3", instanceProperty3); - - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", "v1node1", instanceProperty.getValue()); - assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); - - } - - @Test - public void findPropertyValueBestMatch2() { - - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); - instanceProperty2.setValueUniqueUid("aaaa"); - instanceIdToValue.put("node2", instanceProperty2); - - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", "v1node2", instanceProperty.getValue()); - assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); - assertNull("check value unique id is null", instanceProperty.getValueUniqueUid()); - - } - - @Test - public void findPropertyValueBestMatch3() { - - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - instanceProperty1.setValueUniqueUid("aaaa"); - instanceIdToValue.put("node1", instanceProperty1); - - ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); - instanceProperty3.setValue("v1node3"); - instanceIdToValue.put("node3", instanceProperty3); - - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", "v1node1", instanceProperty.getValue()); - assertEquals("check default value", "v1node3", instanceProperty.getDefaultValue()); - assertEquals("check valid unique id", instanceProperty1.getValueUniqueUid(), - instanceProperty.getValueUniqueUid()); - - } - - @Test - public void findPropertyValueBestMatch1Rules() { - - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - - List rules = new ArrayList<>(); - PropertyRule propertyRule = new PropertyRule(); - String[] ruleArr = { "node1", ".+", "node3" }; - List rule1 = new ArrayList<>(Arrays.asList(ruleArr)); - propertyRule.setRule(rule1); - propertyRule.setValue("88"); - rules.add(propertyRule); - instanceProperty1.setRules(rules); - - instanceIdToValue.put("node1", instanceProperty1); - - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); - instanceIdToValue.put("node2", instanceProperty2); - - ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); - instanceProperty3.setValue("v1node3"); - instanceIdToValue.put("node3", instanceProperty3); - - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", propertyRule.getValue(), instanceProperty.getValue()); - assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); - - } - - @Test - public void findPropertyValueBestMatch2Rules() { - - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - - List rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); - propertyRule1.setRule(rule1); - propertyRule1.setValue("88"); - - PropertyRule propertyRule2 = new PropertyRule(); - String[] ruleArr2 = { "node1", "node2", "node3" }; - List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); - propertyRule2.setRule(rule2); - propertyRule2.setValue("99"); - - rules.add(propertyRule2); - rules.add(propertyRule1); - - instanceProperty1.setRules(rules); - - instanceIdToValue.put("node1", instanceProperty1); - - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); - instanceIdToValue.put("node2", instanceProperty2); - - ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); - instanceProperty3.setValue("v1node3"); - instanceIdToValue.put("node3", instanceProperty3); - - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); - assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); - - } - - @Test - public void findPropertyValueBestMatch1RuleLowLevel() { + TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + + PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao, null); + + @Before + public void setup() { + propertyOperation.setTitanGenericDao(titanGenericDao); + + } + + /* + * @Test public void addPropertyToResourceTest() { + * + * String propName = "myProp"; PropertyDefinition property = buildPropertyDefinition(); List constraints = buildConstraints(); property.setConstraints(constraints); + * + * PropertyData propertyData = new PropertyData(property, propertyOperation.convertConstraintsToString(constraints)); + * + * Either either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation = + * new GraphRelation(); Either relationResult = Either.left(graphRelation); + * + * when(titanGenericDao.createNode((PropertyData)anyObject(), eq(PropertyData.class))).thenReturn(either); when(titanGenericDao.createRelation((GraphNode)anyObject(), (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY), + * anyMap())).thenReturn(relationResult); + * + * Either result = propertyOperation.addPropertyToResource(propName, property, NodeTypeEnum.Resource, "my-resource.1.0"); + * + * assertTrue(result.isLeft()); System.out.println(result.left().value()); PropertyDefinition propertyDefinition = result.left().value(); + * + * List originalConstraints = property.getConstraints(); List propertyConstraintsResult = propertyDefinition.getConstraints(); assertEquals(propertyConstraintsResult.size(), originalConstraints.size()); + * + * } + */ + private PropertyDefinition buildPropertyDefinition() { + PropertyDefinition property = new PropertyDefinition(); + property.setDefaultValue("10"); + property.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property.setType(ToscaType.INTEGER.name().toLowerCase()); + return property; + } + + @Test + public void addPropertiesToGraphTableTest() { + + // Map properties = new HashMap(); + // String propName = "myProp"; + // PropertyDefinition property = buildPropertyDefinition(); + // + // List constraints = buildConstraints(); + // property.setConstraints(constraints); + // + // properties.put(propName, property); + // + // GraphNeighbourTable graphNeighbourTable = new GraphNeighbourTable(); + // ResourceData resourceData = new ResourceData(); + // String resourceName = "my-resource"; + // String resourceVersion = "1.0"; + // String resourceId = resourceName + "." + resourceVersion; + // resourceData.setUniqueId(resourceId); + // int resourceIndex = graphNeighbourTable.addNode(resourceData); + // + // heatParametersOperation.addPropertiesToGraphTable(properties, + // graphNeighbourTable, resourceIndex, resourceId); + // + // assertEquals(2, graphNeighbourTable.getNodes().size()); + // assertEquals(1, graphNeighbourTable.getDirectedEdges().size()); + // List nodes = graphNeighbourTable.getNodes(); + // boolean nodeFound = false; + // for (GraphNode neo4jNode : nodes) { + // if (neo4jNode instanceof PropertyData) { + // PropertyData propertyData = (PropertyData)neo4jNode; + // assertEquals("check property unique id", resourceId + "." + propName, + // propertyData.getUniqueId()); + // assertEquals(property.getDescription(), + // propertyData.getPropertyDataDefinition().getDescription()); + // nodeFound = true; + // } + // } + // assertEquals("looking for PropertyData object in table", true, + // nodeFound); + // + // NodeRelation nodeRelation = + // graphNeighbourTable.getDirectedEdges().get(0); + // assertEquals("check from index to index edge", 0, + // nodeRelation.getFromIndex()); + // assertEquals("check from index to index edge", 1, + // nodeRelation.getToIndex()); + // assertEquals("check edge type", + // GraphEdgePropertiesDictionary.PROPERTY, + // nodeRelation.getEdge().getEdgeType()); + // assertEquals("check propert name on edge", true, + // nodeRelation.getEdge().getProperties().values().contains(propName)); + } + + @Test + public void convertConstraintsTest() { + + List constraints = buildConstraints(); + List convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints); + assertEquals("constraints size", constraints.size(), convertedStringConstraints.size()); + + List convertedConstraints = propertyOperation.convertConstraints(convertedStringConstraints); + assertEquals("check size of constraints", constraints.size(), convertedConstraints.size()); + + Set constraintsClasses = new HashSet<>(); + for (PropertyConstraint propertyConstraint : constraints) { + constraintsClasses.add(propertyConstraint.getClass().getName()); + } + + for (PropertyConstraint propertyConstraint : convertedConstraints) { + assertTrue("check all classes generated", constraintsClasses.contains(propertyConstraint.getClass().getName())); + } + } + + @Test + public void testIsPropertyDefaultValueValid_NoDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.BOOLEAN.getType()); + assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + @Test + public void testIsPropertyDefaultValueValid_ValidDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("50"); + assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + @Test + public void testIsPropertyDefaultValueValid_InvalidDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.BOOLEAN.getType()); + property.setDefaultValue("50"); + assertFalse(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + private List buildConstraints() { + List constraints = new ArrayList<>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + List range = new ArrayList<>(); + range.add("0"); + range.add("100"); + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints.add(propertyConstraint1); + constraints.add(propertyConstraint2); + constraints.add(propertyConstraint3); + return constraints; + } + + @Test + public void findPropertyValueBestMatch1() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node1", instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch2() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceProperty2.setValueUniqueUid("aaaa"); + instanceIdToValue.put("node2", instanceProperty2); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node2", instanceProperty.getValue()); + assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); + assertNull("check value unique id is null", instanceProperty.getValueUniqueUid()); + + } + + @Test + public void findPropertyValueBestMatch3() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + instanceProperty1.setValueUniqueUid("aaaa"); + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node1", instanceProperty.getValue()); + assertEquals("check default value", "v1node3", instanceProperty.getDefaultValue()); + assertEquals("check valid unique id", instanceProperty1.getValueUniqueUid(), instanceProperty.getValueUniqueUid()); + + } + + @Test + public void findPropertyValueBestMatch1Rules() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List rules = new ArrayList<>(); + PropertyRule propertyRule = new PropertyRule(); + String[] ruleArr = { "node1", ".+", "node3" }; + List rule1 = new ArrayList<>(Arrays.asList(ruleArr)); + propertyRule.setRule(rule1); + propertyRule.setValue("88"); + rules.add(propertyRule); + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch2Rules() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); + List rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); + + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); + + rules.add(propertyRule2); + rules.add(propertyRule1); + + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch1RuleLowLevel() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); - List rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); - propertyRule1.setRule(rule1); - propertyRule1.setValue("88"); + rules.add(propertyRule2); + rules.add(propertyRule1); - PropertyRule propertyRule2 = new PropertyRule(); - String[] ruleArr2 = { "node1", "node2", "node3" }; - List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); - propertyRule2.setRule(rule2); - propertyRule2.setValue("99"); + instanceProperty1.setRules(rules); - rules.add(propertyRule2); - rules.add(propertyRule1); + instanceIdToValue.put("node1", instanceProperty1); - instanceProperty1.setRules(rules); + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); - instanceIdToValue.put("node1", instanceProperty1); + List rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node3" }; + List rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); + propertyRule3.setRule(rule3); + propertyRule3.setValue("77"); + rules3.add(propertyRule3); - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); + instanceProperty2.setRules(rules3); + instanceIdToValue.put("node2", instanceProperty2); - List rules3 = new ArrayList<>(); - PropertyRule propertyRule3 = new PropertyRule(); - String[] ruleArr3 = { "node2", "node3" }; - List rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); - propertyRule3.setRule(rule3); - propertyRule3.setValue("77"); - rules3.add(propertyRule3); + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); - instanceProperty2.setRules(rules3); - instanceIdToValue.put("node2", instanceProperty2); + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); - instanceProperty3.setValue("v1node3"); - instanceIdToValue.put("node3", instanceProperty3); + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", propertyRule3.getValue(), instanceProperty.getDefaultValue()); - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + } - assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); - assertEquals("check default value", propertyRule3.getValue(), instanceProperty.getDefaultValue()); + @Test + public void findPropertyValueBestMatchDefaultValueNotChanged() { - } + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); - @Test - public void findPropertyValueBestMatchDefaultValueNotChanged() { + Map instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map instanceIdToValue = new HashMap(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); + List rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); - List rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); - propertyRule1.setRule(rule1); - propertyRule1.setValue("88"); + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); - PropertyRule propertyRule2 = new PropertyRule(); - String[] ruleArr2 = { "node1", "node2", "node3" }; - List rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); - propertyRule2.setRule(rule2); - propertyRule2.setValue("99"); + rules.add(propertyRule2); + rules.add(propertyRule1); - rules.add(propertyRule2); - rules.add(propertyRule1); + instanceProperty1.setRules(rules); - instanceProperty1.setRules(rules); + instanceIdToValue.put("node1", instanceProperty1); - instanceIdToValue.put("node1", instanceProperty1); + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); - ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); - instanceProperty2.setValue("v1node2"); + List rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node333" }; + List rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); + propertyRule3.setRule(rule3); + propertyRule3.setValue("77"); + rules3.add(propertyRule3); - List rules3 = new ArrayList<>(); - PropertyRule propertyRule3 = new PropertyRule(); - String[] ruleArr3 = { "node2", "node333" }; - List rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); - propertyRule3.setRule(rule3); - propertyRule3.setValue("77"); - rules3.add(propertyRule3); + instanceProperty2.setRules(rules3); + instanceIdToValue.put("node2", instanceProperty2); - instanceProperty2.setRules(rules3); - instanceIdToValue.put("node2", instanceProperty2); + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); - - assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); - assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); } @@ -573,38 +536,6 @@ public class PropertyOperationTest extends ModelTestBase { testSubject = createTestSubject(); result = testSubject.convertPropertyDataToPropertyDefinition(propertyDataResult, propertyName, resourceId); } - - - @Test - public void testAddPropertiesToGraph() throws Exception { - PropertyOperation testSubject; - Map properties = null; - String resourceId = ""; - Map dataTypes = null; - TitanOperationStatus result; - - // test 1 - testSubject = createTestSubject(); - properties = null; - result = testSubject.addPropertiesToGraph(properties, resourceId, dataTypes); - } - - - @Test - public void testAddPropertiesToGraph_1() throws Exception { - PropertyOperation testSubject; - TitanVertex metadataVertex = null; - Map properties = null; - Map dataTypes = null; - String resourceId = ""; - TitanOperationStatus result; - - // test 1 - testSubject = createTestSubject(); - properties = null; - result = testSubject.addPropertiesToGraph(metadataVertex, properties, dataTypes, resourceId); - } - @Test public void testAddProperty() throws Exception { @@ -673,19 +604,6 @@ public class PropertyOperationTest extends ModelTestBase { result = testSubject.getTitanGenericDao(); } - - @Test - public void testDeleteProperty() throws Exception { - PropertyOperation testSubject; - String propertyId = ""; - Either result; - - // default test - testSubject = createTestSubject(); - result = testSubject.deleteProperty(propertyId); - } - - @Test public void testDeletePropertyFromGraph() throws Exception { PropertyOperation testSubject; @@ -1183,29 +1101,4 @@ public class PropertyOperationTest extends ModelTestBase { testSubject = createTestSubject(); result = testSubject.updateDataType(newDataTypeDefinition, oldDataTypeDefinition); } - - - @Test - public void testIsValueToscaFunction() throws Exception { - PropertyOperation testSubject; - String type = ""; - String value = ""; - boolean result; - - // test 1 - testSubject = createTestSubject(); - value = null; - result = testSubject.isValueToscaFunction(type, value); - Assert.assertEquals(false, result); - - // test 2 - testSubject = createTestSubject(); - value = ""; - result = testSubject.isValueToscaFunction(type, value); - Assert.assertEquals(false, result); - } - - // add all rule types - // add rule with size = 1(instance itself = ALL). relevant for VLi. equals - // to X.*.*.* in all paths size } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java index 8f8baea22d..506bec4569 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java @@ -23,11 +23,7 @@ package org.openecomp.sdc.be.model.operations.impl; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.*; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -61,554 +57,555 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.*; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class ToscaElementLifecycleOperationTest extends ModelTestBase { - @javax.annotation.Resource - protected TitanDao titanDao; + @javax.annotation.Resource + protected TitanDao titanDao; - @javax.annotation.Resource - private NodeTypeOperation nodeTypeOperation; + @javax.annotation.Resource + private NodeTypeOperation nodeTypeOperation; - @javax.annotation.Resource - private TopologyTemplateOperation topologyTemplateOperation; + @javax.annotation.Resource + private TopologyTemplateOperation topologyTemplateOperation; - @javax.annotation.Resource - private ToscaElementLifecycleOperation lifecycleOperation; + @javax.annotation.Resource + private ToscaElementLifecycleOperation lifecycleOperation; - String categoryName = "category"; - String subcategory = "mycategory"; - String outputDirectory = "C:\\Output"; + String categoryName = "category"; + String subcategory = "mycategory"; + String outputDirectory = "C:\\Output"; - @Rule - public TestName name = new TestName(); + @Rule + public TestName name = new TestName(); - @BeforeClass - public static void initLifecycleOperation() { - ModelTestBase.init(); - } - - private GraphVertex ownerVertex; - private GraphVertex modifierVertex; - private GraphVertex vfVertex; - private GraphVertex serviceVertex; - private GraphVertex rootVertex; + @BeforeClass + public static void initLifecycleOperation() { + ModelTestBase.init(); + } - @Before - public void setupBefore() { - clearGraph(); - createUsers(); - createResourceCategory(); - createServiceCategory(); - GraphTestUtils.createRootCatalogVertex(titanDao); - rootVertex = createRootNodeType(); - createNodeType("firstVf"); - serviceVertex = createTopologyTemplate("firstService"); - } + private GraphVertex ownerVertex; + private GraphVertex modifierVertex; + private GraphVertex vfVertex; + private GraphVertex serviceVertex; + private GraphVertex rootVertex; - @Test - public void lifecycleTest() { - Either res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vfVertex.getMetadataProperty(GraphPropertyEnum.STATE)), vfVertex.getUniqueId(), modifierVertex.getUniqueId(), - ownerVertex.getUniqueId()); - StorageOperationStatus status; + @Before + public void setupBefore() { + clearGraph(); + createUsers(); + createResourceCategory(); + createServiceCategory(); + GraphTestUtils.createRootCatalogVertex(titanDao); + rootVertex = createRootNodeType(); + createNodeType("firstVf"); + serviceVertex = createTopologyTemplate("firstService"); + } - assertTrue(res.isLeft()); - // 1-node type - // 2-vf - // 3- service - verifyInCatalogData(3, null); + @Test + public void lifecycleTest() { + Either res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vfVertex.getMetadataProperty(GraphPropertyEnum.STATE)), vfVertex.getUniqueId(), modifierVertex.getUniqueId(), + ownerVertex.getUniqueId()); + StorageOperationStatus status; - String id = res.left().value().getUniqueId(); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - verifyInCatalogData(3, null); - - PropertyDataDefinition prop55 = new PropertyDataDefinition(); - prop55.setName("prop55"); - prop55.setDefaultValue("def55"); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - CapabilityDataDefinition cap1 = new CapabilityDataDefinition(); - cap1.setName("cap1"); - cap1.setDescription("create"); - cap1.setUniqueId(UniqueIdBuilder.buildCapabilityUid(id, "cap1")); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - prop55.setDefaultValue("AAAAAAAA"); - status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - cap1.setDescription("update"); - - status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - PropertyDataDefinition prop66 = new PropertyDataDefinition(); - prop66.setName("prop66"); - prop66.setDefaultValue("def66"); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop66, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - verifyInCatalogData(3, null); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - verifyInCatalogData(4, null); - - PropertyDataDefinition prop77 = new PropertyDataDefinition(); - prop77.setName("prop77"); - prop77.setDefaultValue("def77"); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop77, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - PropertyDataDefinition prop88 = new PropertyDataDefinition(); - prop88.setName("prop88"); - prop88.setDefaultValue("def88"); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop88, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - verifyInCatalogData(3, null); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - verifyInCatalogData(4, null); - - PropertyDataDefinition prop99 = new PropertyDataDefinition(); - prop99.setName("prop99"); - prop99.setDefaultValue("def99"); - - status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop99, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - status = nodeTypeOperation.deleteToscaDataElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, "prop99", JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - // cancel certification - res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - - // fail certification - res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertTrue(res.isLeft()); - id = res.left().value().getUniqueId(); - verifyInCatalogData(4, null); - // exportGraphMl(titanDao.getGraph().left().value()); - - } - - @Test - public void serviceConformanceLevelTest() { - Either res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) serviceVertex.getMetadataProperty(GraphPropertyEnum.STATE)), serviceVertex.getUniqueId(), - modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - - assertTrue(res.isLeft()); - String id = res.left().value().getUniqueId(); - - res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); - assertTrue(res.isLeft()); - - String conformanceLevel = res.left().value().getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL).toString(); - assertEquals(conformanceLevel, ModelTestBase.configurationManager.getConfiguration().getToscaConformanceLevel()); - } - - @Test - public void catalogTest() { - // start position - 3 in catalog - List expectedIds = new ArrayList(); - expectedIds.add(rootVertex.getUniqueId()); - expectedIds.add(vfVertex.getUniqueId()); - expectedIds.add(serviceVertex.getUniqueId()); - - verifyInCatalogData(3, expectedIds); - - GraphVertex vertex4 = createTopologyTemplate("topTemp4"); - expectedIds.add(vertex4.getUniqueId()); - verifyInCatalogData(4, expectedIds); - - Either res = lifecycleOperation.undoCheckout(vertex4.getUniqueId()); - expectedIds.remove(vertex4.getUniqueId()); - verifyInCatalogData(3, expectedIds); - - vertex4 = createTopologyTemplate("topTemp4"); - expectedIds.add(vertex4.getUniqueId()); - verifyInCatalogData(4, expectedIds); - - res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vertex4.getMetadataProperty(GraphPropertyEnum.STATE)), vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - Either certifyToscaElement = lifecycleOperation.certifyToscaElement(vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(certifyToscaElement.isLeft()); - expectedIds.remove(vertex4.getUniqueId()); - String certifiedId = certifyToscaElement.left().value().getUniqueId(); - expectedIds.add(certifiedId); - verifyInCatalogData(4, expectedIds); - - res = lifecycleOperation.checkoutToscaElement(certifiedId, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); - assertTrue(certifyToscaElement.isLeft()); - expectedIds.add(res.left().value().getUniqueId()); - verifyInCatalogData(5, expectedIds); - } - - private void createResourceCategory() { - - GraphVertex cat = new GraphVertex(VertexTypeEnum.RESOURCE_CATEGORY); - Map metadataProperties = new HashMap<>(); - String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); - cat.setUniqueId(catId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - cat.setMetadataProperties(metadataProperties); - cat.updateMetadataJsonWithCurrentMetadataProperties(); - - GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY); - metadataProperties = new HashMap<>(); - String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory); - subCat.setUniqueId(subCatId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, subcategory); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); - subCat.setMetadataProperties(metadataProperties); - subCat.updateMetadataJsonWithCurrentMetadataProperties(); - - Either catRes = titanDao.createVertex(cat); - - Either subCatRes = titanDao.createVertex(subCat); - - TitanOperationStatus status = titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); - assertEquals(TitanOperationStatus.OK, status); - } - - private void createServiceCategory() { - - GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); - Map metadataProperties = new HashMap<>(); - String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); - cat.setUniqueId(catId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - cat.setMetadataProperties(metadataProperties); - cat.updateMetadataJsonWithCurrentMetadataProperties(); - - Either catRes = titanDao.createVertex(cat); - - assertTrue(catRes.isLeft()); - } - - private GraphVertex createTopologyTemplate(String name) { - - TopologyTemplate service = new TopologyTemplate(); - String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - service.setUniqueId(uniqueId); - service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); - service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); - service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); - service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - service.setCategories(categories); - - service.setComponentType(ComponentTypeEnum.SERVICE); - Either createRes = topologyTemplateOperation.createTopologyTemplate(service); - assertTrue(createRes.isLeft()); - - Either getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); - assertTrue(getNodeTyeRes.isLeft()); - - // serviceVertex = getNodeTyeRes.left().value(); - - return getNodeTyeRes.left().value(); - } - - private NodeType createNodeType(String nodeTypeName) { - - NodeType vf = new NodeType(); - String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - vf.setUniqueId(uniqueId); - vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName); - vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); - vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); - vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List derivedFrom = new ArrayList<>(); - derivedFrom.add("root"); - vf.setDerivedFrom(derivedFrom); - - vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either createVFRes = nodeTypeOperation.createNodeType(vf); - assertTrue(createVFRes.isLeft()); - - Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - assertTrue(getNodeTyeRes.isLeft()); - - vfVertex = getNodeTyeRes.left().value(); - - List addProperties = new ArrayList<>(); - PropertyDataDefinition prop11 = new PropertyDataDefinition(); - prop11.setName("prop11"); - prop11.setDefaultValue("def11"); - - addProperties.add(prop11); - - PropertyDataDefinition prop22 = new PropertyDataDefinition(); - prop22.setName("prop22"); - prop22.setDefaultValue("def22"); - addProperties.add(prop22); - - StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - PropertyDataDefinition prop33 = new PropertyDataDefinition(); - prop33.setName("prop33"); - prop33.setDefaultValue("def33"); - - status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop33, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - PropertyDataDefinition prop44 = new PropertyDataDefinition(); - prop44.setName("prop44"); - prop44.setDefaultValue("def44"); - - status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); - assertTrue(status == StorageOperationStatus.OK); - - PropertyDataDefinition capProp = new PropertyDataDefinition(); - capProp.setName("capProp"); - capProp.setDefaultValue("capPropDef"); - - MapDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - dataToCreate.put("capProp", capProp); - - Map capProps = new HashMap(); - capProps.put("capName", dataToCreate); - - Either res = nodeTypeOperation.assosiateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); - - // exportGraphMl(titanDao.getGraph().left().value()); - - List pathKeys = new ArrayList<>(); - pathKeys.add("capName"); - capProp.setDefaultValue("BBBB"); - status = nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); - return vf; - } - - private GraphVertex createRootNodeType() { - - NodeType vf = new NodeType(); - String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - vf.setUniqueId(uniqueId); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); - vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); - vf.getMetadata().put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); - vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); - - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List derivedFrom = new ArrayList<>(); - vf.setDerivedFrom(derivedFrom); - - Map properties = new HashMap<>(); - PropertyDataDefinition prop1 = new PropertyDataDefinition(); - prop1.setName("derived1"); - prop1.setDefaultValue("deriveddef1"); - - properties.put("derived1", prop1); - - PropertyDataDefinition prop2 = new PropertyDataDefinition(); - prop2.setUniqueId("derived2"); - prop2.setName("deriveddef2"); - properties.put("derived2", prop2); - - PropertyDataDefinition prop3 = new PropertyDataDefinition(); - prop3.setName("derived3"); - prop3.setDefaultValue("deriveddef3"); - properties.put("derived3", prop3); - - vf.setProperties(properties); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either createVFRes = nodeTypeOperation.createNodeType(vf); - assertTrue(createVFRes.isLeft()); - - Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - assertTrue(getNodeTyeRes.isLeft()); - return getNodeTyeRes.left().value(); - } - - private void createUsers() { - - GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); - ownerV.setUniqueId("user1"); - - Map metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user1"); - ownerV.setMetadataProperties(metadataProperties); - ownerV.updateMetadataJsonWithCurrentMetadataProperties(); - ownerV.setJson(new HashMap<>()); - Either createUserRes = titanDao.createVertex(ownerV); - assertTrue(createUserRes.isLeft()); - - ownerVertex = createUserRes.left().value(); - - GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); - modifierV.setUniqueId("user2"); - - metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user2"); - modifierV.setMetadataProperties(metadataProperties); - modifierV.updateMetadataJsonWithCurrentMetadataProperties(); - modifierV.setJson(new HashMap<>()); - createUserRes = titanDao.createVertex(modifierV); - assertTrue(createUserRes.isLeft()); - - modifierVertex = createUserRes.left().value(); - - Either getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); - assertTrue(getOwnerRes.isLeft()); - - } - - public void verifyInCatalogData(int expected, List expectedIds) { - - Either, StorageOperationStatus> highestResourcesRes = topologyTemplateOperation.getElementCatalogData(); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - assertEquals(expected, highestResources.stream().count()); - if (expectedIds != null) { - highestResources.forEach(a -> assertTrue(expectedIds.contains(a.getUniqueId()))); - } - } - - @After - public void teardown() { - clearGraph(); - } - - private void clearGraph() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - vertex.remove(); - } - } - titanDao.commit(); - } + assertTrue(res.isLeft()); + // 1-node type + // 2-vf + // 3- service + verifyInCatalogData(3, null); + + String id = res.left().value().getUniqueId(); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + verifyInCatalogData(3, null); + + PropertyDataDefinition prop55 = new PropertyDataDefinition(); + prop55.setName("prop55"); + prop55.setDefaultValue("def55"); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + CapabilityDataDefinition cap1 = new CapabilityDataDefinition(); + cap1.setName("cap1"); + cap1.setDescription("create"); + cap1.setUniqueId(UniqueIdBuilder.buildCapabilityUid(id, "cap1")); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + prop55.setDefaultValue("AAAAAAAA"); + status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + cap1.setDescription("update"); + + status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + PropertyDataDefinition prop66 = new PropertyDataDefinition(); + prop66.setName("prop66"); + prop66.setDefaultValue("def66"); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop66, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + verifyInCatalogData(3, null); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + verifyInCatalogData(4, null); + + PropertyDataDefinition prop77 = new PropertyDataDefinition(); + prop77.setName("prop77"); + prop77.setDefaultValue("def77"); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop77, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + PropertyDataDefinition prop88 = new PropertyDataDefinition(); + prop88.setName("prop88"); + prop88.setDefaultValue("def88"); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop88, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + verifyInCatalogData(3, null); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + verifyInCatalogData(4, null); + + PropertyDataDefinition prop99 = new PropertyDataDefinition(); + prop99.setName("prop99"); + prop99.setDefaultValue("def99"); + + status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop99, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + status = nodeTypeOperation.deleteToscaDataElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, "prop99", JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + // cancel certification + res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + + // fail certification + res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertTrue(res.isLeft()); + id = res.left().value().getUniqueId(); + verifyInCatalogData(4, null); + // exportGraphMl(titanDao.getGraph().left().value()); + + } + + @Test + public void serviceConformanceLevelTest() { + Either res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) serviceVertex.getMetadataProperty(GraphPropertyEnum.STATE)), serviceVertex.getUniqueId(), + modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + + assertTrue(res.isLeft()); + String id = res.left().value().getUniqueId(); + + res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId()); + assertTrue(res.isLeft()); + + String conformanceLevel = res.left().value().getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL).toString(); + assertEquals(conformanceLevel, ModelTestBase.configurationManager.getConfiguration().getToscaConformanceLevel()); + } + + @Test + public void catalogTest() { + // start position - 3 in catalog + List expectedIds = new ArrayList<>(); + expectedIds.add(rootVertex.getUniqueId()); + expectedIds.add(vfVertex.getUniqueId()); + expectedIds.add(serviceVertex.getUniqueId()); + + verifyInCatalogData(3, expectedIds); + + GraphVertex vertex4 = createTopologyTemplate("topTemp4"); + expectedIds.add(vertex4.getUniqueId()); + verifyInCatalogData(4, expectedIds); + + Either res = lifecycleOperation.undoCheckout(vertex4.getUniqueId()); + expectedIds.remove(vertex4.getUniqueId()); + verifyInCatalogData(3, expectedIds); + + vertex4 = createTopologyTemplate("topTemp4"); + expectedIds.add(vertex4.getUniqueId()); + verifyInCatalogData(4, expectedIds); + + res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vertex4.getMetadataProperty(GraphPropertyEnum.STATE)), vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + Either certifyToscaElement = lifecycleOperation.certifyToscaElement(vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(certifyToscaElement.isLeft()); + expectedIds.remove(vertex4.getUniqueId()); + String certifiedId = certifyToscaElement.left().value().getUniqueId(); + expectedIds.add(certifiedId); + verifyInCatalogData(4, expectedIds); + + res = lifecycleOperation.checkoutToscaElement(certifiedId, modifierVertex.getUniqueId(), ownerVertex.getUniqueId()); + assertTrue(certifyToscaElement.isLeft()); + expectedIds.add(res.left().value().getUniqueId()); + verifyInCatalogData(5, expectedIds); + } + + private void createResourceCategory() { + + GraphVertex cat = new GraphVertex(VertexTypeEnum.RESOURCE_CATEGORY); + Map metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY); + metadataProperties = new HashMap<>(); + String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory); + subCat.setUniqueId(subCatId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, subcategory); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); + subCat.setMetadataProperties(metadataProperties); + subCat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either catRes = titanDao.createVertex(cat); + + Either subCatRes = titanDao.createVertex(subCat); + + TitanOperationStatus status = titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); + assertEquals(TitanOperationStatus.OK, status); + } + + private void createServiceCategory() { + + GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); + Map metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either catRes = titanDao.createVertex(cat); + + assertTrue(catRes.isLeft()); + } + + private GraphVertex createTopologyTemplate(String name) { + + TopologyTemplate service = new TopologyTemplate(); + String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); + service.setUniqueId(uniqueId); + service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); + service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); + service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); + service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + service.setCategories(categories); + + service.setComponentType(ComponentTypeEnum.SERVICE); + Either createRes = topologyTemplateOperation.createTopologyTemplate(service); + assertTrue(createRes.isLeft()); + + Either getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); + assertTrue(getNodeTyeRes.isLeft()); + + // serviceVertex = getNodeTyeRes.left().value(); + + return getNodeTyeRes.left().value(); + } + + private NodeType createNodeType(String nodeTypeName) { + + NodeType vf = new NodeType(); + String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); + vf.setUniqueId(uniqueId); + vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName); + vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); + vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); + vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List derivedFrom = new ArrayList<>(); + derivedFrom.add("root"); + vf.setDerivedFrom(derivedFrom); + + vf.setComponentType(ComponentTypeEnum.RESOURCE); + Either createVFRes = nodeTypeOperation.createNodeType(vf); + assertTrue(createVFRes.isLeft()); + + Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + assertTrue(getNodeTyeRes.isLeft()); + + vfVertex = getNodeTyeRes.left().value(); + + List addProperties = new ArrayList<>(); + PropertyDataDefinition prop11 = new PropertyDataDefinition(); + prop11.setName("prop11"); + prop11.setDefaultValue("def11"); + + addProperties.add(prop11); + + PropertyDataDefinition prop22 = new PropertyDataDefinition(); + prop22.setName("prop22"); + prop22.setDefaultValue("def22"); + addProperties.add(prop22); + + StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + PropertyDataDefinition prop33 = new PropertyDataDefinition(); + prop33.setName("prop33"); + prop33.setDefaultValue("def33"); + + status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop33, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + PropertyDataDefinition prop44 = new PropertyDataDefinition(); + prop44.setName("prop44"); + prop44.setDefaultValue("def44"); + + status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); + assertSame(status, StorageOperationStatus.OK); + + PropertyDataDefinition capProp = new PropertyDataDefinition(); + capProp.setName("capProp"); + capProp.setDefaultValue("capPropDef"); + + MapDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + dataToCreate.put("capProp", capProp); + + Map capProps = new HashMap(); + capProps.put("capName", dataToCreate); + + Either res = nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); + + // exportGraphMl(titanDao.getGraph().left().value()); + + List pathKeys = new ArrayList<>(); + pathKeys.add("capName"); + capProp.setDefaultValue("BBBB"); + status = nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); + return vf; + } + + private GraphVertex createRootNodeType() { + + NodeType vf = new NodeType(); + String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); + vf.setUniqueId(uniqueId); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); + vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); + vf.getMetadata().put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); + vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); + + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List derivedFrom = new ArrayList<>(); + vf.setDerivedFrom(derivedFrom); + + Map properties = new HashMap<>(); + PropertyDataDefinition prop1 = new PropertyDataDefinition(); + prop1.setName("derived1"); + prop1.setDefaultValue("deriveddef1"); + + properties.put("derived1", prop1); + + PropertyDataDefinition prop2 = new PropertyDataDefinition(); + prop2.setUniqueId("derived2"); + prop2.setName("deriveddef2"); + properties.put("derived2", prop2); + + PropertyDataDefinition prop3 = new PropertyDataDefinition(); + prop3.setName("derived3"); + prop3.setDefaultValue("deriveddef3"); + properties.put("derived3", prop3); + + vf.setProperties(properties); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + Either createVFRes = nodeTypeOperation.createNodeType(vf); + assertTrue(createVFRes.isLeft()); + + Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + assertTrue(getNodeTyeRes.isLeft()); + return getNodeTyeRes.left().value(); + } + + private void createUsers() { + + GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); + ownerV.setUniqueId("user1"); + + Map metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user1"); + ownerV.setMetadataProperties(metadataProperties); + ownerV.updateMetadataJsonWithCurrentMetadataProperties(); + ownerV.setJson(new HashMap<>()); + Either createUserRes = titanDao.createVertex(ownerV); + assertTrue(createUserRes.isLeft()); + + ownerVertex = createUserRes.left().value(); + + GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); + modifierV.setUniqueId("user2"); + + metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user2"); + modifierV.setMetadataProperties(metadataProperties); + modifierV.updateMetadataJsonWithCurrentMetadataProperties(); + modifierV.setJson(new HashMap<>()); + createUserRes = titanDao.createVertex(modifierV); + assertTrue(createUserRes.isLeft()); + + modifierVertex = createUserRes.left().value(); + + Either getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); + assertTrue(getOwnerRes.isLeft()); + + } + + public void verifyInCatalogData(int expected, List expectedIds) { + + Either, StorageOperationStatus> highestResourcesRes = topologyTemplateOperation.getElementCatalogData(true, null); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + assertEquals(expected, highestResources.stream().count()); + if (expectedIds != null) { + highestResources.forEach(a -> assertTrue(expectedIds.contains(a.getUniqueId()))); + } + } + + @After + public void teardown() { + clearGraph(); + } + + private void clearGraph() { + Either graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java index 57689edb3d..5226a468d7 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,33 +20,21 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; +import com.thinkaurelius.titan.core.*; +import com.thinkaurelius.titan.graphdb.relations.StandardVertexProperty; +import com.thinkaurelius.titan.graphdb.types.system.EmptyVertex; +import com.thinkaurelius.titan.graphdb.types.system.ImplicitKey; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; @@ -57,173 +45,362 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.api.UserRoleEnum; -import fj.data.Either; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; public class UserAdminOperationTest extends ModelTestBase { - private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); - @InjectMocks - private static final UserAdminOperation userAdminOperation = new UserAdminOperation(titanGenericDao); - private static final String ADMIN = "admin"; - - @BeforeClass - public static void setup() { - ModelTestBase.init(); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - Mockito.reset(titanGenericDao); - mockTitanUpdate(); - mockTitanDelete(); - - } - - @Test - public void testDeActivateUserDataSuccess() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); - - Either eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser(userData)); - - verify(titanGenericDao, times(1)).updateNode(Mockito.eq(userData), Mockito.eq(UserData.class)); - verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - assertTrue(eitherUser.isLeft()); - User user = eitherUser.left().value(); - assertTrue(user.getStatus() == UserStatusEnum.INACTIVE); - } - - @Test - public void testDeleteUserWithoutResources() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); - - List edgesList = new ArrayList(); - - Either, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); - - Either eitherUser = userAdminOperation.deleteUserData(ADMIN); - verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - verify(titanGenericDao, times(1)).deleteNode(userData, UserData.class); - assertTrue(eitherUser.isLeft()); - - } - - @Test - public void testDeleteUserWithResources() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); - - List edgesList = new ArrayList(); - edgesList.add(getEmptyEdgeImpl()); - - Either, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); - - Either eitherUser = userAdminOperation.deleteUserData(ADMIN); - verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - assertTrue(eitherUser.isRight()); - assertTrue(eitherUser.right().value() == ActionStatus.USER_HAS_ACTIVE_ELEMENTS); - - } - - private Edge getEmptyEdgeImpl() { - return new Edge() { - - @Override - public Object id() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String label() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Graph graph() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Property property(String key, V value) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void remove() { - // TODO Auto-generated method stub - - } - - @Override - public Iterator vertices(Direction direction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Iterator> properties(String... propertyKeys) { - // TODO Auto-generated method stub - return null; - } - - }; - } - - private UserData mockTitanGet(String userId, UserRoleEnum role, boolean isActive) { - UserData userData = buildUserData(userId, role, isActive); - Either eitherUserData = Either.left(userData); - when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData); - return userData; - } - - private static void mockTitanUpdate() { - doAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - UserData retValue = (UserData) args[0]; - Either result = Either.left(retValue); - return result; - } - - }).when(titanGenericDao).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - } - - private static void mockTitanDelete() { - doAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - UserData retValue = (UserData) args[0]; - Either result = Either.left(retValue); - return result; - } - - }).when(titanGenericDao).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - } - - private void assertUserEquals(UserData expected, User actual) { - assertEquals(expected.getEmail(), actual.getEmail()); - assertEquals(expected.getFirstName(), actual.getFirstName()); - assertEquals(expected.getLastName(), actual.getLastName()); - assertEquals(expected.getRole(), actual.getRole()); - assertEquals(expected.getStatus(), actual.getStatus().name()); - assertEquals(expected.getUserId(), actual.getUserId()); - - } - - private static UserData buildUserData(String userId, UserRoleEnum role, boolean isActive) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setRole(role.getName()); - userData.setEmail("someEmail@somePlace.com"); - userData.setFirstName("israel"); - userData.setLastName("israeli"); - userData.setLastLoginTime(Instant.MIN.getEpochSecond()); - userData.setStatus(isActive ? UserStatusEnum.ACTIVE.name() : UserStatusEnum.INACTIVE.name()); - return userData; - } + private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); + @InjectMocks + private static final UserAdminOperation userAdminOperation = new UserAdminOperation(titanGenericDao); + private static final String ADMIN = "admin"; + + @BeforeClass + public static void setup() { + ModelTestBase.init(); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Mockito.reset(titanGenericDao); + mockTitanUpdate(); + mockTitanDelete(); + + } + + @Test + public void testDeActivateUserDataSuccess() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + Either eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser(userData)); + + verify(titanGenericDao, times(1)).updateNode(eq(userData), eq(UserData.class)); + verify(titanGenericDao, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); + assertTrue(eitherUser.isLeft()); + User user = eitherUser.left().value(); + assertSame(user.getStatus(), UserStatusEnum.INACTIVE); + } + + @Test + public void testDeleteUserWithoutResources() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + List edgesList = new ArrayList<>(); + + Either, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either eitherUser = userAdminOperation.deleteUserData(ADMIN); + verify(titanGenericDao, times(0)).updateNode(any(UserData.class), eq(UserData.class)); + verify(titanGenericDao, times(1)).deleteNode(userData, UserData.class); + assertTrue(eitherUser.isLeft()); + + } + + @Test + public void testDeleteUserWithResources() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + List edgesList = new ArrayList<>(); + edgesList.add(getEmptyEdgeImpl()); + + Either, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either eitherUser = userAdminOperation.deleteUserData(ADMIN); + verify(titanGenericDao, times(0)).updateNode(any(UserData.class), eq(UserData.class)); + verify(titanGenericDao, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); + assertTrue(eitherUser.isRight()); + assertSame(eitherUser.right().value(), ActionStatus.USER_HAS_ACTIVE_ELEMENTS); + + } + + @Test + public void getUserPendingTasks_shouldReturnNonDeleted() { + String userId = "abc123"; + String userKey = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); + User user = new User(); + user.setUserId(userId); + TitanVertex userVertex = null; + TestVertex component1 = new TestVertex(null); + TestVertex component2 = new TestVertex(true); + TestVertex component3 = new TestVertex(false); + List edges = new ArrayList<>(); + Edge edge1 = new TestEdge(component1, "1"); + Edge edge2 = new TestEdge(component2, "2"); + Edge edge3 = new TestEdge(component3, "3"); + edges.add(edge1); + edges.add(edge2); + edges.add(edge3); + when(titanGenericDao.getVertexByProperty(userKey, userId)).thenReturn(Either.left(userVertex)); + when(titanGenericDao.getOutgoingEdgesByCriteria(any(), any(), any())).thenReturn(Either.left(edges)); + Either, StorageOperationStatus> result = userAdminOperation.getUserPendingTasksList(user, new HashMap<>()); + assertThat(result.isLeft()).isTrue(); + List pendingTasks = result.left().value(); + assertThat(pendingTasks.size()).isEqualTo(2); + assertThat(((TestEdge)pendingTasks.get(0)).getName()).isNotEqualTo("2"); + assertThat(((TestEdge)pendingTasks.get(1)).getName()).isNotEqualTo("2"); + } + + private class TestVertex implements TitanVertex { + + private final Boolean isDeleted; + + private TestVertex(Boolean isDeleted) { + this.isDeleted = isDeleted; + } + + @Override + public TitanEdge addEdge(String s, Vertex vertex, Object... objects) { + return null; + } + + @Override + public TitanVertexProperty property(String s, V v, Object... objects) { + return null; + } + + @Override + public VertexProperty property(String key) { + if (key.equals(GraphPropertiesDictionary.IS_DELETED.getProperty())) { + if (isDeleted==null) + return VertexProperty.empty(); + return new StandardVertexProperty(1, ImplicitKey.ID, new EmptyVertex(), isDeleted, (byte)1); + } + return VertexProperty.empty(); + } + + @Override + public TitanVertexProperty property(VertexProperty.Cardinality cardinality, String s, V v, Object... objects) { + return null; + } + + @Override + public Iterator edges(Direction direction, String... strings) { + return null; + } + + @Override + public Iterator vertices(Direction direction, String... strings) { + return null; + } + + @Override + public Object id() { + return null; + } + + @Override + public long longId() { + return 0; + } + + @Override + public boolean hasId() { + return false; + } + + @Override + public String label() { + return null; + } + + @Override + public VertexLabel vertexLabel() { + return null; + } + + @Override + public TitanVertexQuery query() { + return null; + } + + @Override + public boolean isModified() { + return false; + } + + @Override + public TitanTransaction graph() { + return null; + } + + @Override + public void remove() { + + } + + @Override + public V valueOrNull(PropertyKey propertyKey) { + return null; + } + + @Override + public boolean isNew() { + return false; + } + + @Override + public boolean isLoaded() { + return false; + } + + @Override + public boolean isRemoved() { + return false; + } + + @Override + public Iterator> properties(String... strings) { + return null; + } + } + + private class TestEdge implements Edge { + + private final Vertex inVertx; + private final String name; + + TestEdge(Vertex inVertx, String name) { + this.inVertx = inVertx; + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public Iterator vertices(Direction direction) { + return null; + } + + @Override + public Vertex inVertex() { + return inVertx; + } + + @Override + public Object id() { + return null; + } + + @Override + public String label() { + return null; + } + + @Override + public Graph graph() { + return null; + } + + @Override + public Property property(String s, V v) { + return null; + } + + @Override + public void remove() { + + } + + @Override + public Iterator> properties(String... strings) { + return null; + } + } + + private Edge getEmptyEdgeImpl() { + return new Edge() { + + @Override + public Object id() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String label() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Graph graph() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Property property(String key, V value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void remove() { + // TODO Auto-generated method stub + + } + + @Override + public Iterator vertices(Direction direction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Iterator> properties(String... propertyKeys) { + // TODO Auto-generated method stub + return null; + } + + }; + } + + private UserData mockTitanGet(String userId, UserRoleEnum role, boolean isActive) { + UserData userData = buildUserData(userId, role, isActive); + Either eitherUserData = Either.left(userData); + when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData); + return userData; + } + + private static void mockTitanUpdate() { + doAnswer((Answer>) invocation -> { + Object[] args = invocation.getArguments(); + UserData retValue = (UserData) args[0]; + return Either.left(retValue); + }).when(titanGenericDao).updateNode(any(UserData.class), eq(UserData.class)); + } + + private static void mockTitanDelete() { + doAnswer((Answer>) invocation -> { + Object[] args = invocation.getArguments(); + UserData retValue = (UserData) args[0]; + return Either.left(retValue); + }).when(titanGenericDao).deleteNode(any(UserData.class), eq(UserData.class)); + } + + private static UserData buildUserData(String userId, UserRoleEnum role, boolean isActive) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setRole(role.getName()); + userData.setEmail("someEmail@somePlace.com"); + userData.setFirstName("israel"); + userData.setLastName("israeli"); + userData.setLastLoginTime(Instant.MIN.getEpochSecond()); + userData.setStatus(isActive ? UserStatusEnum.ACTIVE.name() : UserStatusEnum.INACTIVE.name()); + return userData; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java index 9237095ad7..8700aaa5f1 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java @@ -20,19 +20,10 @@ package org.openecomp.sdc.be.model.operations.impl.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Test; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -48,952 +39,951 @@ import org.openecomp.sdc.be.model.tosca.validators.MapValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.*; -import fj.data.Either; +import static org.junit.Assert.*; public class DataTypeValidatorTest { - private static Logger log = LoggerFactory.getLogger(DataTypeValidatorTest.class.getName()); - private static Gson gson = new Gson(); + private static final Logger log = LoggerFactory.getLogger(DataTypeValidatorTest.class); + private static Gson gson = new Gson(); - DataTypeValidatorConverter dataTypeValidator = DataTypeValidatorConverter.getInstance(); + DataTypeValidatorConverter dataTypeValidator = DataTypeValidatorConverter.getInstance(); - @Test - public void testDerivedFromPrimitiveEmptyValue() { + @Test + public void testDerivedFromPrimitiveEmptyValue() { - Map allDataTypes = new HashMap(); - allDataTypes.put("integer", getPrimitiveDataType("integer")); + Map allDataTypes = new HashMap<>(); + allDataTypes.put("integer", getPrimitiveDataType("integer")); - DataTypeDefinition fromIntegerType = buildDerivedFromIntegerType(); - ImmutablePair validate = dataTypeValidator.validateAndUpdate("", fromIntegerType, - allDataTypes); + DataTypeDefinition fromIntegerType = buildDerivedFromIntegerType(); + ImmutablePair validate = dataTypeValidator.validateAndUpdate("", fromIntegerType, + allDataTypes); - assertTrue("check result is valid", validate.right.booleanValue()); - assertEquals("check value is the same as sent", null, validate.left); + assertTrue("check result is valid", validate.right.booleanValue()); + assertNull("check value is the same as sent", validate.left); - validate = dataTypeValidator.validateAndUpdate(null, fromIntegerType, allDataTypes); + validate = dataTypeValidator.validateAndUpdate(null, fromIntegerType, allDataTypes); - assertTrue("check result is valid", validate.right.booleanValue()); - assertEquals("check value is the same as sent", null, validate.left); + assertTrue("check result is valid", validate.right.booleanValue()); + assertNull("check value is the same as sent", validate.left); - validate = dataTypeValidator.validateAndUpdate("88", fromIntegerType, allDataTypes); + validate = dataTypeValidator.validateAndUpdate("88", fromIntegerType, allDataTypes); - assertTrue("check result is valid", validate.right.booleanValue()); - assertEquals("check value is the same as sent", "88", validate.left.toString()); + assertTrue("check result is valid", validate.right.booleanValue()); + assertEquals("check value is the same as sent", "88", validate.left.toString()); - } + } - @Test - public void testCompositeWithParameterDerivedFromPrimitiveEmptyValue() { + @Test + public void testCompositeWithParameterDerivedFromPrimitiveEmptyValue() { - DataTypeDefinition derivedFromIntegerType = buildDerivedFromIntegerType(); - Map allDataTypes = new HashMap(); - allDataTypes.put("myinteger", derivedFromIntegerType); + DataTypeDefinition derivedFromIntegerType = buildDerivedFromIntegerType(); + Map allDataTypes = new HashMap<>(); + allDataTypes.put("myinteger", derivedFromIntegerType); - DataTypeDefinition personDataType = buildPersonDataType(); + DataTypeDefinition personDataType = buildPersonDataType(); - Person person = new Person("my address", 32); - String json = gson.toJson(person); - log.debug(json); + Person person = new Person("my address", 32); + String json = gson.toJson(person); + log.debug(json); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, personDataType, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, personDataType, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - person = new Person("my address", 32); - json = gson.toJson(person); - json = json.replace("32", "32a"); - log.debug(json); + person = new Person("my address", 32); + json = gson.toJson(person); + json = json.replace("32", "32a"); + log.debug(json); - validate = dataTypeValidator.validateAndUpdate(json, personDataType, allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + validate = dataTypeValidator.validateAndUpdate(json, personDataType, allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); - } + } - @Test - public void testCompositeWithEmptyListValue() { + @Test + public void testCompositeWithEmptyListValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - String[] strArr = {}; - List strList = Arrays.asList(strArr); + String[] strArr = {}; + List strList = Arrays.asList(strArr); - // Check empty list - Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, strList); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check empty list + Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); - log.debug(json); + String json = gson.toJson(credential); + log.debug(json); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); - assertEquals("check empty list", 0, credentialRes.getMylist().size()); + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertEquals("check empty list", 0, credentialRes.getMylist().size()); - log.debug("Result is = {}", validate.left.toString()); + log.debug("Result is = {}", validate.left.toString()); - } + } - @Test - public void testCompositeWithListNullValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + @Test + public void testCompositeWithListNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check list is NULL - Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check list is NULL + Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); - assertNull("check list is null", credentialRes.getMylist()); - log.debug("Result is = {}", validate.left.toString()); + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getMylist()); + log.debug("Result is = {}", validate.left.toString()); - } + } - @Test - public void testCompositeWithUserNullValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + @Test + public void testCompositeWithUserNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, null, true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, null, true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); - assertNull("check list is null", credentialRes.getUser()); - log.debug("Result is = {}", validate.left.toString()); - } + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getUser()); + log.debug("Result is = {}", validate.left.toString()); + } - @Test - public void testCompositeWithEmptyUserValue() { + @Test + public void testCompositeWithEmptyUserValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - // Check user is empty - Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "", true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + // Check user is empty + Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "", true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); - log.debug(json); + String json = gson.toJson(credential); + log.debug(json); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); - assertNotNull("check list is not null", credentialRes.getUser()); - assertEquals("check user is empty", "", credentialRes.getUser()); - log.debug("Result is = {}", validate.left.toString()); + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNotNull("check list is not null", credentialRes.getUser()); + assertEquals("check user is empty", "", credentialRes.getUser()); + log.debug("Result is = {}", validate.left.toString()); - } + } - @Test - public void testCompositeWithSumNullValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + @Test + public void testCompositeWithSumNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); - assertNull("check list is null", credentialRes.getSum()); - log.debug("Result is = {}", validate.left.toString()); - } + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getSum()); + log.debug("Result is = {}", validate.left.toString()); + } - @Test - public void testInvalidJson() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + @Test + public void testInvalidJson() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - json += "fdfd"; + json += "fdfd"; - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); - } + } - @Test - public void testInvalidInnerValue() { + @Test + public void testInvalidInnerValue() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - json = json.replace("55", "a55b"); + json = json.replace("55", "a55b"); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); - } + } - @Test - public void testInvalidInnerJson() { + @Test + public void testInvalidInnerJson() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); - City mycity = new City("", null); + // Check user is null + Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); + City mycity = new City("", null); - credential.setMycity(mycity); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - json = json.replace("{\"address\":\"\"}", "scalar"); + json = json.replace("{\"address\":\"\"}", "scalar"); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); - } + } - @Test - public void testInvalidPropertyJson() { + @Test + public void testInvalidPropertyJson() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol
>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - json = json.replace("55", "a55b"); + json = json.replace("55", "a55b"); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); - } + } - @Test - public void testCompositeDataTypeWithInternalComposite() { + @Test + public void testCompositeDataTypeWithInternalComposite() { - DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); - String[] strArr = { "aaa", "bbb", "c
dcc" }; - List strList = Arrays.asList(strArr); + String[] strArr = { "aaa", "bbb", "c
dcc" }; + List strList = Arrays.asList(strArr); - Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, strList); - City mycity = new City("myadd
<
", 55); - credential.setMycity(mycity); + Credential credential = new Credential("protcol
>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd
<
", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); - log.debug("Result is = {}", validate.left.toString()); + log.debug("Result is = {}", validate.left.toString()); - } + } - @Test - public void testMapValidator() { + @Test + public void testMapValidator() { - MapValidator validator = new MapValidator(); - Gson gson = new Gson(); - // Happy Scenarios - // 1 - Map check OK - Map map_1 = new HashMap<>(); - map_1.put("key1", 2); - map_1.put("key2", 3); - String value = gson.toJson(map_1); - String innerType = "integer"; - assertTrue("Test Map validation with inner integer type", validator.isValid(value, innerType, null)); + MapValidator validator = new MapValidator(); + Gson gson = new Gson(); + // Happy Scenarios + // 1 - Map check OK + Map map_1 = new HashMap<>(); + map_1.put("key1", 2); + map_1.put("key2", 3); + String value = gson.toJson(map_1); + String innerType = "integer"; + assertTrue("Test Map validation with inner integer type", validator.isValid(value, innerType, null)); - // 2 - Map check OK - Map map_2 = new HashMap<>(); - map_2.put("key1", true); - map_2.put("key2", false); - value = gson.toJson(map_2); - innerType = "boolean"; - assertTrue("Test Map validation with inner boolean type", validator.isValid(value, innerType, null)); + // 2 - Map check OK + Map map_2 = new HashMap<>(); + map_2.put("key1", true); + map_2.put("key2", false); + value = gson.toJson(map_2); + innerType = "boolean"; + assertTrue("Test Map validation with inner boolean type", validator.isValid(value, innerType, null)); - // 3 - give integer with quotes - innerType = "integer"; - value = "{\"key1\":\"5\",\"key2\":\"7\"}"; - assertTrue("Test Map validation with inner integer type, but qouted values", - validator.isValid(value, innerType, null)); + // 3 - give integer with quotes + innerType = "integer"; + value = "{\"key1\":\"5\",\"key2\":\"7\"}"; + assertTrue("Test Map validation with inner integer type, but qouted values", + validator.isValid(value, innerType, null)); - // 4 - empty default value - innerType = "float"; - value = ""; - assertTrue("Test Map validation with inner float type", validator.isValid(value, innerType, null)); + // 4 - empty default value + innerType = "float"; + value = ""; + assertTrue("Test Map validation with inner float type", validator.isValid(value, innerType, null)); - // Faulty Scenarios - // 5 - mismatch in data type - value = gson.toJson(map_1); - innerType = "boolean"; - assertFalse("Test Map faulty validation with inner boolean type", validator.isValid(value, innerType, null)); - // 6 - mismatch in data type - value = gson.toJson(map_2); - innerType = "integer"; - assertFalse("Test Map faulty validation with inner integer type", validator.isValid(value, innerType, null)); - - } - - @Test - public void testMapConverter() { - - MapConverter converter = new MapConverter(); - Gson gson = new Gson(); - // Happy Scenarios - Map map_1 = new HashMap<>(); - Map resMap_1 = new HashMap<>(); - - // 1 - check Spaces eliminated + html square brackets eliminated - map_1.put("key1", "test"); - map_1.put("key2", " test"); - resMap_1.put("key1", "test"); - resMap_1.put("key2", " test"); - String value = gson.toJson(map_1); - String expectedVal = gson.toJson(resMap_1); - String innerType = "string"; - assertEquals("Test Map validation with inner string type", expectedVal, - converter.convert(value, innerType, null)); - - // 2 - float converter - innerType = "float"; - value = "{\"key1\":0.4545,\"key2\":0.2f}"; - expectedVal = "{\"key1\":0.4545,\"key2\":0.2}"; - assertEquals("Test Map validation with inner float type", expectedVal, - converter.convert(value, innerType, null)); - - // 3 - check default empty value converter - innerType = "float"; - value = ""; - expectedVal = ""; - assertEquals("Test Map validation with inner float type", expectedVal, - converter.convert(value, innerType, null)); - - // 4 - invalid json - // 3 - check default empty value converter - innerType = "float"; - value = "{1345234556@#("; - expectedVal = null; - assertEquals("Test Map validation with inner float type", expectedVal, - converter.convert(value, innerType, null)); - - } - - @Test - public void testCompositeDataTypeWithMapComposite() { - - DataTypeDefinition fileDataTypeDefinition = buildFileDataType(); - Map allDataTypes = new HashMap(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - - MyFile myFile = new MyFile(); - myFile.setAge(88); - Map attributes = new HashMap<>(); - attributes.put("key1", new City("address1
", 11)); - attributes.put("key2", new City("address2
", 22)); - myFile.setAttributes(attributes); - - String str = gson.toJson(myFile); - log.debug(str); - - ImmutablePair convert = dataTypeValidator.validateAndUpdate(str, fileDataTypeDefinition, - allDataTypes); + // Faulty Scenarios + // 5 - mismatch in data type + value = gson.toJson(map_1); + innerType = "boolean"; + assertFalse("Test Map faulty validation with inner boolean type", validator.isValid(value, innerType, null)); + // 6 - mismatch in data type + value = gson.toJson(map_2); + innerType = "integer"; + assertFalse("Test Map faulty validation with inner integer type", validator.isValid(value, innerType, null)); + + } + + @Test + public void testMapConverter() { + + MapConverter converter = new MapConverter(); + Gson gson = new Gson(); + // Happy Scenarios + Map map_1 = new HashMap<>(); + Map resMap_1 = new HashMap<>(); + + // 1 - check Spaces eliminated + html square brackets eliminated + map_1.put("key1", "test"); + map_1.put("key2", " test"); + resMap_1.put("key1", "test"); + resMap_1.put("key2", " test"); + String value = gson.toJson(map_1); + String expectedVal = gson.toJson(resMap_1); + String innerType = "string"; + assertEquals("Test Map validation with inner string type", expectedVal, + converter.convert(value, innerType, null)); + + // 2 - float converter + innerType = "float"; + value = "{\"key1\":0.4545,\"key2\":0.2f}"; + expectedVal = "{\"key1\":0.4545,\"key2\":0.2}"; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + // 3 - check default empty value converter + innerType = "float"; + value = ""; + expectedVal = ""; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + // 4 - invalid json + // 3 - check default empty value converter + innerType = "float"; + value = "{1345234556@#("; + expectedVal = null; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + } + + @Test + public void testCompositeDataTypeWithMapComposite() { + + DataTypeDefinition fileDataTypeDefinition = buildFileDataType(); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + MyFile myFile = new MyFile(); + myFile.setAge(88); + Map attributes = new HashMap<>(); + attributes.put("key1", new City("address1
", 11)); + attributes.put("key2", new City("address2
", 22)); + myFile.setAttributes(attributes); + + String str = gson.toJson(myFile); + log.debug(str); + + ImmutablePair convert = dataTypeValidator.validateAndUpdate(str, fileDataTypeDefinition, + allDataTypes); - assertTrue("check map converter succeed", convert.right); + assertTrue("check map converter succeed", convert.right); - JsonElement convertedValue = convert.left; + JsonElement convertedValue = convert.left; - log.debug("{}", convertedValue); - MyFile fromJson = gson.fromJson(convertedValue, MyFile.class); + log.debug("{}", convertedValue); + MyFile fromJson = gson.fromJson(convertedValue, MyFile.class); - assertEquals("check age", 88, fromJson.getAge().intValue()); - assertEquals("check address 1", "address1", fromJson.getAttributes().get("key1").getAddress()); - assertEquals("check address 2", "address2", fromJson.getAttributes().get("key2").getAddress()); + assertEquals("check age", 88, fromJson.getAge().intValue()); + assertEquals("check address 1", "address1", fromJson.getAttributes().get("key1").getAddress()); + assertEquals("check address 2", "address2", fromJson.getAttributes().get("key2").getAddress()); - } + } - @Test - public void testMapConverterWithComplexInnerType() { + @Test + public void testMapConverterWithComplexInnerType() { - Map allDataTypes = new HashMap(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); - Gson gson = new Gson(); - // Happy Scenarios - Map map_1 = new HashMap<>(); + Gson gson = new Gson(); + // Happy Scenarios + Map map_1 = new HashMap<>(); - // 1 - check Spaces eliminated + html square brackets eliminated + // 1 - check Spaces eliminated + html square brackets eliminated - String[] strArr = { "aaa", "bbb", "c
dcc" }; - List strList = Arrays.asList(strArr); - Credential credential1 = new Credential("protocol;:,.\"
>", 5, "token_type", "token", null, "user", true, - strList); - City mycity1 = new City("myadd
<
", 55); - credential1.setMycity(mycity1); + String[] strArr = { "aaa", "bbb", "c
dcc" }; + List strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol;:,.\"
>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd
<
", 55); + credential1.setMycity(mycity1); - Credential credential2 = new Credential("protocol;:,.\"
>", 5, "token_type", "token", null, "user", true, - strList); - City mycity2 = new City("myadd
<
", 66); - credential2.setMycity(mycity2); + Credential credential2 = new Credential("protocol;:,.\"
>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd
<
", 66); + credential2.setMycity(mycity2); - map_1.put("key1", credential1); - map_1.put("key2", credential2); + map_1.put("key1", credential1); + map_1.put("key2", credential2); - String str = gson.toJson(map_1); - log.debug(str); + String str = gson.toJson(map_1); + log.debug(str); - MapConverter mapConverter = new MapConverter(); - Either convert = mapConverter.convertWithErrorResult(str, "credential", allDataTypes); + MapConverter mapConverter = new MapConverter(); + Either convert = mapConverter.convertWithErrorResult(str, "credential", allDataTypes); - assertTrue("check map converter succeed", convert.isLeft()); + assertTrue("check map converter succeed", convert.isLeft()); - String convertedValue = convert.left().value(); + String convertedValue = convert.left().value(); - Type type = new TypeToken>() { - }.getType(); + Type type = new TypeToken>() { + }.getType(); - Map fromJson = gson.fromJson(convertedValue, type); + Map fromJson = gson.fromJson(convertedValue, type); - Credential actualCredential1 = fromJson.get("key1"); - assertEquals("check sum", 5, actualCredential1.getSum().intValue()); - assertEquals("check protocol", "protocol;:,.\">", actualCredential1.getProtocol()); - String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; - List convertedStrList = Arrays.asList(convertedStrArr); - assertEquals("check list", convertedStrList, actualCredential1.getMylist()); + Credential actualCredential1 = fromJson.get("key1"); + assertEquals("check sum", 5, actualCredential1.getSum().intValue()); + assertEquals("check protocol", "protocol;:,.\">", actualCredential1.getProtocol()); + String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; + List convertedStrList = Arrays.asList(convertedStrArr); + assertEquals("check list", convertedStrList, actualCredential1.getMylist()); - assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); - assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); + assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); + assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); - Credential actualCredential2 = fromJson.get("key2"); - assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); + Credential actualCredential2 = fromJson.get("key2"); + assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); - } + } - @Test - public void testListConverterWithComplexInnerType() { + @Test + public void testListConverterWithComplexInnerType() { - Map allDataTypes = new HashMap(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); - Gson gson = new Gson(); + Gson gson = new Gson(); - List list = buildListOf2CredentialObjects(); + List list = buildListOf2CredentialObjects(); - String str = gson.toJson(list); - log.debug(str); + String str = gson.toJson(list); + log.debug(str); - ListConverter listConverter = new ListConverter(); + ListConverter listConverter = new ListConverter(); - Either convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); + Either convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); - assertTrue("check map converter succeed", convert.isLeft()); + assertTrue("check map converter succeed", convert.isLeft()); - String convertedValue = convert.left().value(); + String convertedValue = convert.left().value(); - validateListOfCredential(gson, convertedValue); + validateListOfCredential(gson, convertedValue); - list.add(null); + list.add(null); - str = gson.toJson(list); - log.debug(str); + str = gson.toJson(list); + log.debug(str); - convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); + convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); - assertTrue("check map converter succeed", convert.isLeft()); + assertTrue("check map converter succeed", convert.isLeft()); - validateListOfCredential(gson, convertedValue); - } + validateListOfCredential(gson, convertedValue); + } - @Test - public void testListValidatorWithComplexInnerType() { + @Test + public void testListValidatorWithComplexInnerType() { - Map allDataTypes = new HashMap(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map allDataTypes = new HashMap<>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); - Gson gson = new Gson(); - // Happy Scenarios - List list = buildListOf2CredentialObjects(); + Gson gson = new Gson(); + // Happy Scenarios + List list = buildListOf2CredentialObjects(); - String str = gson.toJson(list); - log.debug(str); + String str = gson.toJson(list); + log.debug(str); - ListValidator listValidator = new ListValidator(); + ListValidator listValidator = new ListValidator(); - boolean isValid = listValidator.isValid(str, "credential", allDataTypes); + boolean isValid = listValidator.isValid(str, "credential", allDataTypes); - assertTrue("check valid value", isValid); + assertTrue("check valid value", isValid); - String badStr = str.replace("protocol", "protocol1"); + String badStr = str.replace("protocol", "protocol1"); - isValid = listValidator.isValid(badStr, "credential", allDataTypes); + isValid = listValidator.isValid(badStr, "credential", allDataTypes); - assertFalse("check valid value", isValid); + assertFalse("check valid value", isValid); - badStr = str.replace("55", "\"aa\""); + badStr = str.replace("55", "\"aa\""); - isValid = listValidator.isValid(badStr, "credential", allDataTypes); + isValid = listValidator.isValid(badStr, "credential", allDataTypes); - assertFalse("check valid value", isValid); + assertFalse("check valid value", isValid); - } + } - private List buildListOf2CredentialObjects() { - List list = new ArrayList<>(); + private List buildListOf2CredentialObjects() { + List list = new ArrayList<>(); - String[] strArr = { "aaa", "bbb", "c
dcc" }; - List strList = Arrays.asList(strArr); - Credential credential1 = new Credential("protocol.,\":;
>", 5, "token_type", "token", null, "user", true, - strList); - City mycity1 = new City("myadd
<
", 55); - credential1.setMycity(mycity1); - - Credential credential2 = new Credential("protocol.,\":;
>", 5, "token_type", "token", null, "user", true, - strList); - City mycity2 = new City("myadd
<
", 66); - credential2.setMycity(mycity2); + String[] strArr = { "aaa", "bbb", "c
dcc" }; + List strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol.,\":;
>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd
<
", 55); + credential1.setMycity(mycity1); + + Credential credential2 = new Credential("protocol.,\":;
>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd
<
", 66); + credential2.setMycity(mycity2); - list.add(credential1); - list.add(credential2); - return list; - } + list.add(credential1); + list.add(credential2); + return list; + } - private void validateListOfCredential(Gson gson, String convertedValue) { - - log.debug(convertedValue); - Type type = new TypeToken>() { - }.getType(); - - List fromJson = gson.fromJson(convertedValue, type); - - assertEquals("check list size", 2, fromJson.size()); - - // Credential actualCredential1 = gson.fromJson(list.get(0).toString(), - // Credential.class); - Credential actualCredential1 = fromJson.get(0); - assertEquals("check sum", 5, actualCredential1.getSum().intValue()); - assertEquals("check protocol", "protocol.,\":;>", actualCredential1.getProtocol()); - String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; - List convertedStrList = Arrays.asList(convertedStrArr); - assertEquals("check list", convertedStrList, actualCredential1.getMylist()); - - assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); - assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); - - // Credential actualCredential2 = gson.fromJson(list.get(1).toString(), - // Credential.class); - Credential actualCredential2 = fromJson.get(1); - assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); - } - - private DataTypeDefinition buildCredentialDataType() { - DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(); - dataTypeDefinition.setName("datatype.1"); - List properties = new ArrayList<>(); - PropertyDefinition propertyDefinition1 = new PropertyDefinition(); - propertyDefinition1.setName("sum"); - propertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); - PropertyDefinition propertyDefinition2 = new PropertyDefinition(); - propertyDefinition2.setName("protocol"); - propertyDefinition2.setType(ToscaPropertyType.STRING.getType()); - PropertyDefinition propertyDefinition3 = new PropertyDefinition(); - propertyDefinition3.setName("token_type"); - propertyDefinition3.setType(ToscaPropertyType.STRING.getType()); - PropertyDefinition propertyDefinition4 = new PropertyDefinition(); - propertyDefinition4.setName("token"); - propertyDefinition4.setType(ToscaPropertyType.STRING.getType()); - PropertyDefinition propertyDefinition5 = new PropertyDefinition(); - propertyDefinition5.setName("keys"); - propertyDefinition5.setType(ToscaPropertyType.MAP.getType()); - PropertyDefinition propertyDefinition6 = new PropertyDefinition(); - propertyDefinition6.setName("mylist"); - propertyDefinition6.setType(ToscaPropertyType.LIST.getType()); - SchemaDefinition entrySchema = new SchemaDefinition(); - PropertyDataDefinition property = new PropertyDataDefinition(); - property.setType("string"); - entrySchema.setProperty(property); - propertyDefinition6.setSchema(entrySchema); - PropertyDefinition propertyDefinition7 = new PropertyDefinition(); - propertyDefinition7.setName("user"); - propertyDefinition7.setType(ToscaPropertyType.STRING.getType()); - PropertyDefinition propertyDefinition8 = new PropertyDefinition(); - propertyDefinition8.setName("isMandatory"); - propertyDefinition8.setType(ToscaPropertyType.BOOLEAN.getType()); - - PropertyDefinition propertyDefinition9 = new PropertyDefinition(); - propertyDefinition9.setName("mycity"); - propertyDefinition9.setType("city"); - - properties.add(propertyDefinition1); - properties.add(propertyDefinition2); - properties.add(propertyDefinition3); - properties.add(propertyDefinition4); - properties.add(propertyDefinition5); - properties.add(propertyDefinition6); - properties.add(propertyDefinition7); - properties.add(propertyDefinition8); - properties.add(propertyDefinition9); - - dataTypeDefinition.setProperties(properties); - return dataTypeDefinition; - } - - private static DataTypeDefinition buildCityDataType() { - DataTypeDefinition cityDataType = new DataTypeDefinition(); - cityDataType.setName("city"); - List cityProperties = new ArrayList<>(); - PropertyDefinition cityPropertyDefinition1 = new PropertyDefinition(); - cityPropertyDefinition1.setName("age"); - cityPropertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); - PropertyDefinition cityPropertyDefinition2 = new PropertyDefinition(); - cityPropertyDefinition2.setName("address"); - cityPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); - - cityProperties.add(cityPropertyDefinition1); - cityProperties.add(cityPropertyDefinition2); - - cityDataType.setProperties(cityProperties); - return cityDataType; - } - - private static DataTypeDefinition buildPersonDataType() { - DataTypeDefinition personDataType = new DataTypeDefinition(); - personDataType.setName("person"); - List personProperties = new ArrayList<>(); - PropertyDefinition personPropertyDefinition1 = new PropertyDefinition(); - personPropertyDefinition1.setName("age"); - personPropertyDefinition1.setType("myinteger"); - PropertyDefinition personPropertyDefinition2 = new PropertyDefinition(); - personPropertyDefinition2.setName("address"); - personPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); - - personProperties.add(personPropertyDefinition1); - personProperties.add(personPropertyDefinition2); - - personDataType.setProperties(personProperties); - return personDataType; - } - - private static DataTypeDefinition buildFileDataType() { - DataTypeDefinition fileDataType = new DataTypeDefinition(); - fileDataType.setName("file"); - List fileProperties = new ArrayList<>(); - PropertyDefinition filePropertyDefinition1 = new PropertyDefinition(); - filePropertyDefinition1.setName("age"); - filePropertyDefinition1.setType("integer"); - - PropertyDefinition filePropertyDefinition2 = new PropertyDefinition(); - filePropertyDefinition2.setName("attributes"); - filePropertyDefinition2.setType(ToscaPropertyType.MAP.getType()); - - fileProperties.add(filePropertyDefinition1); - fileProperties.add(filePropertyDefinition2); - - SchemaDefinition entrySchema = new SchemaDefinition(); - PropertyDataDefinition property = new PropertyDataDefinition(); - property.setType("city"); - entrySchema.setProperty(property); - filePropertyDefinition2.setSchema(entrySchema); - - fileDataType.setProperties(fileProperties); - return fileDataType; - } - - private static DataTypeDefinition getPrimitiveDataType(String type) { - - DataTypeDefinition derivedFrom = new DataTypeDefinition(); - derivedFrom.setName(type); - - return derivedFrom; - - } - - private static DataTypeDefinition buildDerivedFromIntegerType() { + private void validateListOfCredential(Gson gson, String convertedValue) { + + log.debug(convertedValue); + Type type = new TypeToken>() { + }.getType(); + + List fromJson = gson.fromJson(convertedValue, type); + + assertEquals("check list size", 2, fromJson.size()); + + // Credential actualCredential1 = gson.fromJson(list.get(0).toString(), + // Credential.class); + Credential actualCredential1 = fromJson.get(0); + assertEquals("check sum", 5, actualCredential1.getSum().intValue()); + assertEquals("check protocol", "protocol.,\":;>", actualCredential1.getProtocol()); + String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; + List convertedStrList = Arrays.asList(convertedStrArr); + assertEquals("check list", convertedStrList, actualCredential1.getMylist()); + + assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); + assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); + + // Credential actualCredential2 = gson.fromJson(list.get(1).toString(), + // Credential.class); + Credential actualCredential2 = fromJson.get(1); + assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); + } + + private DataTypeDefinition buildCredentialDataType() { + DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(); + dataTypeDefinition.setName("datatype.1"); + List properties = new ArrayList<>(); + PropertyDefinition propertyDefinition1 = new PropertyDefinition(); + propertyDefinition1.setName("sum"); + propertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); + PropertyDefinition propertyDefinition2 = new PropertyDefinition(); + propertyDefinition2.setName("protocol"); + propertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition3 = new PropertyDefinition(); + propertyDefinition3.setName("token_type"); + propertyDefinition3.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition4 = new PropertyDefinition(); + propertyDefinition4.setName("token"); + propertyDefinition4.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition5 = new PropertyDefinition(); + propertyDefinition5.setName("keys"); + propertyDefinition5.setType(ToscaPropertyType.MAP.getType()); + PropertyDefinition propertyDefinition6 = new PropertyDefinition(); + propertyDefinition6.setName("mylist"); + propertyDefinition6.setType(ToscaPropertyType.LIST.getType()); + SchemaDefinition entrySchema = new SchemaDefinition(); + PropertyDataDefinition property = new PropertyDataDefinition(); + property.setType("string"); + entrySchema.setProperty(property); + propertyDefinition6.setSchema(entrySchema); + PropertyDefinition propertyDefinition7 = new PropertyDefinition(); + propertyDefinition7.setName("user"); + propertyDefinition7.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition8 = new PropertyDefinition(); + propertyDefinition8.setName("isMandatory"); + propertyDefinition8.setType(ToscaPropertyType.BOOLEAN.getType()); + + PropertyDefinition propertyDefinition9 = new PropertyDefinition(); + propertyDefinition9.setName("mycity"); + propertyDefinition9.setType("city"); + + properties.add(propertyDefinition1); + properties.add(propertyDefinition2); + properties.add(propertyDefinition3); + properties.add(propertyDefinition4); + properties.add(propertyDefinition5); + properties.add(propertyDefinition6); + properties.add(propertyDefinition7); + properties.add(propertyDefinition8); + properties.add(propertyDefinition9); + + dataTypeDefinition.setProperties(properties); + return dataTypeDefinition; + } + + private static DataTypeDefinition buildCityDataType() { + DataTypeDefinition cityDataType = new DataTypeDefinition(); + cityDataType.setName("city"); + List cityProperties = new ArrayList<>(); + PropertyDefinition cityPropertyDefinition1 = new PropertyDefinition(); + cityPropertyDefinition1.setName("age"); + cityPropertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); + PropertyDefinition cityPropertyDefinition2 = new PropertyDefinition(); + cityPropertyDefinition2.setName("address"); + cityPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + + cityProperties.add(cityPropertyDefinition1); + cityProperties.add(cityPropertyDefinition2); + + cityDataType.setProperties(cityProperties); + return cityDataType; + } + + private static DataTypeDefinition buildPersonDataType() { + DataTypeDefinition personDataType = new DataTypeDefinition(); + personDataType.setName("person"); + List personProperties = new ArrayList<>(); + PropertyDefinition personPropertyDefinition1 = new PropertyDefinition(); + personPropertyDefinition1.setName("age"); + personPropertyDefinition1.setType("myinteger"); + PropertyDefinition personPropertyDefinition2 = new PropertyDefinition(); + personPropertyDefinition2.setName("address"); + personPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + + personProperties.add(personPropertyDefinition1); + personProperties.add(personPropertyDefinition2); + + personDataType.setProperties(personProperties); + return personDataType; + } + + private static DataTypeDefinition buildFileDataType() { + DataTypeDefinition fileDataType = new DataTypeDefinition(); + fileDataType.setName("file"); + List fileProperties = new ArrayList<>(); + PropertyDefinition filePropertyDefinition1 = new PropertyDefinition(); + filePropertyDefinition1.setName("age"); + filePropertyDefinition1.setType("integer"); + + PropertyDefinition filePropertyDefinition2 = new PropertyDefinition(); + filePropertyDefinition2.setName("attributes"); + filePropertyDefinition2.setType(ToscaPropertyType.MAP.getType()); + + fileProperties.add(filePropertyDefinition1); + fileProperties.add(filePropertyDefinition2); + + SchemaDefinition entrySchema = new SchemaDefinition(); + PropertyDataDefinition property = new PropertyDataDefinition(); + property.setType("city"); + entrySchema.setProperty(property); + filePropertyDefinition2.setSchema(entrySchema); + + fileDataType.setProperties(fileProperties); + return fileDataType; + } + + private static DataTypeDefinition getPrimitiveDataType(String type) { + + DataTypeDefinition derivedFrom = new DataTypeDefinition(); + derivedFrom.setName(type); + + return derivedFrom; + + } + + private static DataTypeDefinition buildDerivedFromIntegerType() { - DataTypeDefinition derivedFrom = getPrimitiveDataType("integer"); + DataTypeDefinition derivedFrom = getPrimitiveDataType("integer"); - DataTypeDefinition myIntegerDataType = new DataTypeDefinition(); - myIntegerDataType.setDerivedFrom(derivedFrom); + DataTypeDefinition myIntegerDataType = new DataTypeDefinition(); + myIntegerDataType.setDerivedFrom(derivedFrom); - myIntegerDataType.setName("myinteger"); + myIntegerDataType.setName("myinteger"); - return myIntegerDataType; - } + return myIntegerDataType; + } - public static class MyFile { + public static class MyFile { - Integer age; + Integer age; - Map attributes; - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } + Map attributes; + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } - public Map getAttributes() { - return attributes; - } + public Map getAttributes() { + return attributes; + } - public void setAttributes(Map attributes) { - this.attributes = attributes; - } + public void setAttributes(Map attributes) { + this.attributes = attributes; + } - } + } - public static class City { + public static class City { - String address; - Integer age; + String address; + Integer age; - public City(String address, Integer age) { - super(); - this.address = address; - this.age = age; - } + public City(String address, Integer age) { + super(); + this.address = address; + this.age = age; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } - public Integer getAge() { - return age; - } + public Integer getAge() { + return age; + } - public void setAge(Integer age) { - this.age = age; - } + public void setAge(Integer age) { + this.age = age; + } - } + } - public static class Person { + public static class Person { - String address; - Integer age; + String address; + Integer age; - public Person(String address, Integer age) { - super(); - this.address = address; - this.age = age; - } + public Person(String address, Integer age) { + super(); + this.address = address; + this.age = age; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } - public Integer getAge() { - return age; - } + public Integer getAge() { + return age; + } - public void setAge(Integer age) { - this.age = age; - } + public void setAge(Integer age) { + this.age = age; + } - @Override - public String toString() { - return "Person [address=" + address + ", age=" + age + "]"; - } + @Override + public String toString() { + return "Person [address=" + address + ", age=" + age + "]"; + } - } + } - public static class Credential { + public static class Credential { - String protocol; - Integer sum; - String token_type; - String token; - Map keys; - String user; - Boolean isMandatory; - List mylist; - City mycity; + String protocol; + Integer sum; + String token_type; + String token; + Map keys; + String user; + Boolean isMandatory; + List mylist; + City mycity; - public Credential(String protocol, Integer sum, String token_type, String token, Map keys, - String user, Boolean isMandatory, List mylist) { - super(); - this.protocol = protocol; - this.sum = sum; - this.token_type = token_type; - this.token = token; - this.keys = keys; - this.user = user; - this.isMandatory = isMandatory; - this.mylist = mylist; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getToken_type() { - return token_type; - } - - public void setToken_type(String token_type) { - this.token_type = token_type; - } - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - public Map getKeys() { - return keys; - } - - public void setKeys(Map keys) { - this.keys = keys; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public Boolean getIsMandatory() { - return isMandatory; - } - - public void setIsMandatory(Boolean isMandatory) { - this.isMandatory = isMandatory; - } - - public Integer getSum() { - return sum; - } - - public void setSum(Integer sum) { - this.sum = sum; - } - - public List getMylist() { - return mylist; - } - - public void setMylist(List mylist) { - this.mylist = mylist; - } - - public City getMycity() { - return mycity; - } - - public void setMycity(City mycity) { - this.mycity = mycity; - } - - @Override - public String toString() { - return "Credential [protocol=" + protocol + ", token_type=" + token_type + ", token=" + token + ", keys=" - + keys + ", user=" + user + ", isMandatory=" + isMandatory + "]"; - } - - } + public Credential(String protocol, Integer sum, String token_type, String token, Map keys, + String user, Boolean isMandatory, List mylist) { + super(); + this.protocol = protocol; + this.sum = sum; + this.token_type = token_type; + this.token = token; + this.keys = keys; + this.user = user; + this.isMandatory = isMandatory; + this.mylist = mylist; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getToken_type() { + return token_type; + } + + public void setToken_type(String token_type) { + this.token_type = token_type; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public Map getKeys() { + return keys; + } + + public void setKeys(Map keys) { + this.keys = keys; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Boolean getIsMandatory() { + return isMandatory; + } + + public void setIsMandatory(Boolean isMandatory) { + this.isMandatory = isMandatory; + } + + public Integer getSum() { + return sum; + } + + public void setSum(Integer sum) { + this.sum = sum; + } + + public List getMylist() { + return mylist; + } + + public void setMylist(List mylist) { + this.mylist = mylist; + } + + public City getMycity() { + return mycity; + } + + public void setMycity(City mycity) { + this.mycity = mycity; + } + + @Override + public String toString() { + return "Credential [protocol=" + protocol + ", token_type=" + token_type + ", token=" + token + ", keys=" + + keys + ", user=" + user + ", isMandatory=" + isMandatory + "]"; + } + + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java index e356b49a10..a0b6ea6fd3 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl.util; +import fj.data.Either; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -33,63 +34,61 @@ import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; import org.openecomp.sdc.common.util.ValidationUtils; -import fj.data.Either; - public class OperationTestsUtil { - public static String deleteAndCreateServiceCategory(String category, TitanGenericDao titanDao) { - CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); - categoryData.getCategoryDataDefinition().setName(category); - categoryData.getCategoryDataDefinition() - .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); - categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( - ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ServiceNewCategory)); - titanDao.deleteNode(categoryData, CategoryData.class); - Either createNode = titanDao.createNode(categoryData, CategoryData.class); - return (String) createNode.left().value().getUniqueId(); - } + public static String deleteAndCreateServiceCategory(String category, TitanGenericDao titanDao) { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setName(category); + categoryData.getCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); + categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( + ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ServiceNewCategory)); + titanDao.deleteNode(categoryData, CategoryData.class); + Either createNode = titanDao.createNode(categoryData, CategoryData.class); + return (String) createNode.left().value().getUniqueId(); + } - public static String deleteAndCreateResourceCategory(String category, String subcategory, - TitanGenericDao titanDao) { + public static String deleteAndCreateResourceCategory(String category, String subcategory, + TitanGenericDao titanDao) { - CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory); - categoryData.getCategoryDataDefinition().setName(category); - categoryData.getCategoryDataDefinition() - .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); - categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( - ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ResourceNewCategory)); + CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory); + categoryData.getCategoryDataDefinition().setName(category); + categoryData.getCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); + categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( + ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ResourceNewCategory)); - SubCategoryData subcategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory); - subcategoryData.getSubCategoryDataDefinition().setName(subcategory); - subcategoryData.getSubCategoryDataDefinition() - .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); - subcategoryData.getSubCategoryDataDefinition().setUniqueId(UniqueIdBuilder - .buildSubCategoryUid(categoryData.getCategoryDataDefinition().getUniqueId(), subcategory)); - titanDao.deleteNode(categoryData, CategoryData.class); - titanDao.deleteNode(subcategoryData, SubCategoryData.class); - Either createNode = titanDao.createNode(categoryData, CategoryData.class); - titanDao.createNode(subcategoryData, SubCategoryData.class); - titanDao.createRelation(categoryData, subcategoryData, GraphEdgeLabels.SUB_CATEGORY, null); - return (String) createNode.left().value().getUniqueId(); - } + SubCategoryData subcategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory); + subcategoryData.getSubCategoryDataDefinition().setName(subcategory); + subcategoryData.getSubCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); + subcategoryData.getSubCategoryDataDefinition().setUniqueId(UniqueIdBuilder + .buildSubCategoryUid(categoryData.getCategoryDataDefinition().getUniqueId(), subcategory)); + titanDao.deleteNode(categoryData, CategoryData.class); + titanDao.deleteNode(subcategoryData, SubCategoryData.class); + Either createNode = titanDao.createNode(categoryData, CategoryData.class); + titanDao.createNode(subcategoryData, SubCategoryData.class); + titanDao.createRelation(categoryData, subcategoryData, GraphEdgeLabels.SUB_CATEGORY, null); + return (String) createNode.left().value().getUniqueId(); + } - public static void deleteServiceCategory(String category, TitanGenericDao titanDao) { - ServiceCategoryData categoryData = new ServiceCategoryData(category); - titanDao.deleteNode(categoryData, ServiceCategoryData.class); - } + public static void deleteServiceCategory(String category, TitanGenericDao titanDao) { + ServiceCategoryData categoryData = new ServiceCategoryData(category); + titanDao.deleteNode(categoryData, ServiceCategoryData.class); + } - public static void deleteResourceCategory(String category, String subcategory, TitanGenericDao titanDao) { - ResourceCategoryData categoryData = new ResourceCategoryData(category, subcategory); - titanDao.deleteNode(categoryData, ResourceCategoryData.class); - } + public static void deleteResourceCategory(String category, String subcategory, TitanGenericDao titanDao) { + ResourceCategoryData categoryData = new ResourceCategoryData(category, subcategory); + titanDao.deleteNode(categoryData, ResourceCategoryData.class); + } - public static User convertUserDataToUser(UserData modifierData) { - User modifier = new User(); - modifier.setUserId(modifierData.getUserId()); - modifier.setEmail(modifierData.getEmail()); - modifier.setFirstName(modifierData.getFirstName()); - modifier.setLastName(modifierData.getLastName()); - modifier.setRole(modifierData.getRole()); - return modifier; - } + public static User convertUserDataToUser(UserData modifierData) { + User modifier = new User(); + modifier.setUserId(modifierData.getUserId()); + modifier.setEmail(modifierData.getEmail()); + modifier.setFirstName(modifierData.getFirstName()); + modifier.setLastName(modifierData.getLastName()); + modifier.setRole(modifierData.getRole()); + return modifier; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java index c305b12834..7ba2e097c2 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java @@ -32,340 +32,339 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; +import java.util.*; +import java.util.Map.Entry; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class PrintGraph { - public void printGraphVertices(TitanGraph graph) { + public void printGraphVertices(TitanGraph graph) { - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - } + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + } - } - // graph.commit(); - graph.tx().commit(); - } + } + // graph.commit(); + graph.tx().commit(); + } - public void printGraphEdges(TitanGraph graph) { - Iterable vertices = graph.query().edges(); + public void printGraphEdges(TitanGraph graph) { + Iterable vertices = graph.query().edges(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - Edge edge = iterator.next(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + Edge edge = iterator.next(); - } + } - } - graph.tx().commit(); - } + } + graph.tx().commit(); + } - public String buildGraphForWebgraphWiz(TitanGraph graph) { + public String buildGraphForWebgraphWiz(TitanGraph graph) { - StringBuilder builder = new StringBuilder(); - builder.append("digraph finite_state_machine {\n"); - builder.append("rankdir=LR;\n"); - builder.append("size=\"15,10\" \n"); - Iterable vertices = graph.query().vertices(); + StringBuilder builder = new StringBuilder(); + builder.append("digraph finite_state_machine {\n"); + builder.append("rankdir=LR;\n"); + builder.append("size=\"15,10\" \n"); + Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); - Map properties = getProperties(vertex); + Map properties = getProperties(vertex); - String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); - String color = getColorByNodeType(nodeLabel); + String color = getColorByNodeType(nodeLabel); - String uid = getNodeIdByLabel(nodeLabel, properties); + String uid = getNodeIdByLabel(nodeLabel, properties); - String nodeRecord = buildNodeRecord(uid, color, properties); + String nodeRecord = buildNodeRecord(uid, color, properties); - builder.append(nodeRecord); + builder.append(nodeRecord); - } + } - } + } - Iterable edges = graph.query().edges(); + Iterable edges = graph.query().edges(); - if (edges != null) { - Iterator iterator = edges.iterator(); - while (iterator.hasNext()) { - Edge edge = iterator.next(); + if (edges != null) { + Iterator iterator = edges.iterator(); + while (iterator.hasNext()) { + Edge edge = iterator.next(); - Vertex vertexFrom = edge.outVertex(); - Vertex vertexTo = edge.inVertex(); - String fromUid = getNodeIdByLabel(vertexFrom.value(GraphPropertiesDictionary.LABEL.getProperty()), - getProperties(vertexFrom)); - String toUid = getNodeIdByLabel(vertexTo.value(GraphPropertiesDictionary.LABEL.getProperty()), - getProperties(vertexTo)); + Vertex vertexFrom = edge.outVertex(); + Vertex vertexTo = edge.inVertex(); + String fromUid = getNodeIdByLabel(vertexFrom.value(GraphPropertiesDictionary.LABEL.getProperty()), + getProperties(vertexFrom)); + String toUid = getNodeIdByLabel(vertexTo.value(GraphPropertiesDictionary.LABEL.getProperty()), + getProperties(vertexTo)); - String edgeLabel = edge.label(); + String edgeLabel = edge.label(); - String edgeRecord = buildEdgeRecord(fromUid, toUid, edgeLabel, getProperties(edge)); + String edgeRecord = buildEdgeRecord(fromUid, toUid, edgeLabel, getProperties(edge)); - builder.append(edgeRecord); - } + builder.append(edgeRecord); + } - } + } - builder.append(" } "); + builder.append(" } "); - return builder.toString(); + return builder.toString(); - } + } - private String buildEdgeRecord(String fromUid, String toUid, String edgeLabel, Map properties) { + private String buildEdgeRecord(String fromUid, String toUid, String edgeLabel, Map properties) { - StringBuilder builder = new StringBuilder(); - // LR_0 -> LR_2 [ label = "SS(B)" ]; + StringBuilder builder = new StringBuilder(); + // LR_0 -> LR_2 [ label = "SS(B)" ]; - String generatedProps = generateStringFromProperties(properties); + String generatedProps = generateStringFromProperties(properties); - String color = getEdgeColorByLabel(edgeLabel); + String color = getEdgeColorByLabel(edgeLabel); - builder.append("\"" + fromUid + "\"" + " -> " + "\"" + toUid + "\"" + " [ color = " + color + " label = \"" - + edgeLabel + "(" + generatedProps + ")\"" + " ] " + "\n"); + builder.append("\"" + fromUid + "\"" + " -> " + "\"" + toUid + "\"" + " [ color = " + color + " label = \"" + + edgeLabel + "(" + generatedProps + ")\"" + " ] " + "\n"); - return builder.toString(); - } + return builder.toString(); + } - private String getEdgeColorByLabel(String edgeLabel) { + private String getEdgeColorByLabel(String edgeLabel) { - GraphEdgeLabels edgeLabelEnum = GraphEdgeLabels.getByName(edgeLabel); + GraphEdgeLabels edgeLabelEnum = GraphEdgeLabels.getByName(edgeLabel); - String color = "black"; + String color = "black"; - switch (edgeLabelEnum) { - case PROPERTY: - color = "orange"; - break; - case CAPABILITY: - break; - case DERIVED_FROM: - color = "red"; - default: - break; - } + switch (edgeLabelEnum) { + case PROPERTY: + color = "orange"; + break; + case CAPABILITY: + break; + case DERIVED_FROM: + color = "red"; + default: + break; + } - return color; - } + return color; + } - private String generateStringFromProperties(Map properties) { + private String generateStringFromProperties(Map properties) { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - if (properties != null) { - for (Entry entry : properties.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue().toString(); - builder.append(key + "=" + value + "__"); - } - } - return builder.toString(); + if (properties != null) { + for (Entry entry : properties.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue().toString(); + builder.append(key + "=" + value + "__"); + } + } + return builder.toString(); - } + } - private String buildNodeRecord(String uid, String color, Map properties) { + private String buildNodeRecord(String uid, String color, Map properties) { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - builder.append("\"" + uid + "\"" + " [ "); - builder.append("style = \"bold\" "); - builder.append(" color = \"" + color + "\""); - builder.append("shape = \"Mrecord\" "); + builder.append("\"" + uid + "\"" + " [ "); + builder.append("style = \"bold\" "); + builder.append(" color = \"" + color + "\""); + builder.append("shape = \"Mrecord\" "); - String label = ""; - int maxKeyLength = 0; - for (Entry entry1 : properties.entrySet()) { - String key = entry1.getKey(); - int keyLength = key.length(); - if (keyLength > maxKeyLength) { - maxKeyLength = keyLength; - } - } - - boolean first = true; - for (Entry entry : properties.entrySet()) { - - String key = entry.getKey(); - String value = entry.getValue().toString(); - - if (key.equals(GraphPropertiesDictionary.CONSTRAINTS.getProperty())) { - value = value.replaceAll("[^\\w\\s]", "_"); - } - - key = padKey(key, maxKeyLength); - - if (first) { - first = false; - } else { - label += " | "; - } - label += " { " + key + " | " + value + " } "; - } - - builder.append("label = \"" + label + "\" "); - builder.append(" ] "); - builder.append(" \n "); - return builder.toString(); - } - - private String getNodeIdByLabel(String nodeLabel, Map properties) { - - NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); - - String uid = null; - switch (typeEnum) { - - case User: - uid = (String) properties.get(GraphPropertiesDictionary.USERID.getProperty()); - break; - case ServiceCategory: - case ResourceCategory: - case Tag: - uid = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty()); - break; - - default: - uid = (String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - break; - } - - return uid; - } - - private String getColorByNodeType(String nodeLabel) { - - NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); - - String color = "red"; - switch (typeEnum) { - case ServiceCategory: - color = "blue"; - break; - case ResourceCategory: - color = "blue"; - break; - case Resource: - color = "forestgreen"; - break; - case User: - color = "green"; - break; - case Capability: - color = "lightgreen"; - break; - case CapabilityType: - color = "gray"; - break; - case Property: - color = "cyan"; - break; - case RelationshipType: - color = "darkorchid"; - break; - case Requirement: - color = "gold"; - break; - case RequirementImpl: - // color = "forestgreen"; - color = "gold"; - break; - case Service: - color = "cyan4"; - break; - case Tag: - color = "dimgrey"; - break; - default: - break; - - } - - return color; - } - - private String padKey(String key, int maxKeyLength) { - - int len = key.length(); - for (int i = len; i < maxKeyLength; i++) { - key += " "; - } - - return key; - } - - public int getNumberOfVertices(TitanGraph graph) { - int counter = 0; - Iterable vertices = graph.query().vertices(); - - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - counter++; - } - } - return counter; - } - - public Set getVerticesSet(TitanGraph titanGraph) { - - Set set = new HashSet(); - - Iterable vertices = titanGraph.query().vertices(); - - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - - Map properties = getProperties(vertex); - - String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); - - String uid = getNodeIdByLabel(nodeLabel, properties); - - set.add(uid); - } - } - - return set; - - } - - public Map getProperties(Element element) { - - Map result = null; - - if (element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, - element.keys().toArray(new String[element.keys().size()])); - result = new HashMap(); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - result.put(key, value); - } - } - return result; - } + String label = ""; + int maxKeyLength = 0; + for (Entry entry1 : properties.entrySet()) { + String key = entry1.getKey(); + int keyLength = key.length(); + if (keyLength > maxKeyLength) { + maxKeyLength = keyLength; + } + } + + boolean first = true; + for (Entry entry : properties.entrySet()) { + + String key = entry.getKey(); + String value = entry.getValue().toString(); + + if (key.equals(GraphPropertiesDictionary.CONSTRAINTS.getProperty())) { + value = value.replaceAll("[^\\w\\s]", "_"); + } + + key = padKey(key, maxKeyLength); + + if (first) { + first = false; + } else { + label += " | "; + } + label += " { " + key + " | " + value + " } "; + } + + builder.append("label = \"" + label + "\" "); + builder.append(" ] "); + builder.append(" \n "); + return builder.toString(); + } + + private String getNodeIdByLabel(String nodeLabel, Map properties) { + + NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); + + String uid = null; + switch (typeEnum) { + + case User: + uid = (String) properties.get(GraphPropertiesDictionary.USERID.getProperty()); + break; + case ServiceCategory: + case ResourceCategory: + case Tag: + uid = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty()); + break; + + default: + uid = (String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + break; + } + + return uid; + } + + private String getColorByNodeType(String nodeLabel) { + + NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); + + String color = "red"; + switch (typeEnum) { + case ServiceCategory: + color = "blue"; + break; + case ResourceCategory: + color = "blue"; + break; + case Resource: + color = "forestgreen"; + break; + case User: + color = "green"; + break; + case Capability: + color = "lightgreen"; + break; + case CapabilityType: + color = "gray"; + break; + case Property: + color = "cyan"; + break; + case RelationshipType: + color = "darkorchid"; + break; + case Requirement: + color = "gold"; + break; + case RequirementImpl: + // color = "forestgreen"; + color = "gold"; + break; + case Service: + color = "cyan4"; + break; + case Tag: + color = "dimgrey"; + break; + default: + break; + + } + + return color; + } + + private String padKey(String key, int maxKeyLength) { + + int len = key.length(); + for (int i = len; i < maxKeyLength; i++) { + key += " "; + } + + return key; + } + + public int getNumberOfVertices(TitanGraph graph) { + int counter = 0; + Iterable vertices = graph.query().vertices(); + + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + counter++; + } + } + return counter; + } + + public Set getVerticesSet(TitanGraph titanGraph) { + + Set set = new HashSet<>(); + + Iterable vertices = titanGraph.query().vertices(); + + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map properties = getProperties(vertex); + + String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + + String uid = getNodeIdByLabel(nodeLabel, properties); + + set.add(uid); + } + } + + return set; + + } + + public Map getProperties(Element element) { + + Map result = null; + + if (element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, + element.keys().toArray(new String[element.keys().size()])); + result = new HashMap<>(); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + result.put(key, value); + } + } + return result; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java index b6b951bdc4..ae32bb1c28 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java @@ -22,15 +22,15 @@ package org.openecomp.sdc.be.model.operations.impl.util; public class ResourceCreationUtils { - public static String ATT_UID = "jm007a"; - public static String FIRST_NAME = "Julia"; - public static String LAST_NAME = "Hendrix"; - public static String DEFAULT_RESOURCE_NAME = "my-resource"; - public static String DEFAULT_RESOURCE_VERSION = "1.0"; - public static String DEFAULT_USER_ID = "jh0003"; + public static String ATT_UID = "jm007a"; + public static String FIRST_NAME = "Julia"; + public static String LAST_NAME = "Hendrix"; + public static String DEFAULT_RESOURCE_NAME = "my-resource"; + public static String DEFAULT_RESOURCE_VERSION = "1.0"; + public static String DEFAULT_USER_ID = "jh0003"; - public static String MODIFIER_ATT_UID = "jk9990"; - public static String MODIFIER_FIRST_NAME = "Roki"; - public static String MODIFIER_LAST_NAME = "Balaboa"; + public static String MODIFIER_ATT_UID = "jk9990"; + public static String MODIFIER_FIRST_NAME = "Roki"; + public static String MODIFIER_LAST_NAME = "Balaboa"; } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java index 276558eafe..ba066d2d14 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java @@ -20,125 +20,135 @@ package org.openecomp.sdc.be.model.serialize; +import fj.data.Either; +import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.common.util.SerializationUtils; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; +import static org.junit.Assert.fail; public class TestResourceSerialization { - // @Test - public void findAllClassesUsedByResource() { - - Set classesWithoutSerialzable = new HashSet<>(); - Set classestoIgnore = new HashSet<>(); - classestoIgnore.add("java.util.List"); - classestoIgnore.add("java.util.Map"); - classestoIgnore.add("long"); - - Set allClasses = new HashSet<>(); - findAllClassesUsedByResource(Resource.class, allClasses); - ArrayList l; - for (Class clazz : allClasses) { - Class[] interfaces = clazz.getInterfaces(); - if (interfaces != null) { - String collect = Arrays.stream(interfaces).map(p -> p.getName()).collect(Collectors.joining("\n")); - - Class orElse = Arrays.stream(interfaces).filter(p -> p.getName().equals("java.io.Serializable")) - .findAny().orElse(null); - if (orElse == null) { - classesWithoutSerialzable.add(clazz); - } - - } - } - - List collect = classesWithoutSerialzable.stream() - .filter(p -> false == classestoIgnore.contains(p.getName())).collect(Collectors.toList()); - - if (collect != null) { - System.out.println(collect.stream().map(p -> p.getName()).collect(Collectors.joining("\n"))); - assertEquals("check all classes implements Serializable", 0, collect.size()); - } - - } - - public void findAllClassesUsedByResource(Class clazz, Set allClasses) { - - Class superclass = clazz.getSuperclass(); - findAllClassesOfClass(clazz, allClasses); - - if (superclass != null) { - findAllClassesOfClass(superclass, allClasses); - } - - } - - public void findAllClassesOfClass(Class clazz, Set allClasses) { - - Field[] fields = clazz.getDeclaredFields(); - if (fields != null) { - for (Field field : fields) { - String name = field.getName(); - Class type = field.getType(); - - if (type.toString().contains(".List")) { - ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); - Class stringListClass = (Class) stringListType.getActualTypeArguments()[0]; - allClasses.add(stringListClass); - } - - if (type.toString().contains("java.util.Map")) { - ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); - - Type[] actualTypeArguments = stringListType.getActualTypeArguments(); - if (actualTypeArguments != null) { - for (Type actualType : actualTypeArguments) { - - String typeName = actualType.getTypeName(); - // System.out.println("field " + name + "," + - // typeName); - - if (typeName.startsWith("java.util.List<")) { - String internalClass = typeName.replace("java.util.List<", "").replace(">", ""); - // create class from string - Class myClass; - try { - myClass = Class.forName(internalClass); - allClasses.add(myClass); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - assertTrue("Failed to convert " + internalClass + " to class", false); - } - - } else { - try { - Class myClass = Class.forName(typeName); - allClasses.add(myClass); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - assertTrue("Failed to convert " + typeName + " to class", false); - } - - } - } - } - - } - - allClasses.add(type); - } - } - - } + // @Test + public void findAllClassesUsedByResource() { + + Set classesWithoutSerialzable = new HashSet<>(); + Set classestoIgnore = new HashSet<>(); + classestoIgnore.add("java.util.List"); + classestoIgnore.add("java.util.Map"); + classestoIgnore.add("long"); + + Set allClasses = new HashSet<>(); + findAllClassesUsedByResource(Resource.class, allClasses); + ArrayList l; + for (Class clazz : allClasses) { + Class[] interfaces = clazz.getInterfaces(); + if (interfaces != null) { + String collect = Arrays.stream(interfaces).map(Class::getName).collect(Collectors.joining("\n")); + + Class orElse = Arrays.stream(interfaces).filter(p -> p.getName().equals("java.io.Serializable")) + .findAny().orElse(null); + if (orElse == null) { + classesWithoutSerialzable.add(clazz); + } + + } + } + + List collect = classesWithoutSerialzable.stream() + .filter(p -> !classestoIgnore.contains(p.getName())).collect(Collectors.toList()); + + if (collect != null) { + System.out.println(collect.stream().map(Class::getName).collect(Collectors.joining("\n"))); + assertEquals("check all classes implements Serializable", 0, collect.size()); + } + + } + + public void findAllClassesUsedByResource(Class clazz, Set allClasses) { + + Class superclass = clazz.getSuperclass(); + findAllClassesOfClass(clazz, allClasses); + + if (superclass != null) { + findAllClassesOfClass(superclass, allClasses); + } + + } + + public void findAllClassesOfClass(Class clazz, Set allClasses) { + + Field[] fields = clazz.getDeclaredFields(); + if (fields != null) { + for (Field field : fields) { + String name = field.getName(); + Class type = field.getType(); + + if (type.toString().contains(".List")) { + ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); + Class stringListClass = (Class) stringListType.getActualTypeArguments()[0]; + allClasses.add(stringListClass); + } + + if (type.toString().contains("java.util.Map")) { + ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); + + Type[] actualTypeArguments = stringListType.getActualTypeArguments(); + if (actualTypeArguments != null) { + for (Type actualType : actualTypeArguments) { + + String typeName = actualType.getTypeName(); + // System.out.println("field " + name + "," + + // typeName); + + if (typeName.startsWith("java.util.List<")) { + String internalClass = typeName.replace("java.util.List<", "").replace(">", ""); + // create class from string + Class myClass; + try { + myClass = Class.forName(internalClass); + allClasses.add(myClass); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + fail("Failed to convert " + internalClass + " to class"); + } + + } else { + try { + Class myClass = Class.forName(typeName); + allClasses.add(myClass); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + fail("Failed to convert " + typeName + " to class"); + } + + } + } + } + + } + + allClasses.add(type); + } + } + + } + private boolean isClassImplementedSerialize(Class clazz) { + Type[] genericInterfaces = clazz.getGenericInterfaces(); + if (genericInterfaces != null) { + Type orElse = Arrays.stream(genericInterfaces).filter(p -> p.getTypeName().equals("java.io.Serializable")) + .findAny().orElse(null); + if (orElse != null) { + return true; + } + } + return false; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/ToscaTypeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/ToscaTypeTest.java deleted file mode 100644 index 8028813aaf..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/ToscaTypeTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.openecomp.sdc.be.model.tosca; - -import org.junit.Assert; -import org.junit.Test; - - -public class ToscaTypeTest { - - private ToscaType createTestSubject() { - return ToscaType.BOOLEAN; - } - - - @Test - public void testFromYamlTypeName() throws Exception { - String typeName = ""; - ToscaType result; - - // test 1 - typeName = null; - result = ToscaType.fromYamlTypeName(typeName); - Assert.assertEquals(null, result); - - // test 2 - typeName = ""; - result = ToscaType.fromYamlTypeName(typeName); - Assert.assertEquals(null, result); - } - - - @Test - public void testIsValidValue() throws Exception { - ToscaType testSubject; - String value = ""; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isValidValue(value); - } - - - - @Test - public void testConvert() throws Exception { - ToscaType testSubject; - String value = ""; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convert(value); - } - - - @Test - public void testToString() throws Exception { - ToscaType testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraintTest.java deleted file mode 100644 index af8f28dd25..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraintTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class EqualConstraintTest { - - private EqualConstraint createTestSubject() { - return new EqualConstraint(""); - } - - - - - @Test - public void testValidate() throws Exception { - EqualConstraint testSubject; - Object propertyValue = null; - - // test 1 - testSubject = createTestSubject(); - propertyValue = null; - testSubject.validate(propertyValue); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraintTest.java deleted file mode 100644 index 7d959d4016..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraintTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - -public class GreaterThanConstraintTest { - - private GreaterThanConstraint createTestSubject() { - return new GreaterThanConstraint(""); - } - - - - - - - @Test - public void testGetGreaterThan() throws Exception { - GreaterThanConstraint testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGreaterThan(); - } - - - @Test - public void testSetGreaterThan() throws Exception { - GreaterThanConstraint testSubject; - String greaterThan = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setGreaterThan(greaterThan); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraintTest.java deleted file mode 100644 index e1df65ef34..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraintTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class InRangeConstraintTest { - - private InRangeConstraint createTestSubject() { - return new InRangeConstraint(null); - } - - - - - - @Test - public void testGetRangeMinValue() throws Exception { - InRangeConstraint testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRangeMinValue(); - } - - - @Test - public void testSetRangeMinValue() throws Exception { - InRangeConstraint testSubject; - String minValue = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setRangeMinValue(minValue); - } - - - @Test - public void testGetRangeMaxValue() throws Exception { - InRangeConstraint testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRangeMaxValue(); - } - - - @Test - public void testSetRangeMaxValue() throws Exception { - InRangeConstraint testSubject; - String maxValue = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setRangeMaxValue(maxValue); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraintTest.java deleted file mode 100644 index 46a273b892..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraintTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class LengthConstraintTest { - - private LengthConstraint createTestSubject() { - return new LengthConstraint(); - } - - - - - - @Test - public void testGetLength() throws Exception { - LengthConstraint testSubject; - Integer result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLength(); - } - - - @Test - public void testSetLength() throws Exception { - LengthConstraint testSubject; - Integer length = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setLength(length); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraintTest.java deleted file mode 100644 index 54d8725914..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraintTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class LessOrEqualConstraintTest { - - private LessOrEqualConstraint createTestSubject() { - return new LessOrEqualConstraint(""); - } - - - - - - - - @Test - public void testGetLessOrEqual() throws Exception { - LessOrEqualConstraint testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLessOrEqual(); - } - - - @Test - public void testSetLessOrEqual() throws Exception { - LessOrEqualConstraint testSubject; - String lessOrEqual = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLessOrEqual(lessOrEqual); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraintTest.java deleted file mode 100644 index 55c70c51c3..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraintTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class MaxLengthConstraintTest { - - private MaxLengthConstraint createTestSubject() { - return new MaxLengthConstraint(null); - } - - - - @Test - public void testGetMaxLength() throws Exception { - MaxLengthConstraint testSubject; - Integer result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMaxLength(); - } - - - @Test - public void testSetMaxLength() throws Exception { - MaxLengthConstraint testSubject; - Integer maxLength = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setMaxLength(maxLength); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraintTest.java deleted file mode 100644 index 1b8694f49e..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraintTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class MinLengthConstraintTest { - - private MinLengthConstraint createTestSubject() { - return new MinLengthConstraint(null); - } - - - - - - @Test - public void testGetMinLength() throws Exception { - MinLengthConstraint testSubject; - Integer result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMinLength(); - } - - - @Test - public void testSetMinLength() throws Exception { - MinLengthConstraint testSubject; - Integer minLength = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setMinLength(minLength); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraintTest.java deleted file mode 100644 index 07c657ceac..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraintTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import org.junit.Test; - - -public class PatternConstraintTest { - - private PatternConstraint createTestSubject() { - return new PatternConstraint(); - } - - - @Test - public void testSetPattern() throws Exception { - PatternConstraint testSubject; - String pattern = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setPattern(pattern); - } - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraintTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraintTest.java deleted file mode 100644 index 9b4c6b932d..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraintTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.constraints; - -import java.util.List; - -import org.junit.Test; - - -public class ValidValuesConstraintTest { - - private ValidValuesConstraint createTestSubject() { - return new ValidValuesConstraint(null); - } - - - - - - - - @Test - public void testGetValidValues() throws Exception { - ValidValuesConstraint testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValidValues(); - } - - - @Test - public void testSetValidValues() throws Exception { - ValidValuesConstraint testSubject; - List validValues = null; - - // default test - testSubject = createTestSubject(); - testSubject.setValidValues(validValues); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverterTest.java deleted file mode 100644 index 384c2d94ef..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class BooleanConverterTest { - - private BooleanConverter createTestSubject() { - return BooleanConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - BooleanConverter result; - - // default test - result = BooleanConverter.getInstance(); - } - - - @Test - public void testConvertToToscaValue() throws Exception { - BooleanConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java index d5425504e6..500ecfc497 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java @@ -1,19 +1,18 @@ package org.openecomp.sdc.be.model.tosca.converters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import com.google.gson.JsonObject; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; - -import com.google.gson.JsonObject; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; public class DataTypePropertyConverterTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverterTest.java deleted file mode 100644 index d151f2aa27..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class DefaultConverterTest { - - private DefaultConverter createTestSubject() { - return DefaultConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - DefaultConverter result; - - // default test - result = DefaultConverter.getInstance(); - } - - - @Test - public void testConvert() throws Exception { - DefaultConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convert(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverterTest.java deleted file mode 100644 index 1fb5c8cbf7..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverterTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class FloatConverterTest { - - private FloatConverter createTestSubject() { - return FloatConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - FloatConverter result; - - // default test - result = FloatConverter.getInstance(); - } - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverterTest.java deleted file mode 100644 index 41a08b3e66..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverterTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class HeatBooleanConverterTest { - - private HeatBooleanConverter createTestSubject() { - return HeatBooleanConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - HeatBooleanConverter result; - - // default test - result = HeatBooleanConverter.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverterTest.java deleted file mode 100644 index 636170601f..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverterTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class HeatCommaDelimitedListConverterTest { - - private HeatCommaDelimitedListConverter createTestSubject() { - return HeatCommaDelimitedListConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - HeatCommaDelimitedListConverter result; - - // default test - result = HeatCommaDelimitedListConverter.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverterTest.java deleted file mode 100644 index 1d13834748..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverterTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class HeatJsonConverterTest { - - private HeatJsonConverter createTestSubject() { - return HeatJsonConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - HeatJsonConverter result; - - // default test - result = HeatJsonConverter.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverterTest.java deleted file mode 100644 index 93a54a7168..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverterTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class HeatNumberConverterTest { - - private HeatNumberConverter createTestSubject() { - return HeatNumberConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - HeatNumberConverter result; - - // default test - result = HeatNumberConverter.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java index 9f000a835a..285dd9a965 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java @@ -1,32 +1,16 @@ package org.openecomp.sdc.be.model.tosca.converters; -import static org.junit.Assert.assertEquals; - import org.junit.Test; -public class HeatStringConverterTest { - - @Test - public void convertString_strWithQuotes_returnStringAsIs() { - String str = "'i'm string with \"quote\"'"; - String convert = HeatStringConverter.getInstance().convert(str, null, null); - assertEquals(str, convert); - } - - private HeatStringConverter createTestSubject() { - return HeatStringConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - HeatStringConverter result; - - // default test - result = HeatStringConverter.getInstance(); - } +import static org.junit.Assert.assertEquals; - +public class HeatStringConverterTest { + @Test + public void convertString_strWithQuotes_returnStringAsIs() { + String str = "'i'm string with \"quote\"'"; + String convert = HeatStringConverter.getInstance().convert(str, null, null); + assertEquals(str, convert); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverterTest.java deleted file mode 100644 index 8691ba00c5..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverterTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class IntegerConverterTest { - - private IntegerConverter createTestSubject() { - return IntegerConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - IntegerConverter result; - - // default test - result = IntegerConverter.getInstance(); - } - - - @Test - public void testConvertToToscaValue() throws Exception { - IntegerConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - Object result; - - // test 1 - testSubject = createTestSubject(); - value = null; - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - Assert.assertEquals(null, result); - - // test 2 - testSubject = createTestSubject(); - value = ""; - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - Assert.assertEquals(null, result); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverterTest.java deleted file mode 100644 index 537b89509b..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class JsonConverterTest { - - private JsonConverter createTestSubject() { - return JsonConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - JsonConverter result; - - // default test - result = JsonConverter.getInstance(); - } - - - @Test - public void testConvert() throws Exception { - JsonConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convert(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ListConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ListConverterTest.java deleted file mode 100644 index 7002f813c1..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ListConverterTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class ListConverterTest { - - private ListConverter createTestSubject() { - return new ListConverter(); - } - - - @Test - public void testGetInstance() throws Exception { - ListConverter result; - - // default test - result = ListConverter.getInstance(); - } - - - - - - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverterTest.java index fe37d3e8c7..7ace040ce6 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverterTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverterTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class LowerCaseConverterTest { private LowerCaseConverter createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/MapConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/MapConverterTest.java deleted file mode 100644 index c837baa0ab..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/MapConverterTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class MapConverterTest { - - private MapConverter createTestSubject() { - return new MapConverter(); - } - - - @Test - public void testGetInstance() throws Exception { - MapConverter result; - - // default test - result = MapConverter.getInstance(); - } - - - @Test - public void testConvert() throws Exception { - MapConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convert(value, innerType, dataTypes); - } - - - - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertorTest.java deleted file mode 100644 index 0cfdba83d2..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertorTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - -public class StringConvertorTest { - - private StringConvertor createTestSubject() { - return StringConvertor.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - StringConvertor result; - - // default test - result = StringConvertor.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverterTest.java deleted file mode 100644 index d5eab58653..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverterTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - -public class ToscaBooleanConverterTest { - - private ToscaBooleanConverter createTestSubject() { - return ToscaBooleanConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - ToscaBooleanConverter result; - - // default test - result = ToscaBooleanConverter.getInstance(); - } - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java index 00ac26312d..7e9388ee1b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.model.tosca.converters; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertNull; +import org.junit.Test; import java.util.Collections; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertNull; public class ToscaFloatConverterTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverterTest.java deleted file mode 100644 index dc7526eb0e..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class ToscaJsonValueConverterTest { - - private ToscaJsonValueConverter createTestSubject() { - return ToscaJsonValueConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - ToscaJsonValueConverter result; - - // default test - result = ToscaJsonValueConverter.getInstance(); - } - - - @Test - public void testConvertToToscaValue() throws Exception { - ToscaJsonValueConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverterTest.java deleted file mode 100644 index 04ae0696a7..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverterTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import org.junit.Test; - - -public class ToscaListValueConverterTest { - - private ToscaListValueConverter createTestSubject() { - return ToscaListValueConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - ToscaListValueConverter result; - - // default test - result = ToscaListValueConverter.getInstance(); - } - - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertorTest.java deleted file mode 100644 index a9909b882f..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertorTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class ToscaStringConvertorTest { - - private ToscaStringConvertor createTestSubject() { - return ToscaStringConvertor.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - ToscaStringConvertor result; - - // default test - result = ToscaStringConvertor.getInstance(); - } - - - @Test - public void testConvertToToscaValue() throws Exception { - ToscaStringConvertor testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverterTest.java deleted file mode 100644 index ea9a4a8eb7..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.converters; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class ToscaValueDefaultConverterTest { - - private ToscaValueDefaultConverter createTestSubject() { - return ToscaValueDefaultConverter.getInstance(); - } - - - @Test - public void testGetInstance() throws Exception { - ToscaValueDefaultConverter result; - - // default test - result = ToscaValueDefaultConverter.getInstance(); - } - - - @Test - public void testConvertToToscaValue() throws Exception { - ToscaValueDefaultConverter testSubject; - String value = ""; - String innerType = ""; - Map dataTypes = null; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertToToscaValue(value, innerType, dataTypes); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java index aff1750344..b33f1d2310 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java @@ -20,51 +20,51 @@ package org.openecomp.sdc.be.model.tosca.validators; +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - public class IntegerValidatorTest { - private static IntegerValidator validator = IntegerValidator.getInstance(); + private static IntegerValidator validator = IntegerValidator.getInstance(); - @Test - public void testIntegerValidatorDecimal() { - assertTrue(validator.isValid(null, null)); - assertTrue(validator.isValid("", null)); - assertTrue(validator.isValid("0", null)); - assertTrue(validator.isValid("+0", null)); - assertTrue(validator.isValid("-0", null)); - assertTrue(validator.isValid("+65465", null)); - assertTrue(validator.isValid("-65465", null)); - assertTrue(validator.isValid("2147483647", null)); - assertFalse(validator.isValid("2147483648", null)); - assertTrue(validator.isValid("-2147483648", null)); - assertFalse(validator.isValid("-2147483649", null)); - } + @Test + public void testIntegerValidatorDecimal() { + assertTrue(validator.isValid(null, null)); + assertTrue(validator.isValid("", null)); + assertTrue(validator.isValid("0", null)); + assertTrue(validator.isValid("+0", null)); + assertTrue(validator.isValid("-0", null)); + assertTrue(validator.isValid("+65465", null)); + assertTrue(validator.isValid("-65465", null)); + assertTrue(validator.isValid("2147483647", null)); + assertFalse(validator.isValid("2147483648", null)); + assertTrue(validator.isValid("-2147483648", null)); + assertFalse(validator.isValid("-2147483649", null)); + } - @Test - public void testIntegerValidatorHexa() { - assertTrue(validator.isValid("-0xadc", null)); - assertTrue(validator.isValid("+0xadf", null)); - assertTrue(validator.isValid("0x7FFFFFFF", null)); - assertFalse(validator.isValid("0x80000000", null)); - assertTrue(validator.isValid("-0x80000000", null)); - assertFalse(validator.isValid("-0x80000001", null)); - } + @Test + public void testIntegerValidatorHexa() { + assertTrue(validator.isValid("-0xadc", null)); + assertTrue(validator.isValid("+0xadf", null)); + assertTrue(validator.isValid("0x7FFFFFFF", null)); + assertFalse(validator.isValid("0x80000000", null)); + assertTrue(validator.isValid("-0x80000000", null)); + assertFalse(validator.isValid("-0x80000001", null)); + } - public void testIntegerValidatorOctal() { - assertTrue(validator.isValid("0o545435", null)); - assertTrue(validator.isValid("-0o545435", null)); - assertTrue(validator.isValid("0o17777777777", null)); - assertFalse(validator.isValid("0o20000000000", null)); - assertTrue(validator.isValid("-0o20000000000", null)); - assertFalse(validator.isValid("-0o20000000001", null)); - } + public void testIntegerValidatorOctal() { + assertTrue(validator.isValid("0o545435", null)); + assertTrue(validator.isValid("-0o545435", null)); + assertTrue(validator.isValid("0o17777777777", null)); + assertFalse(validator.isValid("0o20000000000", null)); + assertTrue(validator.isValid("-0o20000000000", null)); + assertFalse(validator.isValid("-0o20000000001", null)); + } - @Test - public void testIntegerValidatorIncorrect() { - assertFalse(validator.isValid("-2.147483649", null)); - assertFalse(validator.isValid("dsfasf342342", null)); - } + @Test + public void testIntegerValidatorIncorrect() { + assertFalse(validator.isValid("-2.147483649", null)); + assertFalse(validator.isValid("dsfasf342342", null)); + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java index c82894fe5e..4fa64d6394 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model.tosca.validators; -import static org.junit.Assert.assertFalse; +import org.junit.Test; import java.util.Collections; -import org.junit.Test; +import static org.junit.Assert.assertFalse; public class MapValidatorTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidatorTest.java index 3070c3df4e..dafbab8513 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidatorTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidatorTest.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.junit.Test; import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class ToscaBooleanValidatorTest { private ToscaBooleanValidator createTestSubject() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersionTest.java deleted file mode 100644 index 5e1d37851e..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersionTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.version; - -import org.junit.Test; - - -public class ComparableVersionTest { - - private ComparableVersion createTestSubject() { - return new ComparableVersion(""); - } - - - @Test - public void testParseVersion() throws Exception { - ComparableVersion testSubject; - String version = ""; - - // default test - testSubject = createTestSubject(); - testSubject.parseVersion(version); - } - - - - - - - - - @Test - public void testToString() throws Exception { - ComparableVersion testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } - - - @Test - public void testEquals() throws Exception { - ComparableVersion testSubject; - Object o = null; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.equals(o); - } - - - @Test - public void testHashCode() throws Exception { - ComparableVersion testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.hashCode(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/VersionTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/VersionTest.java deleted file mode 100644 index cf848901e5..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/version/VersionTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.openecomp.sdc.be.model.tosca.version; - -import org.junit.Test; - -public class VersionTest { - - private Version createTestSubject() { - return new Version(""); - } - - - @Test - public void testHashCode() throws Exception { - Version testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.hashCode(); - } - - - @Test - public void testEquals() throws Exception { - Version testSubject; - Object other = null; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.equals(other); - } - - - @Test - public void testCompareTo() throws Exception { - Version testSubject; - Version otherVersion = null; - int result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetMajorVersion() throws Exception { - Version testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMajorVersion(); - } - - - @Test - public void testGetMinorVersion() throws Exception { - Version testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMinorVersion(); - } - - - @Test - public void testGetIncrementalVersion() throws Exception { - Version testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getIncrementalVersion(); - } - - - @Test - public void testGetBuildNumber() throws Exception { - Version testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getBuildNumber(); - } - - - @Test - public void testGetQualifier() throws Exception { - Version testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getQualifier(); - } - - - @Test - public void testParseVersion() throws Exception { - Version testSubject; - String version = ""; - - // default test - testSubject = createTestSubject(); - testSubject.parseVersion(version); - } - - - @Test - public void testGetNextIntegerToken() throws Exception { - Integer result; - - // default test - } - - - @Test - public void testToString() throws Exception { - Version testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiCategoriesTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiCategoriesTest.java deleted file mode 100644 index c0d69fae76..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiCategoriesTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import java.util.List; - -import org.junit.Test; -import org.openecomp.sdc.be.model.category.CategoryDefinition; - - -public class UiCategoriesTest { - - private UiCategories createTestSubject() { - return new UiCategories(); - } - - - @Test - public void testGetResourceCategories() throws Exception { - UiCategories testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResourceCategories(); - } - - - @Test - public void testSetResourceCategories() throws Exception { - UiCategories testSubject; - List resourceCategories = null; - - // default test - testSubject = createTestSubject(); - testSubject.setResourceCategories(resourceCategories); - } - - - @Test - public void testGetServiceCategories() throws Exception { - UiCategories testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceCategories(); - } - - - @Test - public void testSetServiceCategories() throws Exception { - UiCategories testSubject; - List serviceCategories = null; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceCategories(serviceCategories); - } - - - @Test - public void testGetProductCategories() throws Exception { - UiCategories testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProductCategories(); - } - - - @Test - public void testSetProductCategories() throws Exception { - UiCategories testSubject; - List productCategories = null; - - // default test - testSubject = createTestSubject(); - testSubject.setProductCategories(productCategories); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransferTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransferTest.java deleted file mode 100644 index 4fd0ccc944..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransferTest.java +++ /dev/null @@ -1,444 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.category.CategoryDefinition; - - -public class UiComponentDataTransferTest { - - private UiComponentDataTransfer createTestSubject() { - return new UiComponentDataTransfer(); - } - - - @Test - public void testGetArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getArtifacts(); - } - - - @Test - public void testSetArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map artifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setArtifacts(artifacts); - } - - - @Test - public void testGetDeploymentArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDeploymentArtifacts(); - } - - - @Test - public void testSetDeploymentArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map deploymentArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDeploymentArtifacts(deploymentArtifacts); - } - - - @Test - public void testGetToscaArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaArtifacts(); - } - - - @Test - public void testSetToscaArtifacts() throws Exception { - UiComponentDataTransfer testSubject; - Map toscaArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaArtifacts(toscaArtifacts); - } - - - @Test - public void testGetCategories() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCategories(); - } - - - @Test - public void testSetCategories() throws Exception { - UiComponentDataTransfer testSubject; - List categories = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCategories(categories); - } - - - @Test - public void testGetCreatorUserId() throws Exception { - UiComponentDataTransfer testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCreatorUserId(); - } - - - @Test - public void testSetCreatorUserId() throws Exception { - UiComponentDataTransfer testSubject; - String creatorUserId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCreatorUserId(creatorUserId); - } - - - @Test - public void testGetCreatorFullName() throws Exception { - UiComponentDataTransfer testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCreatorFullName(); - } - - - @Test - public void testSetCreatorFullName() throws Exception { - UiComponentDataTransfer testSubject; - String creatorFullName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCreatorFullName(creatorFullName); - } - - - @Test - public void testGetLastUpdaterUserId() throws Exception { - UiComponentDataTransfer testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLastUpdaterUserId(); - } - - - @Test - public void testSetLastUpdaterUserId() throws Exception { - UiComponentDataTransfer testSubject; - String lastUpdaterUserId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLastUpdaterUserId(lastUpdaterUserId); - } - - - @Test - public void testGetLastUpdaterFullName() throws Exception { - UiComponentDataTransfer testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLastUpdaterFullName(); - } - - - @Test - public void testSetLastUpdaterFullName() throws Exception { - UiComponentDataTransfer testSubject; - String lastUpdaterFullName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLastUpdaterFullName(lastUpdaterFullName); - } - - - @Test - public void testGetComponentType() throws Exception { - UiComponentDataTransfer testSubject; - ComponentTypeEnum result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentType(); - } - - - @Test - public void testSetComponentType() throws Exception { - UiComponentDataTransfer testSubject; - ComponentTypeEnum componentType = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentType(componentType); - } - - - @Test - public void testGetComponentInstances() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstances(); - } - - - @Test - public void testSetComponentInstances() throws Exception { - UiComponentDataTransfer testSubject; - List componentInstances = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstances(componentInstances); - } - - - @Test - public void testGetComponentInstancesRelations() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstancesRelations(); - } - - - @Test - public void testSetComponentInstancesRelations() throws Exception { - UiComponentDataTransfer testSubject; - List componentInstancesRelations = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstancesRelations(componentInstancesRelations); - } - - - @Test - public void testGetComponentInstancesInputs() throws Exception { - UiComponentDataTransfer testSubject; - Map> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstancesInputs(); - } - - - @Test - public void testSetComponentInstancesInputs() throws Exception { - UiComponentDataTransfer testSubject; - Map> componentInstancesInputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstancesInputs(componentInstancesInputs); - } - - - @Test - public void testGetComponentInstancesProperties() throws Exception { - UiComponentDataTransfer testSubject; - Map> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstancesProperties(); - } - - - @Test - public void testSetComponentInstancesProperties() throws Exception { - UiComponentDataTransfer testSubject; - Map> componentInstancesProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstancesProperties(componentInstancesProperties); - } - - - @Test - public void testGetComponentInstancesAttributes() throws Exception { - UiComponentDataTransfer testSubject; - Map> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstancesAttributes(); - } - - - @Test - public void testSetComponentInstancesAttributes() throws Exception { - UiComponentDataTransfer testSubject; - Map> componentInstancesAttributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstancesAttributes(componentInstancesAttributes); - } - - - @Test - public void testGetCapabilities() throws Exception { - UiComponentDataTransfer testSubject; - Map> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabilities(); - } - - - @Test - public void testSetCapabilities() throws Exception { - UiComponentDataTransfer testSubject; - Map> capabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabilities(capabilities); - } - - - @Test - public void testGetRequirements() throws Exception { - UiComponentDataTransfer testSubject; - Map> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRequirements(); - } - - - @Test - public void testSetRequirements() throws Exception { - UiComponentDataTransfer testSubject; - Map> requirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRequirements(requirements); - } - - - @Test - public void testGetInputs() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInputs(); - } - - - @Test - public void testSetInputs() throws Exception { - UiComponentDataTransfer testSubject; - List inputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInputs(inputs); - } - - - @Test - public void testGetGroups() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGroups(); - } - - - @Test - public void testSetGroups() throws Exception { - UiComponentDataTransfer testSubject; - List groups = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGroups(groups); - } - - - @Test - public void testGetAdditionalInformation() throws Exception { - UiComponentDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAdditionalInformation(); - } - - - @Test - public void testSetAdditionalInformation() throws Exception { - UiComponentDataTransfer testSubject; - List additionalInformation = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAdditionalInformation(additionalInformation); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransferTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransferTest.java deleted file mode 100644 index e50b6c4633..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransferTest.java +++ /dev/null @@ -1,193 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; - - -public class UiResourceDataTransferTest { - - private UiResourceDataTransfer createTestSubject() { - return new UiResourceDataTransfer(); - } - - - @Test - public void testGetAdditionalInformation() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAdditionalInformation(); - } - - - @Test - public void testSetAdditionalInformation() throws Exception { - UiResourceDataTransfer testSubject; - List additionalInformation = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAdditionalInformation(additionalInformation); - } - - - @Test - public void testGetMetadata() throws Exception { - UiResourceDataTransfer testSubject; - UiResourceMetadata result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMetadata(); - } - - - @Test - public void testSetMetadata() throws Exception { - UiResourceDataTransfer testSubject; - UiResourceMetadata metadata = null; - - // default test - testSubject = createTestSubject(); - testSubject.setMetadata(metadata); - } - - - @Test - public void testGetDerivedFrom() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedFrom(); - } - - - @Test - public void testSetDerivedFrom() throws Exception { - UiResourceDataTransfer testSubject; - List derivedFrom = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedFrom(derivedFrom); - } - - - @Test - public void testGetDerivedList() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedList(); - } - - - @Test - public void testSetDerivedList() throws Exception { - UiResourceDataTransfer testSubject; - List derivedList = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedList(derivedList); - } - - - @Test - public void testGetProperties() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProperties(); - } - - - @Test - public void testSetProperties() throws Exception { - UiResourceDataTransfer testSubject; - List properties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setProperties(properties); - } - - - @Test - public void testGetAttributes() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAttributes(); - } - - - @Test - public void testSetAttributes() throws Exception { - UiResourceDataTransfer testSubject; - List attributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAttributes(attributes); - } - - - @Test - public void testGetInterfaces() throws Exception { - UiResourceDataTransfer testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInterfaces(); - } - - - @Test - public void testSetInterfaces() throws Exception { - UiResourceDataTransfer testSubject; - Map interfaces = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInterfaces(interfaces); - } - - - @Test - public void testGetDefaultCapabilities() throws Exception { - UiResourceDataTransfer testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDefaultCapabilities(); - } - - - @Test - public void testSetDefaultCapabilities() throws Exception { - UiResourceDataTransfer testSubject; - List defaultCapabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDefaultCapabilities(defaultCapabilities); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceMetadataTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceMetadataTest.java deleted file mode 100644 index eb5ccff438..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiResourceMetadataTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import java.util.List; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; - - -public class UiResourceMetadataTest { - - private UiResourceMetadata createTestSubject() { - return new UiResourceMetadata(null, null, new ResourceMetadataDataDefinition()); - } - - - @Test - public void testGetDerivedFrom() throws Exception { - UiResourceMetadata testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedFrom(); - } - - - @Test - public void testSetDerivedFrom() throws Exception { - UiResourceMetadata testSubject; - List derivedFrom = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedFrom(derivedFrom); - } - - - @Test - public void testGetVendorName() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getVendorName(); - } - - - @Test - public void testSetVendorName() throws Exception { - UiResourceMetadata testSubject; - String vendorName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setVendorName(vendorName); - } - - - @Test - public void testGetVendorRelease() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getVendorRelease(); - } - - - @Test - public void testSetVendorRelease() throws Exception { - UiResourceMetadata testSubject; - String vendorRelease = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setVendorRelease(vendorRelease); - } - - - @Test - public void testGetResourceVendorModelNumber() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResourceVendorModelNumber(); - } - - - @Test - public void testSetResourceVendorModelNumber() throws Exception { - UiResourceMetadata testSubject; - String resourceVendorModelNumber = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setResourceVendorModelNumber(resourceVendorModelNumber); - } - - - @Test - public void testGetResourceType() throws Exception { - UiResourceMetadata testSubject; - ResourceTypeEnum result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResourceType(); - } - - - @Test - public void testSetResourceType() throws Exception { - UiResourceMetadata testSubject; - ResourceTypeEnum resourceType = null; - - // default test - testSubject = createTestSubject(); - testSubject.setResourceType(resourceType); - } - - - @Test - public void testGetIsAbstract() throws Exception { - UiResourceMetadata testSubject; - Boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getIsAbstract(); - } - - - @Test - public void testSetIsAbstract() throws Exception { - UiResourceMetadata testSubject; - Boolean isAbstract = null; - - // default test - testSubject = createTestSubject(); - testSubject.setIsAbstract(isAbstract); - } - - - @Test - public void testGetCost() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCost(); - } - - - @Test - public void testSetCost() throws Exception { - UiResourceMetadata testSubject; - String cost = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCost(cost); - } - - - @Test - public void testGetLicenseType() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLicenseType(); - } - - - @Test - public void testSetLicenseType() throws Exception { - UiResourceMetadata testSubject; - String licenseType = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLicenseType(licenseType); - } - - - @Test - public void testGetToscaResourceName() throws Exception { - UiResourceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaResourceName(); - } - - - @Test - public void testSetToscaResourceName() throws Exception { - UiResourceMetadata testSubject; - String toscaResourceName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaResourceName(toscaResourceName); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransferTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransferTest.java deleted file mode 100644 index 3bb5aa10b0..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransferTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.model.ArtifactDefinition; - - -public class UiServiceDataTransferTest { - - private UiServiceDataTransfer createTestSubject() { - return new UiServiceDataTransfer(); - } - - - @Test - public void testGetMetadata() throws Exception { - UiServiceDataTransfer testSubject; - UiServiceMetadata result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMetadata(); - } - - - @Test - public void testSetMetadata() throws Exception { - UiServiceDataTransfer testSubject; - UiServiceMetadata metadata = null; - - // default test - testSubject = createTestSubject(); - testSubject.setMetadata(metadata); - } - - - @Test - public void testGetServiceApiArtifacts() throws Exception { - UiServiceDataTransfer testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceApiArtifacts(); - } - - - @Test - public void testSetServiceApiArtifacts() throws Exception { - UiServiceDataTransfer testSubject; - Map serviceApiArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceApiArtifacts(serviceApiArtifacts); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceMetadataTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceMetadataTest.java deleted file mode 100644 index 712053c2f6..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/ui/model/UiServiceMetadataTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.openecomp.sdc.be.ui.model; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; - - -public class UiServiceMetadataTest { - - private UiServiceMetadata createTestSubject() { - return new UiServiceMetadata(null, new ServiceMetadataDataDefinition()); - } - - - @Test - public void testGetDistributionStatus() throws Exception { - UiServiceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDistributionStatus(); - } - - - @Test - public void testSetDistributionStatus() throws Exception { - UiServiceMetadata testSubject; - String distributionStatus = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDistributionStatus(distributionStatus); - } - - - @Test - public void testGetEcompGeneratedNaming() throws Exception { - UiServiceMetadata testSubject; - Boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getEcompGeneratedNaming(); - } - - - @Test - public void testSetEcompGeneratedNaming() throws Exception { - UiServiceMetadata testSubject; - Boolean ecompGeneratedNaming = null; - - // default test - testSubject = createTestSubject(); - testSubject.setEcompGeneratedNaming(ecompGeneratedNaming); - } - - - @Test - public void testGetNamingPolicy() throws Exception { - UiServiceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNamingPolicy(); - } - - - @Test - public void testSetNamingPolicy() throws Exception { - UiServiceMetadata testSubject; - String namingPolicy = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNamingPolicy(namingPolicy); - } - - - @Test - public void testGetServiceType() throws Exception { - UiServiceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceType(); - } - - - @Test - public void testSetServiceType() throws Exception { - UiServiceMetadata testSubject; - String serviceType = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceType(serviceType); - } - - - @Test - public void testGetServiceRole() throws Exception { - UiServiceMetadata testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceRole(); - } - - - @Test - public void testSetServiceRole() throws Exception { - UiServiceMetadata testSubject; - String serviceRole = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceRole(serviceRole); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/FactoryUtilsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/FactoryUtilsTest.java index 53ed77638c..14918be887 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/FactoryUtilsTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/FactoryUtilsTest.java @@ -1,21 +1,11 @@ package org.openecomp.sdc.be.unittests.utils; -import java.util.List; - import org.junit.Test; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.resources.data.*; + +import java.util.List; public class FactoryUtilsTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/ModelConfDependentTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/ModelConfDependentTest.java index 2135b668e6..c25fb451ca 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/ModelConfDependentTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/unittests/utils/ModelConfDependentTest.java @@ -3,7 +3,7 @@ package org.openecomp.sdc.be.unittests.utils; import org.junit.BeforeClass; import org.openecomp.sdc.common.test.BaseConfDependent; -public class ModelConfDependentTest extends BaseConfDependent { +public abstract class ModelConfDependentTest extends BaseConfDependent { @BeforeClass public static void setupBeforeClass() { componentName = "catalog-model"; -- cgit 1.2.3-korg