diff options
Diffstat (limited to 'catalog-model/src/test/java/org/openecomp/sdc/be/model/operations')
18 files changed, 4632 insertions, 3809 deletions
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<UploadArtifactInfo> artifactList = new ArrayList<UploadArtifactInfo>(); - for (int i = 0; i < 2; i++) { - UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/", ArtifactTypeEnum.PUPPET, "This is Description"); - artifactList.add(artifactInfo); - } - ArrayList<String> 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<UploadArtifactInfo> 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<String> 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<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); - assertEquals("add informational artifact version : " + artifactInfo.getArtifactVersion(), "1", artifactInfo.getArtifactVersion()); + Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterDelete.isRight()); - Either<Service, StorageOperationStatus> service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); - Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts(); - for (Map.Entry<String, ArtifactDefinition> 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<Service, StorageOperationStatus> serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); - Either<List<ArtifactData>, 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<ArtifactDefinition, StorageOperationStatus> 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, StorageOperationStatus> service = toscaOperationFacade.getToscaFullElement(serviceId); - assertTrue(service.isLeft()); - - Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts(); - for (Map.Entry<String, ArtifactDefinition> 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<Service, StorageOperationStatus> serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); - - Either<List<ArtifactData>, 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<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNode.isLeft()); - - Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - assertTrue(removeArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - assertTrue(artifactAfterDelete.isRight()); - - Either<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either<HeatParameterData, TitanOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); - assertTrue(updateArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either<ArtifactData, TitanOperationStatus> 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<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either<HeatParameterData, TitanOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); - assertTrue(updateArifact.isLeft()); - - ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either<ArtifactData, TitanOperationStatus> 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<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterDelete.isLeft()); - - Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); - removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - 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<String, Object> props = new HashMap<String, Object>(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); - Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); - assertTrue(createRelation.isLeft()); - - List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition parameter = heatParameters.get(0); - HeatParameterData parameterData = new HeatParameterData(parameter); - Either<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> heatParametersUpdated = new ArrayList<HeatParameterDefinition>(); - heatParamUpdate.setCurrentValue("55"); - heatParametersUpdated.add(heatParamUpdate); - atifactToUpdate.setListHeatParameters(heatParametersUpdated); - - Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactData, TitanOperationStatus> 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<HeatParameterData, TitanOperationStatus> 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<ArtifactData, TitanOperationStatus> 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<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters(); - assertNotNull(heatParametersAfterUpdate); - assertTrue(heatParametersAfterUpdate.size() == 1); - HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); - assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); - Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); - assertTrue(parameterNodeAfterUpdate.isLeft()); - - // delete new artifact - Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactData, TitanOperationStatus> 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<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactDefinition.setListHeatParameters(heatParams); - - Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); - assertTrue(artifact.isLeft()); - return artifact.left().value(); - } - - private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { - 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<Service, StorageOperationStatus> 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<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setIcon("images/my.png"); - List<String> tags = new ArrayList<String>(); - 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<ResourceMetadataData, TitanOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertEquals(artifactNoParams.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() + .getArtifactVersion()); + + Either<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertEquals(artifactWithHeat.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() + .getArtifactVersion()); + + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); + removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + 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<String, Object> props = new HashMap<>(); + props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); + Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); + assertTrue(createRelation.isLeft()); + + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters(); + assertNotNull(heatParameters); + assertEquals(1, heatParameters.size()); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> heatParametersUpdated = new ArrayList<>(); + heatParamUpdate.setCurrentValue("55"); + heatParametersUpdated.add(heatParamUpdate); + atifactToUpdate.setListHeatParameters(heatParametersUpdated); + + Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactData, TitanOperationStatus> origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(origArtifact.isLeft()); + ArtifactData origArtifactData = origArtifact.left().value(); + assertEquals(artifactWithHeat.getArtifactVersion(), origArtifactData.getArtifactDataDefinition() + .getArtifactVersion()); + + Either<HeatParameterData, TitanOperationStatus> 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<ArtifactData, TitanOperationStatus> 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<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters(); + assertNotNull(heatParametersAfterUpdate); + assertEquals(1, heatParametersAfterUpdate.size()); + HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); + assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterUpdate.isLeft()); + + // delete new artifact + Either<ArtifactDefinition, StorageOperationStatus> 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<ArtifactData, TitanOperationStatus> 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<HeatParameterDefinition> 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<ArtifactDefinition, StorageOperationStatus> 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<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); + assertTrue(artifact.isLeft()); + return artifact.left().value(); + } + + private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { + 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<Service, StorageOperationStatus> 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<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setIcon("images/my.png"); + List<String> tags = new ArrayList<>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + return service; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(category, 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<ResourceMetadataData, TitanOperationStatus> 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<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); - } + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } - @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<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertTrue("check capability type added", addCapabilityType1.isLeft()); - Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); + compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); - Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); - compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType2 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertTrue("check capability type failed", addCapabilityType2.isRight()); + assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION, addCapabilityType2.right().value()); - Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + assertEquals("check capability type parent not exist", StorageOperationStatus.NOT_FOUND, addCapabilityType1.right().value()); + } - Either<CapabilityTypeDefinition, StorageOperationStatus> 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<String, PropertyDefinition> properties = new HashMap<>(); - Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + 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<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true); + assertTrue("check capability type fetched", capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); - CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); - Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true); - assertEquals("check capability type fetched", true, capabilityType.isLeft()); - CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + Map<String, PropertyDefinition> fetchedProps = fetchedCTD.getProperties(); - Map<String, PropertyDefinition> 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<String, PropertyDefinition> properties = new HashMap<>(); - Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + 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<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); - Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId()); + assertTrue("check capability type fetched", capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); - CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); - Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId()); - assertEquals("check capability type fetched", true, capabilityType.isLeft()); - CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + Map<String, PropertyDefinition> fetchedProps = fetchedCTD.getProperties(); - Map<String, PropertyDefinition> fetchedProps = fetchedCTD.getProperties(); + compareProperties(fetchedProps, properties); + } - compareProperties(fetchedProps, properties); - } + private void compareProperties(Map<String, PropertyDefinition> first, Map<String, PropertyDefinition> second) { - private void compareProperties(Map<String, PropertyDefinition> first, Map<String, PropertyDefinition> 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<String, PropertyDefinition> entry : first.entrySet()) { - for (Entry<String, PropertyDefinition> 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<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType("not_exists"); + assertEquals("check not found is returned", StorageOperationStatus.NOT_FOUND, capabilityType.right().value()); - Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityTypeRes = capabilityTypeOperation.updateCapabilityType(updatedType, currType); + assertThat(updateCapabilityTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + } - } + @Test + public void updateCapabilityType_basicFields() { + CapabilityTypeDefinition createdType = createCapabilityTypeDef("type1", "description1"); + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> 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<PropertyConstraint> first, List<PropertyConstraint> 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<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>(); - List<String> range = new ArrayList<String>(); - 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<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); - 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(updatedProp1, prop3)); + + Either<CapabilityTypeDefinition, StorageOperationStatus> updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertTrue(updatedCapabilityTypeRes.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedCapabilityTypeRes.right().value()); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(prop3)); + + Either<CapabilityTypeDefinition, StorageOperationStatus> updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertTrue(updatedCapabilityTypeRes.isRight()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedCapabilityTypeRes.right().value()); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "string"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + CapabilityTypeDefinition updatedCapabilityType = createCapabilityTypeDef(asMap(updatedProp1, prop3)); + + Either<CapabilityTypeDefinition, StorageOperationStatus> updatedCapabilityTypeRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + assertTrue(updatedCapabilityTypeRes.isLeft()); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + Either<CapabilityTypeDefinition, StorageOperationStatus> updateRes = + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + assertThat(updateRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<CapabilityTypeDefinition, StorageOperationStatus> currCapabilityType = capabilityTypeOperation.addCapabilityType(capabilityType1); + + Either<CapabilityTypeDefinition, StorageOperationStatus> result = capabilityTypeOperation.updateCapabilityType(updatedCapabilityType, currCapabilityType.left().value()); + assertThat(result.right().value()).isEqualTo(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY); + + Either<CapabilityTypeDefinition, StorageOperationStatus> 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<String, PropertyDefinition> 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<String, PropertyDefinition> 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<String, PropertyDefinition> asMap(PropertyDefinition ... props) { + return Stream.of(props).collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + } + + private void verifyDerivedFromNodeEqualsToRootCapabilityType(CapabilityTypeDefinition rootCapabilityType, String parentCapabilityId) { + Either<ImmutablePair<CapabilityTypeData, GraphEdge>, 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<PropertyConstraint> first, List<PropertyConstraint> 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<PropertyConstraint> constraints3 = new ArrayList<>(); + List<String> 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<PropertyConstraint> 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<String> artifactTypesCfg = new ArrayList<String>(); - artifactTypesCfg.add("type1"); - artifactTypesCfg.add("type2"); - artifactTypesCfg.add("type3"); - artifactTypesCfg.add("type4"); - configurationManager.getConfiguration().setArtifactTypes(artifactTypesCfg); - Either<List<ArtifactType>, ActionStatus> allArtifactTypes = elementOperation.getAllArtifactTypes(); - assertTrue(allArtifactTypes.isLeft()); - assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); + List<String> artifactTypesCfg = new ArrayList<>(); + artifactTypesCfg.add("type1"); + artifactTypesCfg.add("type2"); + artifactTypesCfg.add("type3"); + artifactTypesCfg.add("type4"); + configurationManager.getConfiguration().setArtifactTypes(artifactTypesCfg); + Either<List<ArtifactType>, 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<CategoryDefinition, ActionStatus> 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<CategoryDefinition, ActionStatus> 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<GroupTypeDefinition> 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<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, false); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); @@ -124,18 +127,64 @@ public class GroupTypeOperationTest extends ModelTestBase { } @Test + public void groupTypeWithCapabilityAndPropsButCapTypeWithoutProps() { + getOrCreateRootGroupTypeNode(); + + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(null); + Either<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<PropertyDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<String, PropertyDefinition> 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<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<PropertyDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); GroupTypeData groupTypeNode = extractVal(groupTypeResult); - Either<Edge, TitanOperationStatus> edgeCapTypeResult = titanDao.getEdgeByNodes(groupTypeNode, capabilityTypeNode, GraphEdgeLabels.GROUP_TYPE_CAPABILITY_TYPE); - validate(edgeCapTypeResult); + Either<GroupTypeDefinition, StorageOperationStatus> groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); + assertTrue(groupTypeDefResult.isLeft()); + GroupTypeDefinition groupTypeDefinitionRetrieved = groupTypeDefResult.left().value(); + assertNotNull(groupTypeDefinitionRetrieved); + Map<String, CapabilityDefinition> 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<Edge, TitanOperationStatus> 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<String, PropertyDefinition> capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<PropertyDefinition> 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<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true); + assertTrue("check group type added", addGroupTypeResult.isLeft()); + compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); + + Either<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); + GroupTypeData groupTypeNode = extractVal(groupTypeResult); + + Either<GroupTypeDefinition, StorageOperationStatus> groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); + assertTrue(groupTypeDefResult.isLeft()); + GroupTypeDefinition groupTypeDefinitionRetrieved = groupTypeDefResult.left().value(); + assertNotNull(groupTypeDefinitionRetrieved); + Map<String, CapabilityDefinition> 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<String, PropertyDefinition> capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> 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<String, PropertyDefinition> capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<String, CapabilityDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<String, PropertyDefinition> capTypeProperties = new HashMap<>(); + capTypeProperties.put("vfc_instance_group_reference", property); + CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); + Either<CapabilityTypeData, TitanOperationStatus> 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<String, CapabilityDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<String, CapabilityDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<PropertyDefinition> properties = singletonList( buildProperty("network_collection_type", "l2-network", "network collection type, defined with default value")); groupTypeDefinition.setProperties(properties ); Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.updateGroupType(groupTypeDefinition, groupTypeDefinition); assertNotNull(upgradeResult); assertTrue(upgradeResult.isRight()); } @@ -240,23 +477,25 @@ public class GroupTypeOperationTest extends ModelTestBase { groupTypeDefinition.setVersion("1.0"); Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, true); - assertEquals("check group type added", true, addGroupTypeResult.isLeft()); + Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, false); + assertTrue("check group type added", addGroupTypeResult.isLeft()); Either<GroupTypeData, TitanOperationStatus> 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<String, PropertyDefinition> 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<String, PropertyDefinition> 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<String, PropertyDefinition> 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<CapabilityTypeDefinition, StorageOperationStatus> 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<ComponentInstanceProperty> 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<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanDao.commit(); + } + + + @Test + public void updateGroupType_returnNotFoundErrorIfTryingToUpdateANonExistingType() { + GroupTypeDefinition currType = createGroupTypeDef(); + GroupTypeDefinition updatedType = createGroupTypeDef(); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(createdType); + + GroupTypeDefinition updatedType = createGroupTypeDef("type1", "description2", NULL_STRING); + updatedType.setName("newName"); + updatedType.setIcon("icon"); + groupTypeOperation.updateGroupType(updatedType, currGroupType.left().value()); + + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(groupType); + + PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int"); + PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string"); + GroupTypeDefinition updatedGroupType = createGroupTypeDef(updatedProp1, prop3); + + Either<GroupTypeDefinition, StorageOperationStatus> updatedGroupTypeRetrieved = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertEquals(StorageOperationStatus.MATCH_NOT_FOUND, updatedGroupTypeRetrieved.right().value()); + } + + @Test + public void validateGroupType_FailedDueAttempToCreateGroupTypeWithPropertyWhichTypeIsDifferentFromTypeOfParentPropertyWithTheSameName() { + GroupTypeDefinition rootGroupType = createGroupTypeDef(); + Either<GroupTypeDefinition, StorageOperationStatus> rootGroupTypeRes = groupTypeOperation.addGroupType(rootGroupType); + assertTrue(rootGroupTypeRes.isLeft()); + + PropertyDefinition prop = createSimpleProperty("val1", "prop", "string"); + GroupTypeDefinition groupType1 = createGroupTypeDef("type1", "descr1", rootGroupType.getType(), prop); + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(groupType1); + groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(groupType1); + + Either<GroupTypeDefinition, StorageOperationStatus> updateGroupTypeRes = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertThat(updateGroupTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(groupType1); + + groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + + Either<GroupTypeDefinition, StorageOperationStatus> 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<GroupTypeDefinition, StorageOperationStatus> currGroupType = groupTypeOperation.addGroupType(derivedType1); + groupTypeOperation.addGroupType(groupType1); + + Either<GroupTypeDefinition, StorageOperationStatus> updateResult = groupTypeOperation.updateGroupType(updatedGroupType, currGroupType.left().value()); + assertThat(updateResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + + Either<GroupTypeDefinition, StorageOperationStatus> 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<ImmutablePair<GroupTypeData, GraphEdge>, 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<ImmutablePair<GroupTypeData, GraphEdge>, 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<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); + Either<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); - GraphRelation graphRelation = new GraphRelation(); - Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation); + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> 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<HeatParameterData, TitanOperationStatus> result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + Either<HeatParameterData, TitanOperationStatus> 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<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>(); - parameters.add(property); - parameters.add(property2); + List<HeatParameterDefinition> parameters = new ArrayList<>(); + parameters.add(property); + parameters.add(property2); - HeatParameterData propertyData = new HeatParameterData(property); + HeatParameterData propertyData = new HeatParameterData(property); - Either<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); + Either<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); - GraphRelation graphRelation = new GraphRelation(); - Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation); + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> 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<HeatParameterValueData, TitanOperationStatus> either = Either.left(propertyData); - - GraphRelation graphRelation = new GraphRelation(); - Either<GraphRelation, TitanOperationStatus> 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<HeatParameterValueData, TitanOperationStatus> 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<HeatParameterValueData, TitanOperationStatus> either = Either.left(propertyData); + + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> 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<HeatParameterValueData, TitanOperationStatus> 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<String, Operation> operations = new HashMap<String, Operation>(); - operations.put("Create", op); - interfaceDefinition.setOperations(operations); + Operation op = buildOperationDefinition(); + Map<String, Operation> operations = new HashMap<String, Operation>(); + operations.put("Create", op); + interfaceDefinition.setOperations(operations); - Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - assertTrue(result.isLeft()); - log.debug("{}", result.left().value()); + assertTrue(result.isLeft()); + log.debug("{}", result.left().value()); - Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(rootResource.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); + Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(rootResource.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); - } + } - @Test - public void updateInterfaceToResourceTest() { + @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<String, Operation> operations = new HashMap<String, Operation>(); - operations.put("create", op); - interfaceDefinition.setOperations(operations); + Operation op = buildOperationDefinition(); + Map<String, Operation> operations = new HashMap<String, Operation>(); + operations.put("create", op); + interfaceDefinition.setOperations(operations); - Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either<ResourceMetadataData, TitanOperationStatus> 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<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); - Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); - assertTrue(fetchRootResource.isLeft()); - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "400.0", rootResource.getName(), true, true); + assertTrue(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<Operation, StorageOperationStatus> 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<Operation, StorageOperationStatus> 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<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId()); - assertTrue(getResourceRes.isLeft()); - Resource resourceWithInterface = getResourceRes.left().value(); - Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); - assertNotNull(interfaces); - assertFalse(interfaces.isEmpty()); - InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); - assertNotNull(interfaceDefinition2.getOperations()); - assertFalse(interfaceDefinition2.getOperations().isEmpty()); - Operation operation = interfaceDefinition2.getOperations().get("create"); - assertNotNull(operation); - assertNotNull(operation.getImplementation()); - } + Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); + Operation operation = interfaceDefinition2.getOperations().get("create"); + assertNotNull(operation); + assertNotNull(operation.getImplementation()); + } */ - private void addImplementationToOperation(Operation op) { - ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); - artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); - artifactDataDef.setArtifactName("create_myRoot.sh"); - artifactDataDef.setArtifactLabel("create_myRoot"); - artifactDataDef.setArtifactType("SHELL"); - artifactDataDef.setDescription("good description"); - artifactDataDef.setEsId("esId"); - artifactDataDef.setUniqueId(op.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); - ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); - op.setImplementation(artifactDef); - } - - private InterfaceDefinition buildInterfaceDefinition() { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setType("tosca.interfaces.standard"); - interfaceDefinition.setCreationDate(new Long(101232)); - - 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<CategoryData, TitanOperationStatus> 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<CategoryData, TitanOperationStatus> 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<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable<TitanVertex> vertices = graph.query().vertices(); - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - vertex.remove(); - } - - } - titanGenericDao.commit(); - } - - @Test - public void testAddPolicyType() { - - PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef(); - assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId())); - Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<List<PolicyTypeDefinition>, 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<List<PolicyTypeDefinition>, 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<List<PolicyTypeDefinition>, 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<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanGenericDao.commit(); + } + + @Test + public void testAddPolicyType() { + PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef(); + assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId())); + Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition> 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<PolicyTypeDefinition> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(createdType); - - PolicyTypeDefinition updatedType = createPolicyTypeDef("type1", "description2", NULL_STRING); - policyTypeOperation.updatePolicyType(updatedType, currPolicyType.left().value()); - - Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); - - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); - - policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); - - Either<PolicyTypeDefinition, StorageOperationStatus> 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<ImmutablePair<PolicyTypeData, GraphEdge>, 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<ImmutablePair<PolicyTypeData, GraphEdge>, 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(createdType); + + PolicyTypeDefinition updatedType = createPolicyTypeDef("type1", "description2", NULL_STRING); + updatedType.setName("newName"); + updatedType.setIcon("icon"); + policyTypeOperation.updatePolicyType(updatedType, currPolicyType.left().value()); + + Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); + + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either<PolicyTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1); + + policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value()); + + Either<PolicyTypeDefinition, StorageOperationStatus> 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<ImmutablePair<PolicyTypeData, GraphEdge>, 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<ImmutablePair<PolicyTypeData, GraphEdge>, 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<PropertyConstraint> constraints = - * buildConstraints(); property.setConstraints(constraints); - * - * PropertyData propertyData = new PropertyData(property, - * propertyOperation.convertConstraintsToString(constraints)); - * - * Either<PropertyData, TitanOperationStatus> either = - * Either.left(propertyData); - * //when(propertyDao.create((GraphNeighbourTable)anyObject(), - * eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); - * GraphRelation graphRelation = new GraphRelation(); Either<GraphRelation, - * TitanOperationStatus> 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<PropertyDefinition, StorageOperationStatus> 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<PropertyConstraint> originalConstraints = property.getConstraints(); - * List<PropertyConstraint> 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<String, PropertyDefinition> properties = new HashMap<String, - // PropertyDefinition>(); - // String propName = "myProp"; - // PropertyDefinition property = buildPropertyDefinition(); - // - // List<PropertyConstraint> 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<GraphNode> 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<PropertyConstraint> constraints = buildConstraints(); - List<String> convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints); - assertEquals("constraints size", constraints.size(), convertedStringConstraints.size()); - - List<PropertyConstraint> convertedConstraints = propertyOperation - .convertConstraints(convertedStringConstraints); - assertEquals("check size of constraints", constraints.size(), convertedConstraints.size()); - - Set<String> constraintsClasses = new HashSet<String>(); - 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<PropertyConstraint> buildConstraints() { - List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - List<String> range = new ArrayList<String>(); - 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<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - 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<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - - 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<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - 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<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - - List<PropertyRule> rules = new ArrayList<>(); - PropertyRule propertyRule = new PropertyRule(); - String[] ruleArr = { "node1", ".+", "node3" }; - List<String> 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<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); - - List<PropertyRule> rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); - propertyRule1.setRule(rule1); - propertyRule1.setValue("88"); - - PropertyRule propertyRule2 = new PropertyRule(); - String[] ruleArr2 = { "node1", "node2", "node3" }; - List<String> 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<PropertyConstraint> constraints = buildConstraints(); property.setConstraints(constraints); + * + * PropertyData propertyData = new PropertyData(property, propertyOperation.convertConstraintsToString(constraints)); + * + * Either<PropertyData, TitanOperationStatus> either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation = + * new GraphRelation(); Either<GraphRelation, TitanOperationStatus> 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<PropertyDefinition, StorageOperationStatus> 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<PropertyConstraint> originalConstraints = property.getConstraints(); List<PropertyConstraint> 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<String, PropertyDefinition> properties = new HashMap<String, + // PropertyDefinition>(); + // String propName = "myProp"; + // PropertyDefinition property = buildPropertyDefinition(); + // + // List<PropertyConstraint> 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<GraphNode> 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<PropertyConstraint> constraints = buildConstraints(); + List<String> convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints); + assertEquals("constraints size", constraints.size(), convertedStringConstraints.size()); + + List<PropertyConstraint> convertedConstraints = propertyOperation.convertConstraints(convertedStringConstraints); + assertEquals("check size of constraints", constraints.size(), convertedConstraints.size()); + + Set<String> 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<PropertyConstraint> buildConstraints() { + List<PropertyConstraint> constraints = new ArrayList<>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + List<String> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule = new PropertyRule(); + String[] ruleArr = { "node1", ".+", "node3" }; + List<String> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); + + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); - List<PropertyRule> rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List<String> 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<String> 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<PropertyRule> rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node3" }; + List<String> 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<PropertyRule> rules3 = new ArrayList<>(); - PropertyRule propertyRule3 = new PropertyRule(); - String[] ruleArr3 = { "node2", "node3" }; - List<String> 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<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); - @Test - public void findPropertyValueBestMatchDefaultValueNotChanged() { + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); - String propertyUniqueId = "x1"; - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setValue("v1"); - instanceProperty.setDefaultValue("vv1"); - List<String> path = new ArrayList<>(); - path.add("node1"); - path.add("node2"); - path.add("node3"); - instanceProperty.setPath(path); - - Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); - ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); - instanceProperty1.setValue("v1node1"); + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); - List<PropertyRule> rules = new ArrayList<>(); - PropertyRule propertyRule1 = new PropertyRule(); - String[] ruleArr1 = { "node1", "node2", ".+" }; - List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); - propertyRule1.setRule(rule1); - propertyRule1.setValue("88"); + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); - PropertyRule propertyRule2 = new PropertyRule(); - String[] ruleArr2 = { "node1", "node2", "node3" }; - List<String> 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<PropertyRule> rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node333" }; + List<String> rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); + propertyRule3.setRule(rule3); + propertyRule3.setValue("77"); + rules3.add(propertyRule3); - List<PropertyRule> rules3 = new ArrayList<>(); - PropertyRule propertyRule3 = new PropertyRule(); - String[] ruleArr3 = { "node2", "node333" }; - List<String> 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<String, PropertyDefinition> properties = null; - String resourceId = ""; - Map<String, DataTypeDefinition> 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<String, PropertyDefinition> properties = null; - Map<String, DataTypeDefinition> 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<PropertyData, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<String> expectedIds = new ArrayList<String>(); - 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<GraphPropertyEnum, Object> 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<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); - - Either<GraphVertex, TitanOperationStatus> 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<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); - String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); - cat.setUniqueId(catId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - cat.setMetadataProperties(metadataProperties); - cat.updateMetadataJsonWithCurrentMetadataProperties(); - - Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); - - assertTrue(catRes.isLeft()); - } - - 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<CategoryDefinition> categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - service.setCategories(categories); - - service.setComponentType(ComponentTypeEnum.SERVICE); - Either<TopologyTemplate, StorageOperationStatus> createRes = topologyTemplateOperation.createTopologyTemplate(service); - assertTrue(createRes.isLeft()); - - Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); - assertTrue(getNodeTyeRes.isLeft()); - - // serviceVertex = getNodeTyeRes.left().value(); - - return getNodeTyeRes.left().value(); - } - - private <T extends ToscaDataDefinition> 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<CategoryDefinition> categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List<SubCategoryDefinition> subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List<String> derivedFrom = new ArrayList<>(); - derivedFrom.add("root"); - vf.setDerivedFrom(derivedFrom); - - vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); - assertTrue(createVFRes.isLeft()); - - Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - assertTrue(getNodeTyeRes.isLeft()); - - vfVertex = getNodeTyeRes.left().value(); - - List<PropertyDataDefinition> 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<String, MapDataDefinition> capProps = new HashMap(); - capProps.put("capName", dataToCreate); - - Either<GraphVertex, StorageOperationStatus> res = nodeTypeOperation.assosiateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); - - // exportGraphMl(titanDao.getGraph().left().value()); - - List<String> 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<CategoryDefinition> categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List<SubCategoryDefinition> subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List<String> derivedFrom = new ArrayList<>(); - vf.setDerivedFrom(derivedFrom); - - Map<String, PropertyDataDefinition> 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<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); - assertTrue(createVFRes.isLeft()); - - Either<GraphVertex, TitanOperationStatus> 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<GraphPropertyEnum, Object> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, TitanOperationStatus> getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); - assertTrue(getOwnerRes.isLeft()); - - } - - public void verifyInCatalogData(int expected, List<String> expectedIds) { - - Either<List<CatalogComponent>, StorageOperationStatus> highestResourcesRes = topologyTemplateOperation.getElementCatalogData(); - assertTrue(highestResourcesRes.isLeft()); - List<CatalogComponent> 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<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable<TitanVertex> vertices = graph.query().vertices(); - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - vertex.remove(); - } - } - titanDao.commit(); - } + 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<ToscaElement, StorageOperationStatus> 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<String> 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<GraphPropertyEnum, Object> 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<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); + + Either<GraphVertex, TitanOperationStatus> 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<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); + + assertTrue(catRes.isLeft()); + } + + 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<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + service.setCategories(categories); + + service.setComponentType(ComponentTypeEnum.SERVICE); + Either<TopologyTemplate, StorageOperationStatus> createRes = topologyTemplateOperation.createTopologyTemplate(service); + assertTrue(createRes.isLeft()); + + Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); + assertTrue(getNodeTyeRes.isLeft()); + + // serviceVertex = getNodeTyeRes.left().value(); + + return getNodeTyeRes.left().value(); + } + + private <T extends ToscaDataDefinition> 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<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List<SubCategoryDefinition> subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List<String> derivedFrom = new ArrayList<>(); + derivedFrom.add("root"); + vf.setDerivedFrom(derivedFrom); + + vf.setComponentType(ComponentTypeEnum.RESOURCE); + Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); + assertTrue(createVFRes.isLeft()); + + Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + assertTrue(getNodeTyeRes.isLeft()); + + vfVertex = getNodeTyeRes.left().value(); + + List<PropertyDataDefinition> 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<String, MapDataDefinition> capProps = new HashMap(); + capProps.put("capName", dataToCreate); + + Either<GraphVertex, StorageOperationStatus> res = nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); + + // exportGraphMl(titanDao.getGraph().left().value()); + + List<String> 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<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List<SubCategoryDefinition> subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List<String> derivedFrom = new ArrayList<>(); + vf.setDerivedFrom(derivedFrom); + + Map<String, PropertyDataDefinition> 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<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); + assertTrue(createVFRes.isLeft()); + + Either<GraphVertex, TitanOperationStatus> 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<GraphPropertyEnum, Object> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, TitanOperationStatus> getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); + assertTrue(getOwnerRes.isLeft()); + + } + + public void verifyInCatalogData(int expected, List<String> expectedIds) { + + Either<List<CatalogComponent>, StorageOperationStatus> highestResourcesRes = topologyTemplateOperation.getElementCatalogData(true, null); + assertTrue(highestResourcesRes.isLeft()); + List<CatalogComponent> 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<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } } 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<User, StorageOperationStatus> 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<Edge> edgesList = new ArrayList<Edge>(); - - Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); - - Either<User, ActionStatus> 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<Edge> edgesList = new ArrayList<Edge>(); - edgesList.add(getEmptyEdgeImpl()); - - Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); - - Either<User, ActionStatus> 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 <V> Property<V> property(String key, V value) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void remove() { - // TODO Auto-generated method stub - - } - - @Override - public Iterator<Vertex> vertices(Direction direction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <V> Iterator<Property<V>> 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<UserData, TitanOperationStatus> 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<Either<UserData, TitanOperationStatus>>() { - public Either<UserData, TitanOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - UserData retValue = (UserData) args[0]; - Either<UserData, TitanOperationStatus> result = Either.left(retValue); - return result; - } - - }).when(titanGenericDao).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); - } - - private static void mockTitanDelete() { - doAnswer(new Answer<Either<UserData, TitanOperationStatus>>() { - public Either<UserData, TitanOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - UserData retValue = (UserData) args[0]; - Either<UserData, TitanOperationStatus> 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<User, StorageOperationStatus> 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<Edge> edgesList = new ArrayList<>(); + + Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either<User, ActionStatus> 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<Edge> edgesList = new ArrayList<>(); + edgesList.add(getEmptyEdgeImpl()); + + Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either<User, ActionStatus> 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<Edge> 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<List<Edge>, StorageOperationStatus> result = userAdminOperation.getUserPendingTasksList(user, new HashMap<>()); + assertThat(result.isLeft()).isTrue(); + List<Edge> 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 <V> TitanVertexProperty<V> property(String s, V v, Object... objects) { + return null; + } + + @Override + public <V> VertexProperty<V> 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 <V> TitanVertexProperty<V> property(VertexProperty.Cardinality cardinality, String s, V v, Object... objects) { + return null; + } + + @Override + public Iterator<Edge> edges(Direction direction, String... strings) { + return null; + } + + @Override + public Iterator<Vertex> 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<? extends TitanVertexQuery> query() { + return null; + } + + @Override + public boolean isModified() { + return false; + } + + @Override + public TitanTransaction graph() { + return null; + } + + @Override + public void remove() { + + } + + @Override + public <V> 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 <V> Iterator<VertexProperty<V>> 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<Vertex> 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 <V> Property<V> property(String s, V v) { + return null; + } + + @Override + public void remove() { + + } + + @Override + public <V> Iterator<Property<V>> 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 <V> Property<V> property(String key, V value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void remove() { + // TODO Auto-generated method stub + + } + + @Override + public Iterator<Vertex> vertices(Direction direction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <V> Iterator<Property<V>> 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<UserData, TitanOperationStatus> eitherUserData = Either.left(userData); + when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData); + return userData; + } + + private static void mockTitanUpdate() { + doAnswer((Answer<Either<UserData, TitanOperationStatus>>) 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<Either<UserData, TitanOperationStatus>>) 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - allDataTypes.put("integer", getPrimitiveDataType("integer")); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + allDataTypes.put("integer", getPrimitiveDataType("integer")); - DataTypeDefinition fromIntegerType = buildDerivedFromIntegerType(); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate("", fromIntegerType, - allDataTypes); + DataTypeDefinition fromIntegerType = buildDerivedFromIntegerType(); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - allDataTypes.put("myinteger", derivedFromIntegerType); + DataTypeDefinition derivedFromIntegerType = buildDerivedFromIntegerType(); + Map<String, DataTypeDefinition> 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<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, personDataType, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String> strList = Arrays.asList(strArr); + String[] strArr = {}; + List<String> strList = Arrays.asList(strArr); - // Check empty list - Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check empty list + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); - log.debug(json); + String json = gson.toJson(credential); + log.debug(json); - Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check list is NULL - Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check list is NULL + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, null, true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - // Check user is empty - Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "", true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + // Check user is empty + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "", true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); - log.debug(json); + String json = gson.toJson(credential); + log.debug(json); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - json += "fdfd"; + json += "fdfd"; - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 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<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); - City mycity = new City("", null); + // Check user is null + Credential credential = new Credential("protcol<br>>", 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<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - // Check user is null - Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 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<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertFalse("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<br>dcc" }; - List<String> strList = Arrays.asList(strArr); + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); - Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); - City mycity = new City("myadd<br><<br>", 55); - credential.setMycity(mycity); + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); - String json = gson.toJson(credential); + String json = gson.toJson(credential); - Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); - ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, - allDataTypes); - assertTrue("check valid value", validate.right.booleanValue()); + ImmutablePair<JsonElement, Boolean> 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<String,Integer> check OK - Map<String, Integer> 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<String,Integer> check OK + Map<String, Integer> 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<String,Boolean> check OK - Map<String, Boolean> 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<String,Boolean> check OK + Map<String, Boolean> 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<String, String> map_1 = new HashMap<>(); - Map<String, String> resMap_1 = new HashMap<>(); - - // 1 - check Spaces eliminated + html square brackets eliminated - map_1.put("key1", "<b>test</b>"); - 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - - MyFile myFile = new MyFile(); - myFile.setAge(88); - Map<String, City> attributes = new HashMap<>(); - attributes.put("key1", new City("address1<br>", 11)); - attributes.put("key2", new City("address2<br>", 22)); - myFile.setAttributes(attributes); - - String str = gson.toJson(myFile); - log.debug(str); - - ImmutablePair<JsonElement, Boolean> 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<String, String> map_1 = new HashMap<>(); + Map<String, String> resMap_1 = new HashMap<>(); + + // 1 - check Spaces eliminated + html square brackets eliminated + map_1.put("key1", "<b>test</b>"); + 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<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + MyFile myFile = new MyFile(); + myFile.setAge(88); + Map<String, City> attributes = new HashMap<>(); + attributes.put("key1", new City("address1<br>", 11)); + attributes.put("key2", new City("address2<br>", 22)); + myFile.setAttributes(attributes); + + String str = gson.toJson(myFile); + log.debug(str); + + ImmutablePair<JsonElement, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); - Gson gson = new Gson(); - // Happy Scenarios - Map<String, Object> map_1 = new HashMap<>(); + Gson gson = new Gson(); + // Happy Scenarios + Map<String, Object> 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<br>dcc" }; - List<String> strList = Arrays.asList(strArr); - Credential credential1 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, - strList); - City mycity1 = new City("myadd<br><<br>", 55); - credential1.setMycity(mycity1); + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd<br><<br>", 55); + credential1.setMycity(mycity1); - Credential credential2 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, - strList); - City mycity2 = new City("myadd<br><<br>", 66); - credential2.setMycity(mycity2); + Credential credential2 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd<br><<br>", 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<String, Boolean> convert = mapConverter.convertWithErrorResult(str, "credential", allDataTypes); + MapConverter mapConverter = new MapConverter(); + Either<String, Boolean> 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<Map<String, Credential>>() { - }.getType(); + Type type = new TypeToken<Map<String, Credential>>() { + }.getType(); - Map<String, Credential> fromJson = gson.fromJson(convertedValue, type); + Map<String, Credential> 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<String> 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<String> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map<String, DataTypeDefinition> 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<Object> list = buildListOf2CredentialObjects(); + List<Object> 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<String, Boolean> convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); + Either<String, Boolean> 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<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); - DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); - DataTypeDefinition cityDataType = buildCityDataType(); - allDataTypes.put("city", cityDataType); - allDataTypes.put("credential", credentialDataTypeDefinition); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); - Gson gson = new Gson(); - // Happy Scenarios - List<Object> list = buildListOf2CredentialObjects(); + Gson gson = new Gson(); + // Happy Scenarios + List<Object> 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<Object> buildListOf2CredentialObjects() { - List<Object> list = new ArrayList<>(); + private List<Object> buildListOf2CredentialObjects() { + List<Object> list = new ArrayList<>(); - String[] strArr = { "aaa", "bbb", "c<br>dcc" }; - List<String> strList = Arrays.asList(strArr); - Credential credential1 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, - strList); - City mycity1 = new City("myadd<br><<br>", 55); - credential1.setMycity(mycity1); - - Credential credential2 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, - strList); - City mycity2 = new City("myadd<br><<br>", 66); - credential2.setMycity(mycity2); + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd<br><<br>", 55); + credential1.setMycity(mycity1); + + Credential credential2 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd<br><<br>", 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<List<Credential>>() { - }.getType(); - - List<Credential> 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<String> 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<PropertyDefinition> 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<PropertyDefinition> 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<PropertyDefinition> 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<PropertyDefinition> 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<List<Credential>>() { + }.getType(); + + List<Credential> 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<String> 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<PropertyDefinition> 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<PropertyDefinition> 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<PropertyDefinition> 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<PropertyDefinition> 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<String, City> attributes; - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } + Map<String, City> attributes; + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } - public Map<String, City> getAttributes() { - return attributes; - } + public Map<String, City> getAttributes() { + return attributes; + } - public void setAttributes(Map<String, City> attributes) { - this.attributes = attributes; - } + public void setAttributes(Map<String, City> 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<String, String> keys; - String user; - Boolean isMandatory; - List<String> mylist; - City mycity; + String protocol; + Integer sum; + String token_type; + String token; + Map<String, String> keys; + String user; + Boolean isMandatory; + List<String> mylist; + City mycity; - public Credential(String protocol, Integer sum, String token_type, String token, Map<String, String> keys, - String user, Boolean isMandatory, List<String> 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<String, String> getKeys() { - return keys; - } - - public void setKeys(Map<String, String> 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<String> getMylist() { - return mylist; - } - - public void setMylist(List<String> 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<String, String> keys, + String user, Boolean isMandatory, List<String> 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<String, String> getKeys() { + return keys; + } + + public void setKeys(Map<String, String> 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<String> getMylist() { + return mylist; + } + + public void setMylist(List<String> 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<CategoryData, TitanOperationStatus> 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<CategoryData, TitanOperationStatus> 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<CategoryData, TitanOperationStatus> 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<CategoryData, TitanOperationStatus> 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<TitanVertex> vertices = graph.query().vertices(); + Iterable<TitanVertex> vertices = graph.query().vertices(); - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - } + if (vertices != null) { + Iterator<TitanVertex> 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<TitanEdge> vertices = graph.query().edges(); + public void printGraphEdges(TitanGraph graph) { + Iterable<TitanEdge> vertices = graph.query().edges(); - if (vertices != null) { - Iterator<TitanEdge> iterator = vertices.iterator(); - while (iterator.hasNext()) { - Edge edge = iterator.next(); + if (vertices != null) { + Iterator<TitanEdge> 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<TitanVertex> 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<TitanVertex> vertices = graph.query().vertices(); - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); - Map<String, Object> properties = getProperties(vertex); + Map<String, Object> 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<TitanEdge> edges = graph.query().edges(); + Iterable<TitanEdge> edges = graph.query().edges(); - if (edges != null) { - Iterator<TitanEdge> iterator = edges.iterator(); - while (iterator.hasNext()) { - Edge edge = iterator.next(); + if (edges != null) { + Iterator<TitanEdge> 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<String, Object> properties) { + private String buildEdgeRecord(String fromUid, String toUid, String edgeLabel, Map<String, Object> 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<String, Object> properties) { + private String generateStringFromProperties(Map<String, Object> properties) { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - if (properties != null) { - for (Entry<String, Object> entry : properties.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue().toString(); - builder.append(key + "=" + value + "__"); - } - } - return builder.toString(); + if (properties != null) { + for (Entry<String, Object> 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<String, Object> properties) { + private String buildNodeRecord(String uid, String color, Map<String, Object> 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<String, Object> entry1 : properties.entrySet()) { - String key = entry1.getKey(); - int keyLength = key.length(); - if (keyLength > maxKeyLength) { - maxKeyLength = keyLength; - } - } - - boolean first = true; - for (Entry<String, Object> 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<String, Object> 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<TitanVertex> vertices = graph.query().vertices(); - - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - counter++; - } - } - return counter; - } - - public Set<String> getVerticesSet(TitanGraph titanGraph) { - - Set<String> set = new HashSet<String>(); - - Iterable<TitanVertex> vertices = titanGraph.query().vertices(); - - if (vertices != null) { - Iterator<TitanVertex> iterator = vertices.iterator(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - - Map<String, Object> properties = getProperties(vertex); - - String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); - - String uid = getNodeIdByLabel(nodeLabel, properties); - - set.add(uid); - } - } - - return set; - - } - - public Map<String, Object> getProperties(Element element) { - - Map<String, Object> result = null; - - if (element.keys() != null && element.keys().size() > 0) { - Map<String, Property> propertyMap = ElementHelper.propertyMap(element, - element.keys().toArray(new String[element.keys().size()])); - result = new HashMap<String, Object>(); - - for (Entry<String, Property> 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<String, Object> entry1 : properties.entrySet()) { + String key = entry1.getKey(); + int keyLength = key.length(); + if (keyLength > maxKeyLength) { + maxKeyLength = keyLength; + } + } + + boolean first = true; + for (Entry<String, Object> 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<String, Object> 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<TitanVertex> vertices = graph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + counter++; + } + } + return counter; + } + + public Set<String> getVerticesSet(TitanGraph titanGraph) { + + Set<String> set = new HashSet<>(); + + Iterable<TitanVertex> vertices = titanGraph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map<String, Object> properties = getProperties(vertex); + + String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + + String uid = getNodeIdByLabel(nodeLabel, properties); + + set.add(uid); + } + } + + return set; + + } + + public Map<String, Object> getProperties(Element element) { + + Map<String, Object> result = null; + + if (element.keys() != null && element.keys().size() > 0) { + Map<String, Property> propertyMap = ElementHelper.propertyMap(element, + element.keys().toArray(new String[element.keys().size()])); + result = new HashMap<>(); + + for (Entry<String, Property> 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"; } |