diff options
Diffstat (limited to 'catalog-be/src/test/java/org/openecomp/sdc/be/components/impl')
23 files changed, 5388 insertions, 3159 deletions
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index c57f2a65af..bebe29f13e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -20,28 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -55,6 +41,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -70,6 +57,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -84,294 +72,359 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; public class ArtifactBusinessLogicTest { - public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - @InjectMocks - private static ArtifactsBusinessLogic artifactBL; - @Mock - private ArtifactOperation artifactOperation; - @Mock - public ComponentsUtils componentsUtils; - @Mock - private IInterfaceLifecycleOperation lifecycleOperation; - @Mock - private IUserAdminOperation userOperation; - @Mock - private IElementOperation elementOperation; - @Mock - private ArtifactCassandraDao artifactCassandraDao; - @Mock - public ToscaOperationFacade toscaOperationFacade; - @Mock - private UserBusinessLogic userBusinessLogic; - @Mock - private NodeTemplateOperation nodeTemplateOperation; - @Mock - private ArtifactsOperations artifactsOperations; - - // public static final InformationDeployedArtifactsBusinessLogic - // informationDeployedArtifactsBusinessLogic = - // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); - - public static final Resource resource = Mockito.mock(Resource.class); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - - private static List<ArtifactType> getAllTypes() { - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); - for (String artifactType : artifactTypesList) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return artifactTypes; - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); - - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); - when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); - - Either<User, ActionStatus> getUserResult = Either.left(USER); - - when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); - - Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); - when(elementOperation.getAllArtifactTypes()).thenReturn(getType); - - when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); - } - - @Test - public void testValidJson() { - ArtifactDefinition ad = createArtifactDef(); - - String jsonArtifact = ""; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - try { - jsonArtifact = mapper.writeValueAsString(ad); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); - assertEquals(ad, afterConvert); - } - - private ArtifactDefinition createArtifactDef() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1.yaml"); - ad.setArtifactLabel("label1"); - ad.setDescription("description"); - ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - return ad; - } - - @Test - public void testInvalidStringGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidNumberGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidGroupTypeWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidTimeoutWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testValidMibAritactsConfiguration() { - Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - } - - @Test - public void testDownloadServiceArtifactByNames() { - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); - esArtifactData.setDataAsArray(payload); - Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); - when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); - List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); - serviceList.add(service); - Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); - when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); - Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = - artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - assertTrue(downloadServiceArtifactByNamesRes.isLeft()); - assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); - } - - @Test - public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) - .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) - .build(); - - Resource component = new Resource(); - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); - assertTrue(heatEnvPlaceHolder.isLeft()); - assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); - } - - @Test - public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { - HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); - HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); - HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(heatParam1) - .addHeatParam(heatParam2) - .addHeatParam(heatParam3) - .build(); - - Resource component = new Resource(); - - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); - - assertTrue(heatEnvPlaceHolder.isLeft()); - ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); - List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); - assertEquals(listHeatParameters.size(), 3); - verifyHeatParam(listHeatParameters.get(0), heatParam1); - verifyHeatParam(listHeatParameters.get(1), heatParam2); - verifyHeatParam(listHeatParameters.get(2), heatParam3); - } - - private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { - assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); - assertNull(heatEnvParam.getCurrentValue()); - } + public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + private final static String RESOURCE_INSTANCE_NAME = "Service-111"; + private final static String INSTANCE_ID = "S-123-444-ghghghg"; + + private final static String ARTIFACT_NAME = "service-Myservice-template.yml"; + private final static String ARTIFACT_LABEL = "assettoscatemplate"; + private final static String ES_ARTIFACT_ID = "123123dfgdfgd0"; + private final static byte[] PAYLOAD = "some payload".getBytes(); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + private static ArtifactsBusinessLogic artifactBL; + @Mock + private ArtifactOperation artifactOperation; + @Mock + public ComponentsUtils componentsUtils; + @Mock + private IInterfaceLifecycleOperation lifecycleOperation; + @Mock + private IUserAdminOperation userOperation; + @Mock + private IElementOperation elementOperation; + @Mock + private ArtifactCassandraDao artifactCassandraDao; + @Mock + public ToscaOperationFacade toscaOperationFacade; + @Mock + private UserBusinessLogic userBusinessLogic; + @Mock + private NodeTemplateOperation nodeTemplateOperation; + @Mock + private ArtifactsOperations artifactsOperations; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + TitanDao titanDao; + + // public static final InformationDeployedArtifactsBusinessLogic + // informationDeployedArtifactsBusinessLogic = + // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); + + public static final Resource resource = Mockito.mock(Resource.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + + private static List<ArtifactType> getAllTypes() { + List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); + List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return artifactTypes; + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); + when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); + + Either<User, ActionStatus> getUserResult = Either.left(USER); + + when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); + + Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); + when(elementOperation.getAllArtifactTypes()).thenReturn(getType); + + when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = ""; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try { + jsonArtifact = mapper.writeValueAsString(ad); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); + assertEquals(ad, afterConvert); + } + + private ArtifactDefinition createArtifactDef() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1.yaml"); + ad.setArtifactLabel("label1"); + ad.setDescription("description"); + ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + return ad; + } + + @Test + public void testInvalidStringGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidNumberGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidGroupTypeWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidTimeoutWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testValidMibAritactsConfiguration() { + Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + } + + @Test + public void testDownloadServiceArtifactByNames() { + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); + + ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); + esArtifactData.setDataAsArray(payload); + Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); + when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); + List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); + serviceList.add(service); + Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); + when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); + Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = + artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + assertTrue(downloadServiceArtifactByNamesRes.isLeft()); + assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); + } + + @Test + public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) + .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) + .build(); + + Resource component = new Resource(); + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); + assertTrue(heatEnvPlaceHolder.isLeft()); + assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); + } + + @Test + public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { + HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); + HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); + HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(heatParam1) + .addHeatParam(heatParam2) + .addHeatParam(heatParam3) + .build(); + + Resource component = new Resource(); + + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); + + assertTrue(heatEnvPlaceHolder.isLeft()); + ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); + List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); + assertEquals(listHeatParameters.size(), 3); + verifyHeatParam(listHeatParameters.get(0), heatParam1); + verifyHeatParam(listHeatParameters.get(1), heatParam2); + verifyHeatParam(listHeatParameters.get(2), heatParam3); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, true); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndNotInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, false); + verify(titanDao, times(1)).commit(); + } + + private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { + assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); + assertNull(heatEnvParam.getCurrentValue()); + } // @Test - // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ - // ArtifactDefinition createArtifactDef = createArtifactDef(); - // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); - // - // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL - // - // assertTrue(validateResult.isLeft()); - // ArtifactDefinition validatedArtifact = validateResult.left().value(); - // - // assertEquals(createArtifactDef.getArtifactGroupType(), - // validatedArtifact.getArtifactGroupType()); - // assertEquals(new Integer(0), validatedArtifact.getTimeout()); - // assertFalse(validatedArtifact.getMandatory()); - // assertFalse(validatedArtifact.getServiceApi()); - // - // } + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL + // + // assertTrue(validateResult.isLeft()); + // ArtifactDefinition validatedArtifact = validateResult.left().value(); + // + // assertEquals(createArtifactDef.getArtifactGroupType(), + // validatedArtifact.getArtifactGroupType()); + // assertEquals(new Integer(0), validatedArtifact.getTimeout()); + // assertFalse(validatedArtifact.getMandatory()); + // assertFalse(validatedArtifact.getServiceApi()); + // + // } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java index 8ad9bf80b2..18af7a035a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.Collections; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,12 +28,21 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + public class ArtifactResolverTest { private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); - private Service service, noArtifactsService; - private Resource resource, noArtifactsResource; - private ComponentInstance componentInstance, noArtifactsInstance; + private Service service; + private Service noArtifactsService; + private Resource resource; + private Resource noArtifactsResource; + private ComponentInstance componentInstance; + private ComponentInstance noArtifactsInstance; @Before public void setUp() throws Exception { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java index 41835a6cdc..9b2fb3773b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -20,17 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,58 +36,68 @@ import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.common.util.CapabilityTypeNameEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class CapabilityTypeImportManagerTest { - @InjectMocks - private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + @InjectMocks + private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() { - when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { - public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() { + when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { + public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void testCreateCapabilityTypes() throws IOException { - String ymlContent = getCapabilityTypesYml(); - Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void testCreateCapabilityTypes() throws IOException { + String ymlContent = getCapabilityTypesYml(); + Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); - assertTrue(capabilityTypesList.size() == 14); - Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); - for (CapabilityTypeDefinition capType : capabilityTypesList) { - capibilityTypeMap.put(capType.getType(), capType); - } - assertTrue(capabilityTypesList.size() == 14); + List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); + assertTrue(capabilityTypesList.size() == 14); + Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); + for (CapabilityTypeDefinition capType : capabilityTypesList) { + capibilityTypeMap.put(capType.getType(), capType); + } + assertTrue(capabilityTypesList.size() == 14); - for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { - assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); - } + for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { + assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); + } - } + } - private String getCapabilityTypesYml() throws IOException { - Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getCapabilityTypesYml() throws IOException { + Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java index 2c83c60fc6..8a07e26161 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -45,64 +36,66 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; - -import fj.data.Either; - -public class CategoriesImportManagerTest { - @InjectMocks - static CategoriesImportManager importManager = new CategoriesImportManager(); - public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - static Logger log = Mockito.spy(Logger.class); - private static SubCategoryDefinition subcategory; - - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId("123"); - - when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { - Object[] args = invocation.getArguments(); - CategoryDefinition category = (CategoryDefinition) args[0]; - category.setUniqueId("123"); - Either<CategoryDefinition, ActionStatus> ans = Either.left(category); - return ans; - }); - when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { - public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); - Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); - return ans; - } - - }); - - // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void importCategoriesTest() throws IOException { - String ymlContent = getYmlContent(); - Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; - } +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } +public class CategoriesImportManagerTest { + @InjectMocks + static CategoriesImportManager importManager = new CategoriesImportManager(); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + private static SubCategoryDefinition subcategory; + + @BeforeClass + public static void beforeClass() throws IOException { + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId("123"); + + when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { + Object[] args = invocation.getArguments(); + CategoryDefinition category = (CategoryDefinition) args[0]; + category.setUniqueId("123"); + Either<CategoryDefinition, ActionStatus> ans = Either.left(category); + return ans; + }); + when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { + public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); + Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); + return ans; + } + + }); + + // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importCategoriesTest() throws IOException { + String ymlContent = getYmlContent(); + Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 65f7ac46b6..a5d05eff2c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -1,23 +1,22 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiPredicate; - +import fj.data.Either; import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; @@ -32,214 +31,354 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiPredicate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceBusinessLogic class */ public class ComponentInstanceBusinessLogicTest { - - private final static String USER_ID = "jh0003"; - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - private static ToscaOperationFacade toscaOperationFacade; - private static UserBusinessLogic userAdmin; - - private static ComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentInstanceBusinessLogic resourceBusinessLogic; - private static User user; - private static Component service; - private static Component resource; - private static ComponentInstance toInstance; - private static ComponentInstance fromInstance; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - @BeforeClass - public static void setup() { - createMocks(); - setMocks(); - stubMethods(); - createComponents(); - } - - @Test - public void testGetRelationByIdSuccess(){ - getServiceRelationByIdSuccess(service); - getServiceRelationByIdSuccess(resource); - } - - @Test - public void testGetRelationByIdUserValidationFailure(){ - getServiceRelationByIdUserValidationFailure(service); - getServiceRelationByIdUserValidationFailure(resource); - } - - @Test - public void testGetRelationByIdComponentNotFoundFailure(){ - getRelationByIdComponentNotFoundFailure(service); - getRelationByIdComponentNotFoundFailure(resource); - } - - @SuppressWarnings("unchecked") - private void getServiceRelationByIdSuccess(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); - when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); - - Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); - when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isLeft()); - } - - private void getServiceRelationByIdUserValidationFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private void getRelationByIdComponentNotFoundFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private static void createMocks() { - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - userAdmin = Mockito.mock(UserBusinessLogic.class); - user = Mockito.mock(User.class); - } - - private static void setMocks() { - serviceBusinessLogic = new ServiceComponentInstanceBusinessLogic(); - serviceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - serviceBusinessLogic.setUserAdmin(userAdmin); - serviceBusinessLogic.setComponentsUtils(componentsUtils); - - resourceBusinessLogic = new VFComponentInstanceBusinessLogic(); - resourceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - resourceBusinessLogic.setUserAdmin(userAdmin); - resourceBusinessLogic.setComponentsUtils(componentsUtils); - } - - private static void stubMethods() { - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); - } - - private static void createComponents() { - createRelation(); - createInstances(); - createService(); - createResource(); - } - - private static void createResource() { - resource = new Resource(); - resource.setUniqueId(COMPONENT_ID); - resource.setComponentInstancesRelations(Lists.newArrayList(relation)); - resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - resource.setCapabilities(toInstance.getCapabilities()); - resource.setRequirements(fromInstance.getRequirements()); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - } - - - private static void createService() { - service = new Service(); - service.setUniqueId(COMPONENT_ID); - service.setComponentInstancesRelations(Lists.newArrayList(relation)); - service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - service.setCapabilities(toInstance.getCapabilities()); - service.setRequirements(fromInstance.getRequirements()); - service.setComponentType(ComponentTypeEnum.SERVICE); - } - - - private static void createInstances() { - toInstance = new ComponentInstance(); - toInstance.setUniqueId(TO_INSTANCE_ID); - - fromInstance = new ComponentInstance(); - fromInstance.setUniqueId(FROM_INSTANCE_ID); - - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - - Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); - capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); - - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - - - Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); - requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); - - toInstance.setCapabilities(capabilities); - fromInstance.setRequirements(requirements); - } - - - private static void createRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } + + private final static String USER_ID = "jh0003"; + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + private static ToscaOperationFacade toscaOperationFacade; + private static UserBusinessLogic userAdmin; + + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ForwardingPathOperation forwardingPathOperation; + private static User user; + private static UserValidations userValidations; + private static Component service; + private static Component resource; + private static ComponentInstance toInstance; + private static ComponentInstance fromInstance; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + @BeforeClass + public static void setup() { + createMocks(); + setMocks(); + stubMethods(); + createComponents(); + + } + + @Before + public void init(){ + MockitoAnnotations.initMocks(this); + } + @Test + public void testGetRelationByIdSuccess(){ + getServiceRelationByIdSuccess(service); + getServiceRelationByIdSuccess(resource); + } + + @Test + public void testGetRelationByIdUserValidationFailure(){ + getServiceRelationByIdUserValidationFailure(service); + getServiceRelationByIdUserValidationFailure(resource); + } + + @Test + public void testGetRelationByIdComponentNotFoundFailure(){ + getRelationByIdComponentNotFoundFailure(service); + getRelationByIdComponentNotFoundFailure(resource); + } + + + + + @Test + public void testForwardingPathOnVersionChange(){ + getforwardingPathOnVersionChange(); + } + + private void getforwardingPathOnVersionChange(){ + String containerComponentParam="services"; + String containerComponentID="121-cont"; + String componentInstanceID="121-cont-1-comp"; + Service component=new Service(); + Map<String, ForwardingPathDataDefinition> forwardingPaths = generateForwardingPath(componentInstanceID); + + //Add existing componentInstance to component + List<ComponentInstance> componentInstanceList=new ArrayList<>(); + ComponentInstance oldComponentInstance=new ComponentInstance(); + oldComponentInstance.setName("OLD_COMP_INSTANCE"); + oldComponentInstance.setUniqueId(componentInstanceID); + oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,"1-comp"); + componentInstanceList.add(oldComponentInstance); + component.setComponentInstances(componentInstanceList); + component.setForwardingPaths(forwardingPaths); + + List<ComponentInstance> componentInstanceListNew=new ArrayList<>(); + ComponentInstance newComponentInstance=new ComponentInstance(); + String new_Comp_UID="2-comp"; + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,new_Comp_UID); + newComponentInstance.setUniqueId(new_Comp_UID); + componentInstanceListNew.add(newComponentInstance); + Component component2=new Service(); + component2.setComponentInstances(componentInstanceListNew); + + //Mock for getting component + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE)); + //Mock for getting component for componentInstance + when(toscaOperationFacade.getToscaFullElement(eq("1-comp"))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaFullElement(eq(new_Comp_UID))).thenReturn(Either.left(component2)); + + Either<Set<String>, ResponseFormat> resultOp = componentInstanceBusinessLogic.forwardingPathOnVersionChange + (containerComponentParam,containerComponentID,componentInstanceID,newComponentInstance); + Assert.assertEquals(1,resultOp.left().value().size()); + Assert.assertEquals("FP-ID-1",resultOp.left().value().iterator().next()); + + } + + + @Test + public void testDeleteForwardingPathsWhenComponentinstanceDeleted(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.left(new ComponentInstance())); + Assert.assertTrue(responseFormatEither.isLeft()); + + } + + @Test + public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.right(new ResponseFormat())); + Assert.assertTrue(responseFormatEither.isRight()); + + } + + + private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode , String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol("protocol"); + forwardingPath.setDestinationPortNumber("port"); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(fromNode, toNode, + "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } + + + + private Map<String, ForwardingPathDataDefinition> generateForwardingPath(String componentInstanceID) { + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + forwardingPath.setUniqueId("FP-ID-1"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = + new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY", + "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("1122", forwardingPath); + return forwardingPaths; + } + + @SuppressWarnings("unchecked") + private void getServiceRelationByIdSuccess(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); + when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); + + Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); + when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isLeft()); + } + + private void getServiceRelationByIdUserValidationFailure(Component component){ + //Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); + //when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.right(new ResponseFormat(404))); + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private void getRelationByIdComponentNotFoundFailure(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private static void createMocks() { + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + userAdmin = Mockito.mock(UserBusinessLogic.class); + user = Mockito.mock(User.class); + userValidations = Mockito.mock(UserValidations.class); + forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + } + + private static void setMocks() { + componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic(); + componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); + componentInstanceBusinessLogic.setUserAdmin(userAdmin); + componentInstanceBusinessLogic.setComponentsUtils(componentsUtils); + componentInstanceBusinessLogic.setUserValidations(userValidations); + componentInstanceBusinessLogic.setForwardingPathOperation(forwardingPathOperation); + } + + private static void stubMethods() { + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.left(user)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); + } + + private static void createComponents() { + createRelation(); + createInstances(); + createService(); + createResource(); + } + + private static void createResource() { + resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setComponentInstancesRelations(Lists.newArrayList(relation)); + resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + resource.setCapabilities(toInstance.getCapabilities()); + resource.setRequirements(fromInstance.getRequirements()); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + } + + + private static void createService() { + service = new Service(); + service.setUniqueId(COMPONENT_ID); + service.setComponentInstancesRelations(Lists.newArrayList(relation)); + service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + service.setCapabilities(toInstance.getCapabilities()); + service.setRequirements(fromInstance.getRequirements()); + service.setComponentType(ComponentTypeEnum.SERVICE); + } + + + private static void createInstances() { + toInstance = new ComponentInstance(); + toInstance.setUniqueId(TO_INSTANCE_ID); + + fromInstance = new ComponentInstance(); + fromInstance.setUniqueId(FROM_INSTANCE_ID); + + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); + + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + + + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); + + toInstance.setCapabilities(capabilities); + fromInstance.setRequirements(requirements); + } + + + private static void createRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java new file mode 100644 index 0000000000..a9245d2897 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java @@ -0,0 +1,402 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESC_ERROR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_500; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentsUtilsTest { + + private static User modifier = new User(); + private Component service = new Service(); + private Resource resource = new Resource(); + + @Mock + private AuditingManager manager; + + @Mock + private ResponseFormat responseFormat; + + @Captor + private ArgumentCaptor<AuditBaseEventFactory> factoryCaptor; + + @InjectMocks + private static ComponentsUtils utils; + + @BeforeClass + public static void setUpClass() { + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + @Before + public void setUp() { + ThreadLocalsHolder.setUuid(REQUEST_ID); + utils = new ComponentsUtils(manager); + } + + @Test + public void auditComponentWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + } + + @Test + public void auditComponentWhenAllParamsPassedAndMostFromComponent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + + } + + @Test + public void auditComponentDistStateWithoutArtDataCommentAndDid() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build()); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), + STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, false, false, true); + } + + @Test + public void auditComponentWhenError() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE, + ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(PREV_RESOURCE_STATE).version(PREV_RESOURCE_VERSION).artifactUuid(ARTIFACT_UUID).build()); + verifyResourceAdminEvent(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName(), STATUS_500, DESC_ERROR, + service.getComponentType().getValue(), false, true, false, false, false, false); + } + + @Test + public void auditComponentWhenCompIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE, + RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT); + verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + true, false, false, false, true, false); + } + + @Test + public void auditComponentAdmin() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setName(RESOURCE_NAME); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponentAdmin(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType()); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + resource.setToscaResourceName(TOSCA_NODE_TYPE); + utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .build(), + ARTIFACT_UUID, ARTIFACT_DATA); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(), + false, true, true, true, false, false); + } + + @Test + public void auditResourceWithoutPrevFields() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + utils.auditResource(responseFormat, modifier, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + verifyResourceAdminEvent(AuditingActionEnum.UPDATE_RESOURCE_METADATA.getName(), STATUS_500, DESC_ERROR, resource.getResourceType().name(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenResourceIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditResource(responseFormat, modifier, RESOURCE_NAME, AuditingActionEnum.CHECKOUT_RESOURCE); + verifyResourceAdminEvent(AuditingActionEnum.CHECKOUT_RESOURCE.getName(), STATUS_500, DESC_ERROR, ComponentTypeEnum.RESOURCE.getValue(), + true, false, false, false, false, false); + } + + @Test + public void auditUserAdminEvent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + User userAfter = new User(); + userAfter.setFirstName(USER_FIRST_NAME); + userAfter.setUserId(USER_ID); + userAfter.setLastName(USER_LAST_NAME); + userAfter.setRole(TESTER_USER_ROLE); + userAfter.setEmail(USER_EMAIL); + + utils.auditAdminUserAction(AuditingActionEnum.ADD_USER, modifier, null, userAfter, responseFormat); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + UserAdminEvent event = (UserAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.ADD_USER.getName()); + assertThat(event.getUserBefore()).isNull(); + assertThat(event.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + } + + @Test + public void auditEcompOpEnvEvent() { + utils.auditEnvironmentEngine(AuditingActionEnum.CREATE_ENVIRONMENT, OP_ENV_ID, OP_ENV_TYPE, OP_ENV_ACTION, OP_ENV_NAME, TENANT_CONTEXT); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + EcompOperationalEnvironmentEvent event = (EcompOperationalEnvironmentEvent)factory.getDbEvent(); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + assertThat(event.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(event.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(event.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(event.getOperationalEnvironmentAction()).isEqualTo(OP_ENV_ACTION); + assertThat(event.getTenantContext()).isEqualTo(TENANT_CONTEXT); + } + + @Test + public void auditDistrDownloadEvent(){ + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + utils.auditDistributionDownload(responseFormat, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + DistributionDownloadEvent event = (DistributionDownloadEvent)factory.getDbEvent(); + assertThat(event.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + } + + private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull, + boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided, + boolean isDistStatusProvided) { + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(status); + assertThat(event.getDesc()).isEqualTo(desc); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(action); + assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME); + + if (isComponentNull) { + assertThat(event.getServiceInstanceId()).isNull(); + assertThat(event.getCurrState()).isNull(); + assertThat(event.getCurrVersion()).isNull(); + assertThat(event.getInvariantUUID()).isNull(); + assertThat(event.getResourceType()).isEqualTo(resourceType); + } + else { + assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(event.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(event.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + } + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(event.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } + else { + assertThat(event.getToscaNodeType()).isEmpty(); + } + if (isPrevStateAndVersionSet) { + assertThat(event.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(event.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getPrevState()).isNull(); + assertThat(event.getPrevVersion()).isNull(); + assertThat(event.getPrevArtifactUUID()).isNull(); + } + if (isCurrFieldsProvided) { + assertThat(event.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getCurrArtifactUUID()).isNull(); + } + if (isArtDataProvided) { + assertThat(event.getArtifactData()).isEqualTo(ARTIFACT_DATA); + if (resourceType.equals(ResourceTypeEnum.VFC.name())) { + assertThat(event.getDid()).isNull(); + } + else { + assertThat(event.getDid()).isEqualTo(DIST_ID); + } + } + else { + assertThat(event.getArtifactData()).isNull(); + assertThat(event.getDid()).isNull(); + } + if (isCommentProvided) { + assertThat(event.getComment()).isEqualTo(COMMENT); + } + else { + assertThat(event.getComment()).isEmpty(); + } + if (isDistStatusProvided) { + assertThat(event.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(event.getDprevStatus()).isEqualTo(DPREV_STATUS); + } + else { + assertThat(event.getDcurrStatus()).isNull(); + assertThat(event.getDprevStatus()).isNull(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java index 4f1f929382..7b37b0e96a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -20,7 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; import java.util.ArrayList; import java.util.HashMap; @@ -29,126 +35,120 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; +import static org.junit.Assert.assertTrue; public class CompositionBusinessLogicTest { - CompositionBusinessLogic compBl = new CompositionBusinessLogic(); - - @Test - public void testBuildSpiralPatternPositioningForComponentInstances() { - int instancesNum = 10; - Resource createVF = FactoryUtils.createVF(); - for (int i = 0; i < instancesNum; i++) { - FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); - } - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); - assertTrue(componentInstances.size() == instancesNum); - // Verify Spiral Pattern - ImmutablePair<Double, Double> key; - key = new ImmutablePair<>(0D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-2D, -1D); - assertTrue(componentInstances.containsKey(key)); - } - - @Test - public void testGetCpsConnectedToVFC() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); - - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - assertTrue(cpsConnectedToVFC.size() == 1); - assertTrue(cpsConnectedToVFC.containsKey(vfc)); - Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); - assertTrue(cps.size() == 3); - cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); - - } - - @Test - public void testBuildCirclePatternForCps() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); - componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); - compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); - assertTrue(componentInstLocations.size() == 4); - - Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); - // Verify that all cps are located at different positions - assertTrue(cpsLocations.size() == 3); - Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); - // Verify that all cps are at the same distance from center - assertTrue(distances.size() == 1); - - } - - /** - * Adds 4 instances to the vf.<br> - * vfc instance and 3 cps instances.<br> - * the cp instances are connected to the vfc instance.<br> - * - * @param allComponentInstances - * @param createVF - * @return vfc instance - */ - private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { - ComponentInstance vfc = FactoryUtils.createResourceInstance(); - vfc.setOriginType(OriginTypeEnum.VFC); - FactoryUtils.addComponentInstanceToVF(createVF, vfc); - allComponentInstances.add(vfc); - - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - return vfc; - } - - private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { - List<RequirementCapabilityRelDef> allRelations; - if (createVF.getComponentInstancesRelations() != null) { - allRelations = createVF.getComponentInstancesRelations(); - } else { - allRelations = new ArrayList<>(); - createVF.setComponentInstancesRelations(allRelations); - } - ComponentInstance cp1 = FactoryUtils.createResourceInstance(); - cp1.setOriginType(OriginTypeEnum.CP); - addVfcCpRelation(vfc, cp1, allRelations); - FactoryUtils.addComponentInstanceToVF(createVF, cp1); - allComponentInstances.add(cp1); - } - - private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { - RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); - rel.setToNode(vfc.getComponentUid()); - rel.setFromNode(cp.getComponentUid()); - allRelations.add(rel); - } + CompositionBusinessLogic compBl = new CompositionBusinessLogic(); + + @Test + public void testBuildSpiralPatternPositioningForComponentInstances() { + int instancesNum = 10; + Resource createVF = FactoryUtils.createVF(); + for (int i = 0; i < instancesNum; i++) { + FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); + } + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); + assertTrue(componentInstances.size() == instancesNum); + // Verify Spiral Pattern + ImmutablePair<Double, Double> key; + key = new ImmutablePair<>(0D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-2D, -1D); + assertTrue(componentInstances.containsKey(key)); + } + + @Test + public void testGetCpsConnectedToVFC() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); + + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + assertTrue(cpsConnectedToVFC.size() == 1); + assertTrue(cpsConnectedToVFC.containsKey(vfc)); + Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); + assertTrue(cps.size() == 3); + cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); + + } + + @Test + public void testBuildCirclePatternForCps() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); + componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); + compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); + assertTrue(componentInstLocations.size() == 4); + + Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); + // Verify that all cps are located at different positions + assertTrue(cpsLocations.size() == 3); + Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); + // Verify that all cps are at the same distance from center + assertTrue(distances.size() == 1); + + } + + /** + * Adds 4 instances to the vf.<br> + * vfc instance and 3 cps instances.<br> + * the cp instances are connected to the vfc instance.<br> + * + * @param allComponentInstances + * @param createVF + * @return vfc instance + */ + private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { + ComponentInstance vfc = FactoryUtils.createResourceInstance(); + vfc.setOriginType(OriginTypeEnum.VFC); + FactoryUtils.addComponentInstanceToVF(createVF, vfc); + allComponentInstances.add(vfc); + + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + return vfc; + } + + private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { + List<RequirementCapabilityRelDef> allRelations; + if (createVF.getComponentInstancesRelations() != null) { + allRelations = createVF.getComponentInstancesRelations(); + } else { + allRelations = new ArrayList<>(); + createVF.setComponentInstancesRelations(allRelations); + } + ComponentInstance cp1 = FactoryUtils.createResourceInstance(); + cp1.setOriginType(OriginTypeEnum.CP); + addVfcCpRelation(vfc, cp1, allRelations); + FactoryUtils.addComponentInstanceToVF(createVF, cp1); + allComponentInstances.add(cp1); + } + + private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + rel.setToNode(vfc.getComponentUid()); + rel.setFromNode(cp.getComponentUid()); + allRelations.add(rel); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java index 50ad990560..d91fa7995b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -20,18 +20,18 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Arrays; - import org.junit.Assert; import org.junit.Test; +import java.util.Arrays; + public class CsarValidationUtilsTest { - private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; - private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; + private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; + private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; - @Test - public void testIsCsarPayloadName() { - Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); - Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); - } + @Test + public void testIsCsarPayloadName() { + Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); + Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java new file mode 100644 index 0000000000..46ee852aa0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +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.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 12/7/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class ElementBLTest { + + private static final String CATAGORY_NAME = "categoryName"; + private static final String CATEGORY_UNIQUE_ID = "catUniqueId"; + private static final String SERVICE_NOT_DELETED_ID = "notDeletedId"; + private static final String DELETED_SERVICE_ID = "deletedId"; + private List<CategoryData> categories = new ArrayList<>(); + private List<ImmutablePair<ServiceMetadataData, GraphEdge>> services = new ArrayList<>(); + private List<ImmutablePair<ResourceMetadataData, GraphEdge>> resources = new ArrayList<>(); + private Service notDeletedService = new Service(); + private Resource notDeletedResource = new Resource(); + + @Mock + private TitanGenericDao titanGenericDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private TitanDao titanDao; + + @InjectMocks + private ElementBusinessLogic elementBusinessLogic; + + @Before + public void setup() { + + initCategoriesList(); + initServicesList(); + initResourceslist(); + + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void initCategoriesList() { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setUniqueId(CATEGORY_UNIQUE_ID); + categories.add(categoryData); + } + + private void initServicesList() { + ServiceMetadataData serviceNotDeleted = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition1 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition1.setIsDeleted(false); + componentMetadataDataDefinition1.setHighestVersion(true); + componentMetadataDataDefinition1.setUniqueId(SERVICE_NOT_DELETED_ID); + serviceNotDeleted.setMetadataDataDefinition(componentMetadataDataDefinition1); + services.add(new ImmutablePair<>(serviceNotDeleted, null)); + + ServiceMetadataData deletedService = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition2 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition2.setIsDeleted(true); + componentMetadataDataDefinition2.setHighestVersion(true); + componentMetadataDataDefinition2.setUniqueId(DELETED_SERVICE_ID); + deletedService.setMetadataDataDefinition(componentMetadataDataDefinition2); + services.add(new ImmutablePair<>(deletedService, null)); + } + + private void initResourceslist() { + ResourceMetadataData notDeletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition3 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition3.setIsDeleted(false); + componentMetadataDataDefinition3.setHighestVersion(true); + componentMetadataDataDefinition3.setUniqueId(SERVICE_NOT_DELETED_ID); + notDeletedResource.setMetadataDataDefinition(componentMetadataDataDefinition3); + resources.add(new ImmutablePair<>(notDeletedResource, null)); + + ResourceMetadataData deletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition4 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition4.setIsDeleted(true); + componentMetadataDataDefinition4.setHighestVersion(true); + componentMetadataDataDefinition4.setUniqueId(DELETED_SERVICE_ID); + deletedResource.setMetadataDataDefinition(componentMetadataDataDefinition4); + resources.add(new ImmutablePair<>(deletedResource, null)); + } + + @Test + public void testFetchElementsByCategoryName_filterDeleted() { + ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class); + + when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) + .thenReturn(Either.left(categories)); + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class)) + .thenReturn(Either.left(services)); + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedService)); + + Either<List<Object>, StorageOperationStatus> elementsByCategoryEither = + elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), + NodeTypeEnum.Service, false, ServiceMetadataData.class, null); + + List<Object> elementsByCategory = elementsByCategoryEither.left().value(); + assertThat(elementsByCategory.get(0)).isSameAs(notDeletedService); + assertThat(elementsByCategory.size()).isEqualTo(1); + verifyCriteriaProperties(criteriaCapture); + } + + private void verifyCriteriaProperties(ArgumentCaptor<Map> propsCapture) { + Map<String, Object> props = propsCapture.getValue(); + assertThat(props.size()).isEqualTo(1); + assertThat(props.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty())).isEqualTo(ValidationUtils.normalizeCategoryName4Uniqueness(CATAGORY_NAME)); + } + + @Test + public void testFetchResourcesBySubcategoryUid_filterDeleted() { + + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)) + .thenReturn(Either.left(resources)); + + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedResource)); + + Either<List<Object>, StorageOperationStatus> resourcesBySubCategoryUidEither = elementBusinessLogic.fetchByCategoryOrSubCategoryUid(CATEGORY_UNIQUE_ID, NodeTypeEnum.ResourceSubcategory, + GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, false, ResourceMetadataData.class, null); + List<Object> resourcesBySubCategoryUid = resourcesBySubCategoryUidEither.left().value(); + assertThat(resourcesBySubCategoryUid.size()).isEqualTo(1); + assertThat(resourcesBySubCategoryUid.get(0)).isSameAs(notDeletedResource); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 5edf448cc2..b65e77c57f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -20,21 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; @@ -46,462 +32,475 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ImportUtilsTest { - @Test - public void testStringTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 4); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof String); - String value = (String) element; - assertTrue(value.equals("stringVal" + count)); - count++; - } - } - - @Test - public void testBooleanTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Boolean); - Boolean value = (Boolean) element; - if (count == 1 || count == 3) { - assertFalse(value); - } else if (count == 2) { - assertTrue(value); - } - - count++; - } - } - - @Test - public void testListTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof List); - - if (count == 1) { - verifyListElement1(element); - } else if (count == 2) { - verifyListElement2(element); - } - - else if (count == 3) { - verifyListElement3(element); - } - count++; - } - } - - @Test - public void testAllTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 5); - int count = 1; - for (Object element : list) { - if (count == 1) { - assertTrue(element instanceof String); - assertTrue(element.equals("tosca.nodes.Root")); - } else if (count == 2) { - assertTrue(element instanceof Map); - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); - Entry<String, Object> elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("mapTestTag")); - assertTrue(elementEntry.getValue().equals("string")); - - elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("required")); - assertTrue(elementEntry.getValue() instanceof Boolean); - assertTrue((Boolean) elementEntry.getValue()); - } - - else if (count == 3) { - assertTrue(element instanceof String); - assertTrue(element.equals("1 MB")); - } - - else if (count == 4) { - assertTrue(element instanceof List); - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - assertTrue(listElement.get(0) instanceof Map); - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("greater_or_equal")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal3")); - } else if (count == 5) { - assertTrue(element instanceof Boolean); - assertFalse((Boolean) element); - } - count++; - } - } - - @Test - public void testMapTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 2); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Map); - - if (count == 1) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("stringTestTag")); - assertTrue(inerElementEntry.getValue().equals("stringVal1")); - - inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("listTestTag")); - assertTrue(inerElementEntry.getValue() instanceof List); - List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); - - assertTrue(innerValue.size() == 3); - - } else if (count == 2) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("type")); - assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); - inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("allTestTag")); - assertTrue(inerElementEntry.getValue() instanceof Boolean); - } - - count++; - } - } - - @Test - public void testCreateFullHeatParameterModuleWithString() { - - testCreateFullHeatParameterModule("string", "default value"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithNumber() { - - testCreateFullHeatParameterModule("number", "777"); - testCreateFullHeatParameterModule("number", "777.23"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithBoolean() { - - testCreateFullHeatParameterModule("boolean", "true"); - testCreateFullHeatParameterModule("boolean", "on"); - testCreateFullHeatParameterModule("boolean", "n"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithList() { - - testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); - - } - - // @Test - // public void testCreateFullHeatParameterModuleWithInvalidType(){ - // - // String name = "fullParameter"; - // String description = "description_text"; - // - // Map<String, Object> parametersMap = new HashMap<String, Object>(); - // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", - // name, description); - // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), - // firstParam); - // - // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = - // ImportUtils.getHeatParameters(parametersMap); - // assertTrue(heatParameters.isRight()); - // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, - // heatParameters.right().value()); - // - // } - - @Test - public void testCreateFullHeatParameterModuleWithMissingType() { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isRight()); - assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); + @Test + public void testStringTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 4); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof String); + String value = (String) element; + assertTrue(value.equals("stringVal" + count)); + count++; + } + } + + @Test + public void testBooleanTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Boolean); + Boolean value = (Boolean) element; + if (count == 1 || count == 3) { + assertFalse(value); + } else if (count == 2) { + assertTrue(value); + } + + count++; + } + } + + @Test + public void testListTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof List); + + if (count == 1) { + verifyListElement1(element); + } else if (count == 2) { + verifyListElement2(element); + } + + else if (count == 3) { + verifyListElement3(element); + } + count++; + } + } + + @Test + public void testAllTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 5); + int count = 1; + for (Object element : list) { + if (count == 1) { + assertTrue(element instanceof String); + assertTrue(element.equals("tosca.nodes.Root")); + } else if (count == 2) { + assertTrue(element instanceof Map); + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); + Entry<String, Object> elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("mapTestTag")); + assertTrue(elementEntry.getValue().equals("string")); + + elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("required")); + assertTrue(elementEntry.getValue() instanceof Boolean); + assertTrue((Boolean) elementEntry.getValue()); + } + + else if (count == 3) { + assertTrue(element instanceof String); + assertTrue(element.equals("1 MB")); + } + + else if (count == 4) { + assertTrue(element instanceof List); + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + assertTrue(listElement.get(0) instanceof Map); + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("greater_or_equal")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal3")); + } else if (count == 5) { + assertTrue(element instanceof Boolean); + assertFalse((Boolean) element); + } + count++; + } + } + + @Test + public void testMapTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 2); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Map); + + if (count == 1) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("stringTestTag")); + assertTrue(inerElementEntry.getValue().equals("stringVal1")); + + inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("listTestTag")); + assertTrue(inerElementEntry.getValue() instanceof List); + List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); + + assertTrue(innerValue.size() == 3); + + } else if (count == 2) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("type")); + assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); + inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("allTestTag")); + assertTrue(inerElementEntry.getValue() instanceof Boolean); + } + + count++; + } + } + + @Test + public void testCreateFullHeatParameterModuleWithString() { + + testCreateFullHeatParameterModule("string", "default value"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithNumber() { + + testCreateFullHeatParameterModule("number", "777"); + testCreateFullHeatParameterModule("number", "777.23"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithBoolean() { + + testCreateFullHeatParameterModule("boolean", "true"); + testCreateFullHeatParameterModule("boolean", "on"); + testCreateFullHeatParameterModule("boolean", "n"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithList() { + + testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); + + } + + // @Test + // public void testCreateFullHeatParameterModuleWithInvalidType(){ + // + // String name = "fullParameter"; + // String description = "description_text"; + // + // Map<String, Object> parametersMap = new HashMap<String, Object>(); + // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", + // name, description); + // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), + // firstParam); + // + // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = + // ImportUtils.getHeatParameters(parametersMap); + // assertTrue(heatParameters.isRight()); + // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, + // heatParameters.right().value()); + // + // } + + @Test + public void testCreateFullHeatParameterModuleWithMissingType() { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isRight()); + assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); - } + } - @Test - public void testCreateFullHeatParameterModuleWithMissingFields() { + @Test + public void testCreateFullHeatParameterModuleWithMissingFields() { - String name = "fullParameter"; + String name = "fullParameter"; - Map<String, Object> parametersMap = new HashMap<String, Object>(); - String type = "number"; - String defValue = "defvalue"; - // default value cannot be empty in heat in case tag exists - Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + Map<String, Object> parametersMap = new HashMap<String, Object>(); + String type = "number"; + String defValue = "defvalue"; + // default value cannot be empty in heat in case tag exists + Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - assertParameter(parameterDefinition, name, type, null, defValue); + assertParameter(parameterDefinition, name, type, null, defValue); - } + } - @Test - public void testGetAttributesFromYml() throws IOException { + @Test + public void testGetAttributesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); - assertTrue(actualAttributes.isLeft()); - Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); - compareAttributes(expectedAttributes, actualAttributes.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + assertTrue(actualAttributes.isLeft()); + Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); + compareAttributes(expectedAttributes, actualAttributes.left().value()); - } + } - @Test - public void testGetPropertiesFromYml() throws IOException { + @Test + public void testGetPropertiesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); - assertTrue(actualProperties.isLeft()); - Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); - compareProperties(expectedProperties, actualProperties.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); + assertTrue(actualProperties.isLeft()); + Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); + compareProperties(expectedProperties, actualProperties.left().value()); - } + } - private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedAttribute; - PropertyDefinition actualAttribute, expectedAttributeModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { + Map<String, Object> singleExpectedAttribute; + PropertyDefinition actualAttribute, expectedAttributeModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { - singleExpectedAttribute = expectedAttribute.getValue(); - assertNotNull(singleExpectedAttribute); - actualAttribute = actual.get(expectedAttribute.getKey()); - assertNotNull(actualAttribute); - actualAttribute.setName(expectedAttribute.getKey().toString()); - expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); - expectedAttributeModel.setName(expectedAttribute.getKey().toString()); + singleExpectedAttribute = expectedAttribute.getValue(); + assertNotNull(singleExpectedAttribute); + actualAttribute = actual.get(expectedAttribute.getKey()); + assertNotNull(actualAttribute); + actualAttribute.setName(expectedAttribute.getKey().toString()); + expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); + expectedAttributeModel.setName(expectedAttribute.getKey().toString()); - assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); - assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); - assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); - assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); - assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); + assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); + assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); + assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); + assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); - compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); + compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); - } + } - } + } - private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedProperty; - PropertyDefinition actualProperty, expectedPropertyModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { + Map<String, Object> singleExpectedProperty; + PropertyDefinition actualProperty, expectedPropertyModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { - singleExpectedProperty = expectedProperty.getValue(); - assertNotNull(singleExpectedProperty); - actualProperty = actual.get(expectedProperty.getKey()); - assertNotNull(actualProperty); - actualProperty.setName(expectedProperty.getKey().toString()); - expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); - expectedPropertyModel.setName(expectedProperty.getKey().toString()); + singleExpectedProperty = expectedProperty.getValue(); + assertNotNull(singleExpectedProperty); + actualProperty = actual.get(expectedProperty.getKey()); + assertNotNull(actualProperty); + actualProperty.setName(expectedProperty.getKey().toString()); + expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); + expectedPropertyModel.setName(expectedProperty.getKey().toString()); - assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); - assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); - assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); - assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); - assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); + assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); + assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); + assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); + assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); + assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); - compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); - } + } - } + } - private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { + private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { - if (expected == null && actual == null) { - return; - } - PropertyDataDefinition actualPropertySchema = actual.getProperty(); - PropertyDataDefinition expectedPropertySchema = expected.getProperty(); - assertNotNull(actualPropertySchema); - assertNotNull(expectedPropertySchema); - assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); - assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); - - } + if (expected == null && actual == null) { + return; + } + PropertyDataDefinition actualPropertySchema = actual.getProperty(); + PropertyDataDefinition expectedPropertySchema = expected.getProperty(); + assertNotNull(actualPropertySchema); + assertNotNull(expectedPropertySchema); + assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); + assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); + + } - private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { - - Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); - assertTrue(toscaExpectedElements.isLeft()); - - return toscaExpectedElements.left().value(); - - } - - private void testCreateFullHeatParameterModule(String type, Object defaultVal) { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - - assertParameter(parameterDefinition, name, type, description, defaultVal); - - } - - private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { - Map<String, Object> firstParam = new HashMap<String, Object>(); - Map<String, Object> valuesMap = new HashMap<String, Object>(); - - valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); - valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); - valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); - - firstParam.put(name, valuesMap); - return firstParam; - } - - private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { - assertEquals(name, parameterDefinition.getName()); - assertEquals(description, parameterDefinition.getDescription()); - assertEquals(type, parameterDefinition.getType()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); - } - - private void verifyListElement3(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("type")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - private void verifyListElement2(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue() instanceof List); - } - - private void verifyListElement1(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 3); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("2 MB")); - - innerElement = (Map<String, String>) listElement.get(2); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - public static String loadFileNameToJsonString(String fileName) throws IOException { - String sourceDir = "src/test/resources/normativeTypes"; - java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); - byte[] fileContent = Files.readAllBytes(filePath); - String content = new String(fileContent); - return content; - } - - private static Object loadJsonFromFile(String fileName) throws IOException { - String content = loadFileNameToJsonString(fileName); - Object load = new Yaml().load(content); - return load; - } + private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { + + Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); + assertTrue(toscaExpectedElements.isLeft()); + + return toscaExpectedElements.left().value(); + + } + + private void testCreateFullHeatParameterModule(String type, Object defaultVal) { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, description, defaultVal); + + } + + private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { + Map<String, Object> firstParam = new HashMap<String, Object>(); + Map<String, Object> valuesMap = new HashMap<String, Object>(); + + valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); + valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); + valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); + + firstParam.put(name, valuesMap); + return firstParam; + } + + private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { + assertEquals(name, parameterDefinition.getName()); + assertEquals(description, parameterDefinition.getDescription()); + assertEquals(type, parameterDefinition.getType()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); + } + + private void verifyListElement3(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("type")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + private void verifyListElement2(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue() instanceof List); + } + + private void verifyListElement1(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 3); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("2 MB")); + + innerElement = (Map<String, String>) listElement.get(2); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + public static String loadFileNameToJsonString(String fileName) throws IOException { + String sourceDir = "src/test/resources/normativeTypes"; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static Object loadJsonFromFile(String fileName) throws IOException { + String content = loadFileNameToJsonString(fileName); + Object load = new Yaml().load(content); + return load; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index ac4d37ef76..068f04aae2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; @@ -46,7 +39,17 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class InputsBusinessLogicTest { @@ -63,6 +66,9 @@ public class InputsBusinessLogicTest { @Mock private ToscaOperationFacade toscaOperationFacadeMock; + @Mock + private UserValidations userValidations; + @InjectMocks private InputsBusinessLogic testInstance; @@ -83,13 +89,13 @@ public class InputsBusinessLogicTest { instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput)); instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput())); service.setComponentInstancesInputs(instanceInputMap); - - Mockito.when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); } @Test public void getComponentInstanceInputs_ComponentInstanceNotExist() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, "nonExisting"); assertTrue(componentInstanceInputs.isRight()); Mockito.verify(componentsUtilsMock).getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); @@ -115,13 +121,13 @@ public class InputsBusinessLogicTest { @Test public void getComponentInstanceInputs() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals("inputId", componentInstanceInputs.left().value().get(0).getInputId()); } private void getComponents_emptyInputs(Service service) { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals(Collections.emptyList(), componentInstanceInputs.left().value()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java index 8109e36be1..e726f608f5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -42,51 +34,54 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; -public class InterfaceLifecycleTypeImportManagerTest { +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - @InjectMocks - private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); +public class InterfaceLifecycleTypeImportManagerTest { - static Logger log = Mockito.spy(Logger.class); + @InjectMocks + private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { - public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() throws IOException { + when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { + public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void importLiecycleTest() throws IOException { - String ymlContent = getYmlContent(); - Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void importLiecycleTest() throws IOException { + String ymlContent = getYmlContent(); + Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - } + } - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java new file mode 100644 index 0000000000..9aca92010e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java @@ -0,0 +1,493 @@ +package org.openecomp.sdc.be.components.impl; + + +import fj.data.Either; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyBusinessLogicTest { + + @InjectMocks + private PolicyBusinessLogic businessLogic; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private UserValidations userValidations; + @Mock + private TitanDao titanDao; + @Mock + private ApplicationDataTypeCache dataTypeCache; + @Mock + private PropertyOperation propertyOperation; + + private final static String COMPONENT_ID = "componentId"; + private final static String COMPONENT_NAME = "componentName"; + private final static String POLICY_TYPE_NAME = "policyTypeName"; + private final static String POLICY_ID = "policyId"; + private final static String INVALID_POLICY_ID = "invalidPolicyId"; + private final static String POLICY_NAME = "policyName"; + private final static String OTHER_POLICY_NAME = "otherPolicyName"; + private final static String USER_ID = "jh0003"; + private final static String UNIQUE_ID_EXSISTS = "uniqueIdExists"; + private final static String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists"; + private final static String FAKE_TYPE = "fakeType"; + private final static String COMPONENT_INSTANCE_TYPE = "component_Instances"; + private final static String GROUP_TYPE = "GROUPS"; + + + + + private final String CREATE_POLICY = "create Policy"; + + private final static User user = buildUser(); + private final static PolicyDefinition policy = buildPolicy(POLICY_NAME); + private final static PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME); + private final static Resource resource = buildResource(); + private final static PolicyTypeDefinition policyType = buildPolicyType(); + + private static Either<User, ResponseFormat> userSuccessEither; + private static Either<Component, StorageOperationStatus> componentSuccessEither; + private static Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeSuccessEither; + private static Either<PolicyDefinition, StorageOperationStatus> policySuccessEither; + private static ResponseFormat notFoundResponse; + private static ResponseFormat invalidContentResponse; + private static ResponseFormat nameExistsResponse; + + @BeforeClass + public static void setup() { + String appConfigDir = "src/test/resources/config/catalog-be"; + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + createResponses(); + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + } + + private static void createResponses() { + userSuccessEither = Either.left(user); + componentSuccessEither = Either.left(resource); + getPolicyTypeSuccessEither = Either.left(policyType); + policySuccessEither = Either.left(policy); + notFoundResponse = new ResponseFormat(); + notFoundResponse.setStatus(404); + invalidContentResponse = new ResponseFormat(); + invalidContentResponse.setStatus(400); + nameExistsResponse = new ResponseFormat(); + nameExistsResponse.setStatus(409); + } + + @Test + public void createPolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void createPolicyUserFailureTest(){ + Either<User, ResponseFormat> userNotFoundResponse = Either.right(new ResponseFormat(404)); + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userNotFoundResponse); + stubRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + private void assertNotFound(Either<PolicyDefinition, ResponseFormat> response) { + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void createPolicyComponentFailureTest(){ + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither); + Either<Component, StorageOperationStatus> componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND); + when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(ComponentTypeEnum.RESOURCE))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyPolicyTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeFailed); + when(componentsUtils.convertFromStorageResponse(eq(getPolicyTypeFailed.right().value()))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyComponentTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + Either<PolicyDefinition, StorageOperationStatus> addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes); + when(componentsUtils.convertFromStorageResponse(eq(addPolicyRes.right().value()))).thenReturn(ActionStatus.INVALID_CONTENT); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_CONTENT))).thenReturn(invalidContentResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(400)); + } + + @Test + public void updatePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyNameFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NAME_ALREADY_EXIST), eq(POLICY_NAME))).thenReturn(nameExistsResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(409)); + } + + @Test + public void getPolicySuccessTest(){ + stubValidationSuccess(CREATE_POLICY); + stubCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID); + assertTrue(response.isLeft()); + } + + @Test + public void getPolicyFailureTest(){ + stubValidationSuccess(CREATE_POLICY); + stubRollback(); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), eq(INVALID_POLICY_ID), eq(COMPONENT_ID))).thenReturn(notFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void deletePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + when(toscaOperationFacade.removePolicyFromComponent(eq(COMPONENT_ID),eq(POLICY_ID))).thenReturn(StorageOperationStatus.OK); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void deletePolicyFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true); + assertNotFound(response); + } + + private void stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), anyString(), anyString())).thenReturn(new ResponseFormat(404)); + } + + @Test + public void updatePolicyPropertiesSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + String prop1 = "Name"; + String prop2 = "Type"; + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1)); + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2)); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + PropertyDataDefinition[] properties = getProperties(prop1, prop2); + policy.setProperties(Arrays.asList(properties)); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties , USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyTargetsSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubGetToscaElementSuccess(); + stubGetTargetType(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID); + + Assert.assertTrue(result.isLeft()); + PolicyDefinition policyResult = result.left().value(); + Map<PolicyTargetType, List<String>> targets = getTargets(); + assertThat(policyResult.getTargets().values()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES)); + + } + + private void stubGetTargetType() { + } + + @Test + public void updatePolicyTargetsTargetIDFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeId(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertEquals(responseResult.getStatus().longValue(), 400L); + + } + + private void stubComponentUtilsGetResponseTargetNotFound() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST), (anyString()))).thenReturn(new ResponseFormat(400)); + } + + @Test + public void updatePolicyTargetsTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeType(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertTrue(responseResult.getStatus().equals(400)); + + } + + private void stubUpdatePolicyOfComponentSuccess() { + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy))).thenReturn(policySuccessEither); + } + + + @Test + public void updatePolicyPropertiesFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.PROPERTY_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + policy.setProperties(null); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getProperties("Name", "Type") , USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + private PropertyDataDefinition[] getProperties(String prop1, String prop2) { + PropertyDataDefinition property1 = new PropertyDataDefinition(); + property1.setName(prop1); + property1.setValue(prop1); + PropertyDataDefinition property2 = new PropertyDataDefinition(); + property2.setName(prop2); + property2.setValue(prop2); + PropertyDataDefinition[] properties = {property1, property2}; + return properties; + } + + + private void stubUnlockAndRollback() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubRollback(); + } + + private void stubCommit() { + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void stubRollback() { + when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + } + + private void stubUnlockAndCommit() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubCommit(); + } + + private void stubValidateAndLockSuccess(String methodName) { + stubValidationSuccess(methodName); + when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + } + + private void stubValidationSuccess(String methodName) { + when(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(userSuccessEither); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither); + } + + private void stubGetToscaFullElementSuccess() { + when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(buildElementEither()); + } + + private void stubGetToscaElementSuccess() { + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID))).thenReturn(componentSuccessEither); + } + + private Either<Component, StorageOperationStatus> buildElementEither() { + ResourceBuilder builder = new ResourceBuilder(); + GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build(); + ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder(); + ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build(); + return Either.left(builder.addGroups(groupDefinition).addComponentInstance(componentInstance).build()); + } + + private Map<PolicyTargetType, List<String>> getTargets() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + + + private static PolicyTypeDefinition buildPolicyType() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + policyType.setType(POLICY_TYPE_NAME); + return policyType; + } + + private static PolicyDefinition buildPolicy(String policyName) { + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + policy.setPolicyTypeName(POLICY_TYPE_NAME); + policy.setComponentName(COMPONENT_NAME); + policy.setName(policyName); + return policy; + } + + private static Resource buildResource() { + Resource resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setName(COMPONENT_NAME); + resource.setCreatorUserId(USER_ID); + resource.setLastUpdaterUserId(USER_ID); + resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setResourceType(ResourceTypeEnum.VF); + resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); + Map<String, PolicyDefinition> policies = new HashMap<>(); + policies.put(POLICY_ID, policy); + resource.setPolicies(policies); + return resource; + } + + private static User buildUser() { + User user = new User(); + user.setUserId(USER_ID); + return user; + } + private List<PolicyTargetDTO> getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType("componentInstances"); + + return Arrays.asList(target1, target2); + } + + private List<PolicyTargetDTO> getFakeIDTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target1.setType(GROUP_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target2.setType(COMPONENT_INSTANCE_TYPE); + + return Arrays.asList(target1, target2); + } + private List<PolicyTargetDTO> getFakeTypeTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType(FAKE_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType(FAKE_TYPE); + + return Arrays.asList(target1, target2); + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeType() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeId() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + return targets; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java new file mode 100644 index 0000000000..ad3e6e8974 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java @@ -0,0 +1,148 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.core.Response; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyPropertiesBusinessLogicTest { + + private static final String POLICY_ID = "policy1"; + private static final String RESOURCE_ID = "resourceId"; + private static final String USER_ID = "userId"; + public static final String NO_PROPS_POLICY = "policy2"; + @InjectMocks + private PolicyBusinessLogic testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private TitanDao titanDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private ComponentsUtils componentsUtils; + + private ComponentParametersView componentFilter; + private Resource resource; + private PropertyDefinition prop1, prop2; + + @Before + public void setUp() throws Exception { + componentFilter = new ComponentParametersView(true); + componentFilter.setIgnorePolicies(false); + componentFilter.setIgnoreUsers(false); + + prop1 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + prop2 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + + PolicyDefinition policy1 = PolicyDefinitionBuilder.create() + .setUniqueId(POLICY_ID) + .setProperties(prop1, prop2) + .build(); + + PolicyDefinition policy2 = PolicyDefinitionBuilder.create() + .setUniqueId(NO_PROPS_POLICY) + .build(); + resource = new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) + .setLastUpdaterUserId(USER_ID) + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + @After + public void tearDown() { + verify(titanDao).commit(); + } + + @Test + public void getPolicyProperties_userIdIsNull() { + String userId = null; + ResponseFormat forbiddenResponse = new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()); + when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenReturn(Either.right(forbiddenResponse)); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null); + assertThat(policyProperties.right().value()).isSameAs(forbiddenResponse); + } + + @Test + public void getPolicyProperties_componentNotFound() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.right().value()).isSameAs(notFoundResponse); + } + + @Test + public void getPolicyProperties_policyNotExist() { + doPolicyValidations(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, "nonExistingPolicy", RESOURCE_ID)).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, "nonExistingPolicy", USER_ID); + assertThat(policyProperties.right().value()).isEqualTo(notFoundResponse); + } + + @Test + public void getPolicyProperties_noPropertiesOnPolicy() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, NO_PROPS_POLICY, USER_ID); + assertThat(policyProperties.left().value()).isNull(); + } + + @Test + public void getPolicyProperties() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.left().value()) + .usingElementComparatorOnFields("uniqueId") + .containsExactly(prop1, prop2); + } + + private void doPolicyValidations() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.left(resource)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java new file mode 100644 index 0000000000..7dc12d96e6 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.impl; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTypeBusinessLogicTest { + + private static final String USER_ID = "userId"; + private static final Set<String> EXCLUDED_POLICY_TYPES = newHashSet("type1", "type2"); + private static final String COMPONENT_TYPE = "VF"; + + @InjectMocks + private PolicyTypeBusinessLogic testInstance; + @Mock + private TitanDao titanDao; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private UserValidations userValidations; + + @Before + public void setUp() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.left(new User())); + when(componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(any(StorageOperationStatus.class))).thenCallRealMethod(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES)); + } + + @BeforeClass + public static void beforeClass() { + new DummyConfigurationManager(); + } + + @Test + public void getAllPolicyTypes_userNotExist() { + ResponseFormat userNotExistResponse = new ResponseFormat(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.right(userNotExistResponse)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(userNotExistResponse); + } + + @Test + public void getAllPolicyTypes_whenExcludePolicyTypesSetIsNull_passNullExcludedTypesSet() { + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenCallRealMethod(); + when(policyTypeOperation.getAllPolicyTypes(null)).thenReturn(Either.left(emptyList())); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + } + + @Test + public void getAllPolicyTypes() { + List<PolicyTypeDefinition> policyTypes = Arrays.asList(new PolicyTypeBuilder().setUniqueId("id1").build(), + new PolicyTypeBuilder().setUniqueId("id2").build(), + new PolicyTypeBuilder().setUniqueId("id3").build()); + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.left(policyTypes)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isSameAs(policyTypes); + } + + @Test + public void getAllPolicyTypes_noPolicyTypes() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + verify(titanDao).commit(); + } + + @Test + public void getAllPolicyTypes_err() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + ResponseFormat errResponse = new ResponseFormat(); + when(componentsUtils.getResponseFormat(StorageOperationStatus.GENERAL_ERROR)).thenReturn(errResponse); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(errResponse); + verify(titanDao).commit(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index f7724aaeff..8054baf15f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -20,22 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; @@ -44,13 +29,13 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -98,1635 +83,1738 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class ResourceBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName()); - public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; - public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; - public static final String RESOURCE_SUBCATEGORY = "Router"; + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class); + public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; + public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; + public static final String RESOURCE_SUBCATEGORY = "Router"; - public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; - public static final String UPDATED_SUBCATEGORY = "Gateway"; + public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; + public static final String UPDATED_SUBCATEGORY = "Gateway"; - public static final String RESOURCE_NAME = "My-Resource_Name with space"; + public static final String RESOURCE_NAME = "My-Resource_Name with space"; private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF"; + private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR"; private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC"; private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF"; - - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - IElementOperation mockElementDao; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); - NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); - TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); - final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); - final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); - final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); - final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - ResponseFormatManager responseManager = null; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - User user = null; - Resource resourceResponse = null; - Resource genericVF = null; - Resource genericVFC = null; - Resource genericPNF = null; - ComponentsUtils componentsUtils = new ComponentsUtils(); - ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); - CsarOperation csarOperation = Mockito.mock(CsarOperation.class); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - - - public ResourceBusinessLogicTest() { - - } - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - Mockito.reset(propertyOperation); - - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - - Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); - Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); - - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); - - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - - // createResource - resourceResponse = createResourceObject(true); - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); - Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - - // BL object - artifactManager.nodeTemplateOperation = nodeTemplateOperation; - bl = new ResourceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setCapabilityTypeOperation(capabilityTypeOperation); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setLifecycleManager(lifecycleBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setArtifactsManager(artifactManager); - bl.setPropertyOperation(propertyOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setApplicationDataTypeCache(applicationDataTypeCache); - bl.setCsarOperation(csarOperation); - bl.setCacheManagerOperation(cacheManager); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); - toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); - bl.setToscaOperationFacade(toscaOperationFacade); - Resource resourceCsar = createResourceObjectCsar(true); - setCanWorkOnResource(resourceCsar); - Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); - when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); - responseManager = ResponseFormatManager.getInstance(); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource createResourceObjectCsar(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setResourceVendorModelNumber(""); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - resource.setCsarUUID("valid_vf.csar"); - resource.setCsarVersion("1"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource setCanWorkOnResource(Resource resource) { - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setLastUpdaterUserId(user.getUserId()); - return resource; - } - - @Test - public void testHappyScenario() { - Resource resource = createResourceObject(false); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEquals(createResourceObject(true), createResponse.left().value()); - } - - @Test - public void testUpdateHappyScenario() { - Resource resource = createResourceObjectCsar(true); - setCanWorkOnResource(resource); - - Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); - when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); - if (updateResponse.isRight()) { - assertEquals(new Integer(200), updateResponse.right().value().getStatus()); - } - assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); - } - - /* CREATE validations - start ***********************/ - // Resource name - start - - @Test - public void testFailedResourceValidations() { - testResourceNameExist(); - testResourceNameEmpty(); - // testResourceNameExceedsLimit(); - testResourceNameWrongFormat(); - testResourceDescExceedsLimitCreate(); - testResourceDescNotEnglish(); - testResourceDescriptionEmpty(); - testResourceDescriptionMissing(); - testResourceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - testResourceTagNotExist(); - testResourceTagEmpty(); - testTagsExceedsLimitCreate(); - testTagsNoServiceName(); - testInvalidTag(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testResourceContactIdEmpty(); - testResourceContactIdMissing(); - testVendorNameExceedsLimit(); - testVendorNameWrongFormatCreate(); - testVendorReleaseWrongFormat(); - testVendorReleaseExceedsLimitCreate(); - testResourceVendorModelNumberExceedsLimit(); - testResourceVendorNameMissing(); - testResourceVendorReleaseMissing(); - testResourceCategoryExist(); - testResourceBadCategoryCreate(); - testHappyScenarioCostLicenseType(); - testCostWrongFormatCreate(); - testLicenseTypeWrongFormatCreate(); - testResourceTemplateNotExist(); - testResourceTemplateEmpty(); - testResourceTemplateInvalid(); - } - - private void testResourceNameExist() { - String resourceName = "alreadyExists"; - Resource resourceExist = createResourceObject(false); - resourceExist.setName(resourceName); - resourceExist.getTags().add(resourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - private void testResourceNameEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceNameExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - resourceExccedsNameLimit.setName(tooLongResourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testResourceNameWrongFormat() { - Resource resource = createResourceObject(false); - // contains : - String nameWrongFormat = "ljg?fd"; - resource.setName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Resource name - end - // Resource description - start - private void testResourceDescExceedsLimitCreate() { - Resource resourceExccedsDescLimit = createResourceObject(false); - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - resourceExccedsDescLimit.setDescription(tooLongResourceDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testResourceDescNotEnglish() { - Resource notEnglish = createResourceObject(false); - // Not english - String notEnglishDesc = "\uC2B5"; - notEnglish.setDescription(notEnglishDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - // Resource description - end - // Resource icon start - - private void testResourceIconMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconInvalid() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Resource icon end - // Resource tags - start - private void testResourceTagNotExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testResourceTagEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testTagsExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resourceExccedsNameLimit.getName()); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; - String tag2 = resourceExccedsNameLimit.getName(); - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb%#%"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); - - } - - // Resource tags - stop - // Resource contact start - - private void testContactIdTooLong() { - Resource resourceContactId = createResourceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - resourceContactId.setContactId(contactIdTooLong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Resource resourceContactId = createResourceObject(false); - // 3 letters and 3 digits and special characters - String contactIdFormatWrong = "yrt134!!!"; - resourceContactId.setContactId(contactIdFormatWrong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testVendorNameExceedsLimit() { - Resource resourceExccedsVendorNameLimit = createResourceObject(false); - String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - } - - private void testResourceVendorModelNumberExceedsLimit() { - Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); - String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - } - - private void testVendorNameWrongFormatCreate() { - Resource resource = createResourceObject(false); - // contains * - String nameWrongFormat = "ljg*fd"; - resource.setVendorName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - } - - private void testVendorReleaseWrongFormat() { - Resource resource = createResourceObject(false); - // contains > - String nameWrongFormat = "1>2"; - resource.setVendorRelease(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); - - } - - private void testVendorReleaseExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - private void testResourceVendorNameMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); - } - - private void testResourceVendorReleaseMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorRelease(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); - } - - // Resource vendor name/release stop - // Category start - private void testResourceCategoryExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceBadCategoryCreate() { - - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - resourceExist.addCategory("koko", "koko"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Category stop - // Cost start - private void testHappyScenarioCostLicenseType() { - Resource createResourceObject = createResourceObject(false); - Resource createResourceObjectAfterCreate = createResourceObject(true); - // Adding cost and licenseType to basic mock - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - - String cost = "123.456"; - String licenseType = "User"; - createResourceObject.setCost(cost); - createResourceObject.setLicenseType(licenseType); - Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - createResourceObjectAfterCreate.setCost(cost); - createResourceObjectAfterCreate.setLicenseType(licenseType); - assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); - } - - private void testCostWrongFormatCreate() { - Resource resourceCost = createResourceObject(false); - // Comma instead of fullstop - String cost = "12356,464"; - resourceCost.setCost(cost); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // Cost stop - // License type start - private void testLicenseTypeWrongFormatCreate() { - Resource resourceLicenseType = createResourceObject(false); - // lowcase - String licenseType = "cpu"; - resourceLicenseType.setLicenseType(licenseType); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // License type stop - // Derived from start - private void testResourceTemplateNotExist() { - Resource resourceExist = createResourceObject(false); - List<String> list = null; - resourceExist.setDerivedFrom(list); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDerivedFrom(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateInvalid() { - Resource resourceExist = createResourceObject(false); - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - resourceExist.setDerivedFrom(derivedFrom); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - // Derived from stop - - private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - // UPDATE tests - start - // Resource name - @Test - public void testResourceNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setName(nameWrongFormat); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testResourceNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String name = "ljg"; - updatedResource.setName(name); - resource.setVersion("1.0"); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - - } - - @Ignore - public void testResourceNameExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - updatedResource.setName(tooLongResourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - @Test - public void testResourceNameAlreadyExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceName = "alreadyExists"; - updatedResource.setName(resourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - // - - @Test - public void testResourceDescExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - updatedResource.setDescription(tooLongResourceDesc); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - - } - - @Test - public void testIconWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains . - String icon = "icon.jpg"; - updatedResource.setIcon(icon); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testIconAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains - String icon = "icon"; - updatedResource.setIcon(icon); - - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - - } - - @Test - public void testTagsExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resource.getName()); - - updatedResource.setTags(tagsList); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - } - - @Test - public void testVendorNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - - } - - @Test - public void testVendorNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - - } - - @Test - public void testVendorReleaseExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // 129 chars, the limit is 128 - String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; - updatedResource.setVendorRelease(tooLongVendorRelease); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - @Ignore - public void testContactIdWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - // 3 letters and 3 digits - String contactIdTooLong = "yrt134"; - updatedResource.setContactId(contactIdTooLong); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceBadCategory_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - String badCategory = "ddfds"; - updatedResource.setCategories(null); - updatedResource.addCategory(badCategory, "fikt"); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceCategoryAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - updatedResource.setCategories(null); - updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - } - - // Derived from start - @Test - public void testResourceTemplateNotExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - String resourceId = resource.getUniqueId(); - - List<String> list = null; - updatedResource.setDerivedFrom(list); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateEmpty_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - updatedResource.setDerivedFrom(new ArrayList<String>()); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateInvalid_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - - @Test - public void testResourceTemplateCertify_UPDATE_HAPPY() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); - - Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); - when(propertyOperation.deleteAllPropertiesAssociatedToNode(Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isLeft()); - } - - @Test - public void testResourceTemplateCertify_UPDATE_SAD() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) - .thenReturn(isToscaNameExtending); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, - false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - } - // Derived from stop - - @Test - public void createOrUpdateResourceAlreadyCheckout() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - createResponse.left().value().setLastUpdaterUserId(user.getUserId()); - assertTrue(createResponse.isLeft()); - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceCertified() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - assertTrue(createResponse.isLeft()); - Resource certifiedResource = createResponse.left().value(); - certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - certifiedResource.setVersion("1.0"); - - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceNotExist() { - Resource resourceToUpdtae = createResourceObject(false); - - Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); - - Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { - Resource basic = createResourceObject(true); - - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); - when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - @Test - public void testValidatePropertiesDefaultValues_FailedWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1.5"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IElementOperation mockElementDao; + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); + NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); + TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); + final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); + final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + ResponseFormatManager responseManager = null; + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + User user = null; + Resource resourceResponse = null; + Resource genericVF = null; + Resource genericCR = null; + Resource genericVFC = null; + Resource genericPNF = null; + ComponentsUtils componentsUtils; + ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + + public ResourceBusinessLogicTest() { + + } + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); + + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); + Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); + + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); + + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount); + /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/ + + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + + // createResource + resourceResponse = createResourceObject(true); + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); + Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + artifactManager.setNodeTemplateOperation(nodeTemplateOperation); + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setCapabilityTypeOperation(capabilityTypeOperation); + bl.setComponentsUtils(componentsUtils); + bl.setLifecycleManager(lifecycleBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setArtifactsManager(artifactManager); + bl.setPropertyOperation(propertyOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setApplicationDataTypeCache(applicationDataTypeCache); + bl.setCsarOperation(csarOperation); + bl.setCacheManagerOperation(cacheManager); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); + toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setUserValidations(userValidations); + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); + when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + responseManager = ResponseFormatManager.getInstance(); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource createResourceObjectCsar(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setResourceVendorModelNumber(""); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + resource.setCsarUUID("valid_vf.csar"); + resource.setCsarVersion("1"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); + return resource; + } + + @Test + public void testHappyScenario() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createResourceObject(false); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEquals(createResourceObject(true), createResponse.left().value()); + } + + @Test + public void testUpdateHappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + if (updateResponse.isRight()) { + assertEquals(new Integer(200), updateResponse.right().value().getStatus()); + } + assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); + } + + /* CREATE validations - start ***********************/ + // Resource name - start + + @Test + public void testFailedResourceValidations() { + testResourceNameExist(); + testResourceNameEmpty(); + // testResourceNameExceedsLimit(); + testResourceNameWrongFormat(); + testResourceDescExceedsLimitCreate(); + testResourceDescNotEnglish(); + testResourceDescriptionEmpty(); + testResourceDescriptionMissing(); + testResourceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + testResourceTagNotExist(); + testResourceTagEmpty(); + testTagsExceedsLimitCreate(); + testTagsNoServiceName(); + testInvalidTag(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + testResourceVendorModelNumberExceedsLimit(); + testResourceVendorNameMissing(); + testResourceVendorReleaseMissing(); + testResourceCategoryExist(); + testResourceBadCategoryCreate(); + testHappyScenarioCostLicenseType(); + testCostWrongFormatCreate(); + testLicenseTypeWrongFormatCreate(); + testResourceTemplateNotExist(); + testResourceTemplateEmpty(); + testResourceTemplateInvalid(); + } + + private void testResourceNameExist() { + String resourceName = "alreadyExists"; + Resource resourceExist = createResourceObject(false); + resourceExist.setName(resourceName); + resourceExist.getTags().add(resourceName); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + private void testResourceNameEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceNameExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + resourceExccedsNameLimit.setName(tooLongResourceName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testResourceNameWrongFormat() { + Resource resource = createResourceObject(false); + // contains : + String nameWrongFormat = "ljg?fd"; + resource.setName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Resource name - end + // Resource description - start + private void testResourceDescExceedsLimitCreate() { + Resource resourceExccedsDescLimit = createResourceObject(false); + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + resourceExccedsDescLimit.setDescription(tooLongResourceDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testResourceDescNotEnglish() { + Resource notEnglish = createResourceObject(false); + // Not english + String notEnglishDesc = "\uC2B5"; + notEnglish.setDescription(notEnglishDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + // Resource description - end + // Resource icon start + + private void testResourceIconMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconInvalid() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Resource icon end + // Resource tags - start + private void testResourceTagNotExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testResourceTagEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testTagsExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resourceExccedsNameLimit.getName()); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; + String tag2 = resourceExccedsNameLimit.getName(); + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb%#%"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"}); + + } + + // Resource tags - stop + // Resource contact start + + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + resourceContactId.setContactId(contactIdTooLong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Resource resourceContactId = createResourceObject(false); + // 3 letters and 3 digits and special characters + String contactIdFormatWrong = "yrt134!!!"; + resourceContactId.setContactId(contactIdFormatWrong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testResourceVendorModelNumberExceedsLimit() { + Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); + String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + } + + private void testVendorReleaseWrongFormat() { + Resource resource = createResourceObject(false); + // contains > + String nameWrongFormat = "1>2"; + resource.setVendorRelease(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); + + } + + private void testVendorReleaseExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + private void testResourceVendorNameMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); + } + + private void testResourceVendorReleaseMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorRelease(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); + } + + // Resource vendor name/release stop + // Category start + private void testResourceCategoryExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceBadCategoryCreate() { + + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + resourceExist.addCategory("koko", "koko"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Category stop + // Cost start + private void testHappyScenarioCostLicenseType() { + Resource createResourceObject = createResourceObject(false); + Resource createResourceObjectAfterCreate = createResourceObject(true); + // Adding cost and licenseType to basic mock + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + createResourceObjectAfterCreate.setCost(cost); + createResourceObjectAfterCreate.setLicenseType(licenseType); + assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); + } + + private void testCostWrongFormatCreate() { + Resource resourceCost = createResourceObject(false); + // Comma instead of fullstop + String cost = "12356,464"; + resourceCost.setCost(cost); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // Cost stop + // License type start + private void testLicenseTypeWrongFormatCreate() { + Resource resourceLicenseType = createResourceObject(false); + // lowcase + String licenseType = "cpu"; + resourceLicenseType.setLicenseType(licenseType); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // License type stop + // Derived from start + private void testResourceTemplateNotExist() { + Resource resourceExist = createResourceObject(false); + List<String> list = null; + resourceExist.setDerivedFrom(list); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDerivedFrom(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateInvalid() { + Resource resourceExist = createResourceObject(false); + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + resourceExist.setDerivedFrom(derivedFrom); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + // Derived from stop + + private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + // UPDATE tests - start + // Resource name + @Test + public void testResourceNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testResourceNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + @Test + public void testResourceNameAlreadyExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + // + + @Test + public void testResourceDescExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + + } + + @Test + public void testIconWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testIconAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + + } + + @Test + public void testTagsExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resource.getName()); + + updatedResource.setTags(tagsList); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + } + + @Test + public void testVendorNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorNameWrongFormat() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorReleaseExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + @Ignore + public void testContactIdWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + updatedResource.setContactId(contactIdTooLong); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceBadCategory_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceCategoryAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + } + + // Derived from start + @Test + public void testResourceTemplateNotExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List<String> list = null; + updatedResource.setDerivedFrom(list); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateEmpty_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList<String>()); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateInvalid_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + + @Test + public void testResourceTemplateCertify_UPDATE_HAPPY() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); + + Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); + when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isLeft()); + } + + @Test + public void testResourceTemplateCertify_UPDATE_SAD() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) + .thenReturn(isToscaNameExtending); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, + false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceCertified() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + assertTrue(createResponse.isLeft()); + Resource certifiedResource = createResponse.left().value(); + certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + certifiedResource.setVersion("1.0"); + + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceNotExist() { + Resource resourceToUpdtae = createResourceObject(false); + + Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); + + Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { + Resource basic = createResourceObject(true); + + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_FailedWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1.5"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isRight()); - } - -// @Test -// public void testDeleteMarkedResourcesNoResources() { -// List<GraphVertex> ids = new ArrayList<>(); -// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + +// @Test +// public void testDeleteMarkedResourcesNoResources() { +// List<GraphVertex> ids = new ArrayList<>(); +// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); +// +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// } // -// } +// @Test +// public void testDeleteMarkedResources() { +// List<String> ids = new ArrayList<String>(); +// String resourceInUse = "123"; +// ids.add(resourceInUse); +// String resourceFree = "456"; +// ids.add(resourceFree); +// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// @Test -// public void testDeleteMarkedResources() { -// List<String> ids = new ArrayList<String>(); -// String resourceInUse = "123"; -// ids.add(resourceInUse); -// String resourceFree = "456"; -// ids.add(resourceFree); -// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); +// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); // -// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); -// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); +// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); +// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); // -// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); -// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); +// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); +// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); // -// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); -// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); +// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); +// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); // -// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); -// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); +// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); +// List<String> deletedComponents = new ArrayList<>(); +// deletedComponents.add(resourceFree); +// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); // -// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); -// List<String> deletedComponents = new ArrayList<>(); -// deletedComponents.add(resourceFree); -// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); -// -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// List<String> resourceIdList = deleteMarkedResources.left().value(); -// assertFalse(resourceIdList.isEmpty()); -// assertTrue(resourceIdList.contains(resourceFree)); -// assertFalse(resourceIdList.contains(resourceInUse)); +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// List<String> resourceIdList = deleteMarkedResources.left().value(); +// assertFalse(resourceIdList.isEmpty()); +// assertTrue(resourceIdList.contains(resourceFree)); +// assertFalse(resourceIdList.contains(resourceInUse)); // -// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); -// } - - @SuppressWarnings("unchecked") - @Test - public void testFindVfCsarArtifactsToHandle() { - - Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; - String methodName = "findVfCsarArtifactsToHandle"; - Resource resource = new Resource(); - String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; - String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; - String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; - - String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; - String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; - String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; - - byte[] oldPayloadData = "oldPayloadData".getBytes(); - byte[] newPayloadData = "newPayloadData".getBytes(); - Map<String, ArtifactDefinition> deploymentArtifacts =new HashMap<>(); - - ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); - deploymentArtifactToUpdate.setMandatory(false); - deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); - deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); - deploymentArtifactToUpdate.setPayload(oldPayloadData); - deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); - deploymentArtifactToDelete.setMandatory(false); - deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); - deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); - deploymentArtifactToDelete.setPayload(oldPayloadData); - deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); - - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); - deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); - - Map<String, ArtifactDefinition> artifacts = new HashMap<>(); - - ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); - artifactToUpdate.setMandatory(false); - artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); - artifactToUpdate.setArtifactType("SNMP_POLL"); - artifactToUpdate.setPayload(oldPayloadData); - artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToDelete = new ArtifactDefinition(); - artifactToDelete.setMandatory(false); - artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); - artifactToDelete.setArtifactType("SNMP_TRAP"); - artifactToDelete.setPayload(oldPayloadData); - artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); - - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()),artifactToUpdate); - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()),artifactToDelete); - artifacts.put("ignore",artifactToIgnore); - - resource.setDeploymentArtifacts(deploymentArtifacts); - resource.setArtifacts(artifacts); - - List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); - NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, deploymentArtifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName); - - NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactInfoToCreateFileName); - - artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); - artifactPathAndNameList.add(informationalArtifactInfoToUpdate); - artifactPathAndNameList.add(deploymentArtifactInfoToCreate); - artifactPathAndNameList.add(informationalArtifactInfoToCreate); - - Object[] argObjects = {resource, artifactPathAndNameList, user}; - Class[] argClasses = {Resource.class, List.class, User.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = - (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Update).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - - } - catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testVFGeneratedInputs() { - - Resource resource = createVF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); - } - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckout() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - // create a new generic version without properties - genericVF.setVersion("2.0"); - genericVF.setProperties(null); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - List<InputDefinition> currentInputs = resource.getInputs(); - //verify previous inputs ownerId fields exist - user may not delete generated inputs - assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update required and valid - assertTrue(upgradeToLatestGeneric.left().value()); - //verify version was upgraded - assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not deleted - assertTrue(8 == resource.getInputs().size()); - //verify inputs ownerId fields were removed - user may delete/edit inputs - assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - } - - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - - //add an input to the VF - PropertyDefinition newProp = new PropertyDefinition(); - newProp.setType("integer"); - newProp.setName("newProp"); - resource.getInputs().add(new InputDefinition(newProp)); - - //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type - genericVF.setVersion("2.0"); - newProp.setType("string"); - genericVF.setProperties(new ArrayList<PropertyDefinition>()); - genericVF.getProperties().add(newProp); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update is invalid an void - assertFalse(upgradeToLatestGeneric.left().value()); - //verify version was not upgraded - assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not removed - assertTrue(9 == resource.getInputs().size()); - //verify user defined input exists - assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); - } - - @Test - public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { - - Resource resource = createPNF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); - assertTrue(0 == resource.getArtifacts().size()); - } - - - private Resource createVF() { - - genericVF = setupGenericTypeMock(GENERIC_VF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.VF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - private Resource createPNF() { - - genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.PNF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - - +// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); +// } + + @SuppressWarnings("unchecked") + @Test + public void testFindVfCsarArtifactsToHandle() { + + Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; + String methodName = "findVfCsarArtifactsToHandle"; + Resource resource = new Resource(); + String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; + String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; + String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; + + String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; + String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; + String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml"; + String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; + + byte[] oldPayloadData = "oldPayloadData".getBytes(); + byte[] newPayloadData = "newPayloadData".getBytes(); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + + ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); + deploymentArtifactToUpdate.setMandatory(false); + deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); + deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); + deploymentArtifactToUpdate.setPayload(oldPayloadData); + deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); + deploymentArtifactToDelete.setMandatory(false); + deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); + deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); + deploymentArtifactToDelete.setPayload(oldPayloadData); + deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); + + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); + deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); + + Map<String, ArtifactDefinition> artifacts = new HashMap<>(); + + ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); + artifactToUpdate.setMandatory(false); + artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); + artifactToUpdate.setArtifactType("SNMP_POLL"); + artifactToUpdate.setPayload(oldPayloadData); + artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition artifactToDelete = new ArtifactDefinition(); + artifactToDelete.setMandatory(false); + artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); + artifactToDelete.setArtifactType("SNMP_TRAP"); + artifactToDelete.setPayload(oldPayloadData); + artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToDelete.setIsFromCsar(true); + + ArtifactDefinition artifactToNotDelete = new ArtifactDefinition(); + artifactToNotDelete.setMandatory(false); + artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName); + artifactToNotDelete.setArtifactType("SNMP_TRAP"); + artifactToNotDelete.setPayload(oldPayloadData); + artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToNotDelete.setIsFromCsar(false); + + ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); + + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete); + artifacts.put("ignore", artifactToIgnore); + + resource.setDeploymentArtifacts(deploymentArtifacts); + resource.setArtifacts(artifacts); + + List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); + NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false); + + NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactInfoToCreateFileName, false); + + artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdate); + artifactPathAndNameList.add(deploymentArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar); + artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar); + + Object[] argObjects = {resource, artifactPathAndNameList, user}; + Class[] argClasses = {Resource.class, List.class, User.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = + (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size() == 1); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testVFGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(8 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); + } + + @Test + public void testCRGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createCR(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(5 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericCR.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericCR.getVersion())); + } + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckout() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + //create a VF that is derived from generic version 1.0 + Resource resource = createVF(); + // create a new generic version without properties + genericVF.setVersion("2.0"); + genericVF.setProperties(null); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + List<InputDefinition> currentInputs = resource.getInputs(); + //verify previous inputs ownerId fields exist - user may not delete generated inputs + assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update required and valid + assertTrue(upgradeToLatestGeneric.left().value()); + //verify version was upgraded + assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not deleted + assertTrue(8 == resource.getInputs().size()); + //verify inputs ownerId fields were removed - user may delete/edit inputs + assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + } + + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { + + //create a VF that is derived from generic version 1.0 + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + + //add an input to the VF + PropertyDefinition newProp = new PropertyDefinition(); + newProp.setType("integer"); + newProp.setName("newProp"); + resource.getInputs().add(new InputDefinition(newProp)); + + //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type + genericVF.setVersion("2.0"); + newProp.setType("string"); + genericVF.setProperties(new ArrayList<PropertyDefinition>()); + genericVF.getProperties().add(newProp); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update is invalid an void + assertFalse(upgradeToLatestGeneric.left().value()); + //verify version was not upgraded + assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not removed + assertTrue(9 == resource.getInputs().size()); + //verify user defined input exists + assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); + } + + @Test + public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createPNF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(3 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); + assertTrue(0 == resource.getArtifacts().size()); + } + + + private Resource createVF() { + + genericVF = setupGenericTypeMock(GENERIC_VF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.VF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Resource createCR() { + + genericCR = setupGenericTypeMock(GENERIC_CR_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.CR); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + private Resource createPNF() { + + genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.PNF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Map<String, String> getGenericPropertiesByToscaName(String toscaName) { + HashMap<String, String> PNFProps = new HashMap<String, String>() {{ + put("nf_function", "string"); + put("nf_role", "string"); + put("nf_type", "string"); + }}; + + HashMap<String, String> CRProps = new HashMap<String, String>() {{ + putAll(PNFProps); + put("nf_naming_code", "string"); + put("nf_naming", "org.openecomp.datatypes.Naming"); + }}; + + HashMap<String, String> VFProps = new HashMap<String, String>() {{ + putAll(CRProps); + put("availability_zone_max_count", "integer"); + put("min_instances", "integer"); + put("max_instances", "integer"); + }}; + + if (toscaName.contains("PNF")) return PNFProps; + if (toscaName.contains("CR")) return CRProps; + if (toscaName.contains("VF")) return VFProps; + + return new HashMap<>(); + } + + private Resource setupGenericTypeMock(String toscaName) { - - Resource genericType = createResourceObject(true); - genericType.setVersion("1.0"); - genericType.setToscaResourceName(toscaName); - String[] propNames = {"nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count", "min_instances", "max_instances"}; - String[] propTypes = {"string", "string", "string", "string", "org.openecomp.datatypes.Naming", "integer", "integer", "integer"}; - List<PropertyDefinition> genericProps = new ArrayList<>(); - for(int i = 0; i < 8; ++i){ - PropertyDefinition prop = new PropertyDefinition(); - prop.setName(propNames[i]); - prop.setType(propTypes[i]); - genericProps.add(prop); - } - genericType.setProperties(genericProps); - return genericType; - } - - - + + Resource genericType = createResourceObject(true); + genericType.setVersion("1.0"); + genericType.setToscaResourceName(toscaName); + List<PropertyDefinition> genericProps = new ArrayList<>(); + Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName); + genericPropsMap.forEach((name, type) -> { + PropertyDefinition prop = new PropertyDefinition(); + prop.setName(name); + prop.setType(type); + genericProps.add(prop); + }); + + genericType.setProperties(genericProps); + return genericType; + } + + private void validateUserRoles(Role... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java index 581adb28df..3abf711b91 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -53,6 +44,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ConfigurationSource; @@ -61,252 +53,259 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class ResourceInstanceBusinessLogicTest { - private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; - private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; - private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; - private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; - private static final String SERVICE_ID = "MyServiceId"; - private static final String HEAT_LABEL = "myHeat"; - private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; - private static final String USER_ID = "jh0003"; - private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); - - static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); - - @InjectMocks - static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic(); - - public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); - public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); -// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); - public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // @BeforeClass - public static void setup() { - - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); - - ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); - Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); - artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); - - ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); - Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); - artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); - - ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); - Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); - artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); - - Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); - Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); - - Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); - - Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); - - Either<User, ActionStatus> eitherUser = Either.left(adminUser); - Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); - - Object lightService = new Service(); - Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); -// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); - - Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), - Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); - - Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - - Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), - Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); - - Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); - Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); - - bl.setToscaOperationFacade(toscaOperationFacade); - - StorageOperationStatus status = StorageOperationStatus.OK; - Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); - Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); - Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); - - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); -// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); - setup(); - } - - @Test - public void testAddResourceInstanceArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); + private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; + private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; + private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; + private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; + private static final String SERVICE_ID = "MyServiceId"; + private static final String HEAT_LABEL = "myHeat"; + private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; + private static final String USER_ID = "jh0003"; + private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); + + static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); + + @InjectMocks + static ComponentInstanceBusinessLogic bl = new ComponentInstanceBusinessLogic(); + + public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); + public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); +// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); + public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // @BeforeClass + public static void setup() { + + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); + + ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); + Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); + artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); + + ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); + Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); + artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); + + ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); + Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); + artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); + + Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); + Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); + + Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); + + Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); + + Either<User, ActionStatus> eitherUser = Either.left(adminUser); + Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); + + Object lightService = new Service(); + Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); + + Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.any(AuditingActionEnum.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ResourceAuditData.class)); + + Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + + Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), + Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); + + Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); + Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); + + bl.setToscaOperationFacade(toscaOperationFacade); + + StorageOperationStatus status = StorageOperationStatus.OK; + Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); + Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); + Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); + + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); +// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); + setup(); + } + + @Test + public void testAddResourceInstanceArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); // -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); // -// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); -// assertNotNull(heatParameters); +// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); +// assertNotNull(heatParameters); // -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNotNull(heatEnvParameters); +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNotNull(heatEnvParameters); // -// assertEquals(heatParameters.size(), heatEnvParameters.size()); +// assertEquals(heatParameters.size(), heatEnvParameters.size()); // -// int index = 0; -// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { -// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); -// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); -// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); -// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); -// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); -// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); -// // current of heat parameter should be the default for heat env -// // parameter -// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); +// int index = 0; +// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { +// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); +// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); +// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); +// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); +// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); +// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); +// // current of heat parameter should be the default for heat env +// // parameter +// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); // -// index++; -// } - } - - @Test - public void testAddResourceInstanceArtifactsNoParams() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); - -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); - - List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); - assertNull(heatParameters); - -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNull(heatEnvParameters); - - } - - @SuppressWarnings("unchecked") - @Test - public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); - assertTrue(deploymentArtifacts.size() == 0); - - Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); - } - - private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".yml"); - artifactInfo.setArtifactType("HEAT"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - 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(HEAT_LABEL.toLowerCase()); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); - - if (!placeholderOnly) { - artifactInfo.setEsId(artifactInfo.getUniqueId()); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - - if (withHeatParams) { - 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); - artifactInfo.setListHeatParameters(heatParams); - } - } - - return artifactInfo; - } - - private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } +// index++; +// } + } + + @Test + public void testAddResourceInstanceArtifactsNoParams() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); + +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); + + List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); + assertNull(heatParameters); + +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNull(heatEnvParameters); + + } + + @SuppressWarnings("unchecked") + @Test + public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 0); + + Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); + } + + private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + 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(HEAT_LABEL.toLowerCase()); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + + if (!placeholderOnly) { + artifactInfo.setEsId(artifactInfo.getUniqueId()); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + if (withHeatParams) { + 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); + artifactInfo.setListHeatParameters(heatParams); + } + } + + return artifactInfo; + } + + private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java index 309689af45..5f4dfdc6f7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java @@ -1,12 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +14,12 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class GenericTypeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java new file mode 100644 index 0000000000..6b1b37e5bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java @@ -0,0 +1,258 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class PolicyTypeImportUtilsTest { + + private static final String UNIQUE_ID_EXSISTS = "uniqueId"; + + @Test + public void isPolicyTypesEquals_whenBothTypesAreNull_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, null)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenOneTypeIsNull_returnFalse() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(new PolicyTypeDefinition(), null)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, new PolicyTypeDefinition())).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTypesIsSameObject_returnTrue() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(policyType, policyType)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_allFieldsEquals_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(createPolicyTypeWithAllFields(), createPolicyTypeWithAllFields())).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenTypesAreDifferentInANonCompareFields_returnTrue() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setOwnerId("ownerIdNew"); + type2.setModificationTime(System.currentTimeMillis()); + type2.setCreationTime(System.currentTimeMillis()); + type2.setUniqueId("uniqueIdNew"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenTypeIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setType("newType"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDescription("newDescription"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTargetsAreDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setTargets(new ArrayList<>()); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDerivedFromIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDerivedFrom("newDerivedFrom"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenVersionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setVersion("2.0"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenMetadataIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setMetadata(ImmutableMap.of("newKey", "newVal")); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() { + PolicyTypeDefinition noProperties = new PolicyTypeDefinition(); + PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build(); + PolicyTypeDefinition oneProp = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition twoProps = new PolicyTypeBuilder().setProperties(Arrays.asList(createPropertyDefinitionWithAllFields("prop1"), + createPropertyDefinitionWithAllFields("prop2"))) + .build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(twoProps, oneProp)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesSamePropertiesList_returnTrue() { + List<PropertyDefinition> propList = Collections.singletonList(createPropertyDefinitionWithAllFields("prop1")); + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(propList).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(propList).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListFieldsEquals_returnTrue() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListDifferentInANonComparedFields_returnTrue() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffNonComparedFields = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffNonComparedFields.setOwnerId("newOwner"); + prop1DiffNonComparedFields.setValue("newVal"); + prop1DiffNonComparedFields.setConstraints(null); + prop1DiffNonComparedFields.setUniqueId("newId"); + prop1DiffNonComparedFields.setHidden(true); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffNonComparedFields)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameName_returnFalse() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop2"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOFSameType_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1TypeInteger = createPropertyDefinitionWithAllFields("prop1"); + prop1TypeInteger.setType("integer"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1TypeInteger)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameDefaultVal_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDefault = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDefault.setDefaultValue("newDefVal"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDefault)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameSchema_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffSchema = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffSchema.setSchema(null); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffSchema)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsPasswordFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsPassword = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsPassword.setPassword(!prop1.isPassword()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsPassword)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsRequiredFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsRequired = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsRequired.setRequired(!prop1.isRequired()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsRequired)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotSameDescription_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDescription = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDescription.setDescription("newDescription"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDescription)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + private PolicyTypeDefinition createPolicyTypeWithAllFields() { + return new PolicyTypeBuilder() + .setType("type1") + .setDerivedFrom("derivedFrom") + .setVersion("1.0") + .setDescription("description") + .setUniqueId("id1") + .setHighestVersion(true) + .setModificationTime(System.currentTimeMillis()) + .setCreationTime(System.currentTimeMillis()) + .setTargets(getTargets()) + .setOwner("owner") + .setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2")) + .build(); + } + + private PropertyDefinition createPropertyDefinitionWithAllFields(String name) { + return new PropertyDataDefinitionBuilder() + .setConstraints(Arrays.asList(new GreaterThanConstraint("abc"), new MinLengthConstraint(5))) + .setUniqueId("uid") + .setDefaultValue("val1") + .setType("string") + .setValue("val1") + .setName(name) + .setSchemaType("string") + .setOwnerId("owner") + .setStatus("status") + .setDescription("description") + .setIsPassword(false) + .setIsRequired(false) + .build(); + } + + private List<String> getTargets() { + + return Collections.singletonList(UNIQUE_ID_EXSISTS); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java new file mode 100644 index 0000000000..0dac6ecb2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestGenerationUtils { + + public static ComponentsUtils getComponentsUtils() { + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + return new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java new file mode 100644 index 0000000000..fe6071239e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java @@ -0,0 +1,152 @@ +package org.openecomp.sdc.be.components.impl.version; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GroupMembersUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + private static final String INSTANCE_ID_PRE_CHANGE = "inst2"; + private static final String INSTANCE_ID_POST_CHANGE = "newInst2"; + @InjectMocks + private GroupMembersUpdateOperation testInstance; + @Mock + private GroupsOperation groupsOperation; + @Mock + private ComponentsUtils componentsUtils; + + @Captor + private ArgumentCaptor<List<GroupDataDefinition>> updatedGroupsCaptor; + private GroupDefinition group1, group2, group3; + private Resource container; + private ComponentInstance prevInst2Version, currInst2Version; + private static final ComponentInstance DONT_CARE = new ComponentInstance(); + + @Before + public void setUp() throws Exception { + group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE); + group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3"); + group3 = createGroupWithMembers("group3", "inst1", "inst3"); + container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .setUniqueId(CONTAINER_ID) + .setComponentType(ComponentTypeEnum.RESOURCE) + .build(); + prevInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_PRE_CHANGE) + .build(); + currInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_POST_CHANGE) + .build(); + } + + @Test + public void whenNoGroupsOnContainer_returnOk() { + ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenEmptyListOfGroups_returnOk() { + Resource resource = new Resource(); + resource.setGroups(new ArrayList<>()); + ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupsHasNoMembers_returnOk() { + GroupDefinition group1 = new GroupDefinition(); + group1.setMembers(emptyMap()); + GroupDefinition group2 = new GroupDefinition(); + group2.setMembers(emptyMap()); + Resource container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .build(); + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() { + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() { + verifyAllGroupsHasPrevInstancesAsMembers(); + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null)); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyGroupWithPrevInstanceMemberWereReplaced(); + assertThat(updatedGroupsCaptor.getValue()) + .containsExactlyInAnyOrder(group1, group2); + } + + @Test + public void whenFailingToUpdateGroups_propagateError() { + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void verifyGroupWithPrevInstanceMemberWereReplaced() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void verifyAllGroupsHasPrevInstancesAsMembers() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_PRE_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_PRE_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void assertGroupMembersIds(GroupDefinition group, String ... expectedMembersIds) { + assertThat(group.getMembers()) + .containsValues(expectedMembersIds); + } + + private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) { + GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create(); + Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId)); + groupDefinitionBuilder.setUniqueId(groupId); + return groupDefinitionBuilder.build(); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java new file mode 100644 index 0000000000..0da59d1157 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.utils.TestGenerationUtils.getComponentsUtils; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTargetsUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + + private PolicyTargetsUpdateOperation policyTargetsUpdateOperation; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Captor + private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor; + private PolicyDefinition policy1, policy2, policy3; + private Resource container; + + @Before + public void setUp() throws Exception { + policy1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2"); + policy2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3"); + policy3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3"); + container = new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .addPolicy(policy3) + .setUniqueId(CONTAINER_ID) + .build(); + policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils()); + } + + @Test + public void whenNoPolicies_returnActionOk() { + Component container = new Resource(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoCmptInstancePolicies_returnOk() { + PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build(); + Component container = new ResourceBuilder().addPolicy(policy).build(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.OK); + List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue(); + verifyUpdatedPolicies(updatedPolicies, policy1, policy2);//policy3 does not have "inst2" as target, no update needed + verifyUpdatedPolicyTargets(policy1, "inst1", "inst2New"); + verifyUpdatedPolicyTargets(policy2, "inst1", "inst2New", "inst3"); + } + + @Test + public void whenUpdateOfPoliciesFails_propagateTheFailure() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) { + assertThat(updatedPolicy.resolveComponentInstanceTargets()) + .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds); + } + + private void verifyUpdatedPolicies(List<PolicyDefinition> updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) { + assertThat(updatedPolicies) + .usingElementComparatorOnFields("targets") + .containsExactlyInAnyOrder(expectedUpdatedPolicies); + } + + private PolicyDefinition createPolicyWithCmptInstAsTargets(String uniqueId, String ... instId) { + PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create(); + Stream.of(instId).forEach(policyDefinitionBuilder::addComponentInstanceTarget); + return policyDefinitionBuilder.setUniqueId(uniqueId).build(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java new file mode 100644 index 0000000000..ef239f9a2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PostChangeVersionOperationOrchestratorTest { + + private PostChangeVersionOperationOrchestrator testInstance; + @Mock + private PostChangeVersionOperation postChangeVersionOperation1; + @Mock + private PostChangeVersionOperation postChangeVersionOperation2; + @Mock + private PostChangeVersionOperation postChangeVersionOperation3; + + @Before + public void setUp() throws Exception { + testInstance = new PostChangeVersionOperationOrchestrator(asList(postChangeVersionOperation1, postChangeVersionOperation2, postChangeVersionOperation3)); + } + + @Test + public void whenFirstPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation2, postChangeVersionOperation3); + } + + @Test + public void whenAnyPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation3); + } + + @Test + public void whenLastPostOperationFails_returnTheFailureResult() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void whenAllOperationsSucceeds_returnOk() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + +}
\ No newline at end of file |