diff options
Diffstat (limited to 'catalog-be/src/test/java')
42 files changed, 8913 insertions, 0 deletions
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java new file mode 100644 index 0000000000..272f0d6a1d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.util.EnumMap; + +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AuditingMockManager implements IAuditingManager { + + private static Logger log = LoggerFactory.getLogger(AuditingMockManager.class.getName()); + + public AuditingMockManager(String string) { + // TODO Auto-generated constructor stub + } + + @Override + public void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { + AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); + log.debug("call was made to auditEvent with event type {}", actionEnum.getName()); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java new file mode 100644 index 0000000000..28b60559aa --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.Category; +import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.Tag; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.CategoryData; + +import fj.data.Either; + +public class ElementOperationMock implements IElementOperation { + + CategoryDefinition resourceCategory; + CategoryDefinition serviceCategory; + CategoryDefinition productCategory; + + Category oldService; + + public ElementOperationMock() { + resourceCategory = new CategoryDefinition(); + resourceCategory.setName("Network Layer 2-3"); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(); + subCategoryDefinition.setName("Router"); + SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition(); + subCategoryDefinition1.setName("Gateway"); + + resourceCategory.addSubCategory(subCategoryDefinition); + resourceCategory.addSubCategory(subCategoryDefinition1); + + serviceCategory = new CategoryDefinition(); + serviceCategory.setName("Mobility"); + oldService = new Category(); + oldService.setName("Mobility"); + + productCategory = new CategoryDefinition(); + productCategory.setName("Network Layer 2-31"); + SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition(); + subCategoryDefinition11.setName("Router1"); + GroupingDefinition group = new GroupingDefinition(); + group.setName("group1"); + subCategoryDefinition11.addGrouping(group); + productCategory.addSubCategory(subCategoryDefinition11); + + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() { + + List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>(); + categories.add(resourceCategory); + return Either.left(categories); + + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() { + + List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>(); + categories.add(serviceCategory); + return Either.left(categories); + + } + + /* + * @Override public Either<Category, ActionStatus> getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } } + */ + + @Override + public Either<List<Tag>, ActionStatus> getAllTags() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Integer, ActionStatus> getDefaultHeatTimeout() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { + + List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>(); + switch (nodeType) { + case ResourceNewCategory: + categories.add(resourceCategory); + break; + case ProductCategory: + categories.add(productCategory); + break; + case ServiceNewCategory: + categories.add(serviceCategory); + break; + default: + break; + } + return Either.left(categories); + } + + @Override + public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Map<String, String>, ActionStatus> getResourceTypesMap() { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() { + List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>(); + categories.add(productCategory); + return Either.left(categories); + } + + @Override + public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java new file mode 100644 index 0000000000..5b86b9cc69 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.config.ErrorConfiguration; +import org.openecomp.sdc.be.config.ErrorInfo; +import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.FileChangeCallback; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ErrorConfigurationTest { + ConfigurationSource configurationSource = null; + private static Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class.getName()); + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + } + + @Test + public void testReadConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } + + }); + + ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener); + + assertTrue(testConfiguration != null); + ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND"); + assertTrue(errorInfo != null); + log.debug("{}", testConfiguration); + log.debug("{}", errorInfo); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java new file mode 100644 index 0000000000..d19ae9c872 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.io.IOException; + +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.FileChangeCallback; +import org.openecomp.sdc.common.impl.ConfigFileChangeListener; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestExternalConfiguration<T extends Object> { + + public static void main(String[] args) throws IOException { + + ExternalConfiguration.setAppName("catalog-server"); + ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() { + + @Override + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + + } + }); + + ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); + configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); + + try { + Thread.currentThread().sleep(100 * 1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java new file mode 100644 index 0000000000..a651b77f9a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +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.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.ByteArrayOutputStream; + +public class ZipUtil { + + public static void main(String[] args) { + + String zipFileName = "/src/test/resources/config/config.zip"; + + zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip"; + zipFileName = "src/test/resources/config/config.zip"; + + Path path = Paths.get(zipFileName); + + try { + byte[] zipAsBytes = Files.readAllBytes(path); + // encode to base + + byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); + String decodedStr = new String(decodedMd5); + + zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); + + // String str = new String(zipAsBytes); + + // readZip(str.getBytes()); + readZip(zipAsBytes); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + private static Map<String, byte[]> readZip(byte[] zipAsBytes) { + + Map<String, byte[]> fileNameToByteArray = new HashMap<String, byte[]>(); + + byte[] buffer = new byte[1024]; + ZipInputStream zis = null; + try { + + zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes)); + // get the zipped file list entry + ZipEntry ze = zis.getNextEntry(); + + while (ze != null) { + + String fileName = ze.getName(); + + if (false == ze.isDirectory()) { + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + int len; + while ((len = zis.read(buffer)) > 0) { + os.write(buffer, 0, len); + } + + // aClass.outputStreamMethod(os); + String aString = new String(os.toByteArray(), "UTF-8"); + + fileNameToByteArray.put(fileName, os.toByteArray()); + + } finally { + if (os != null) { + os.close(); + } + } + } + ze = zis.getNextEntry(); + + } + + zis.closeEntry(); + zis.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } finally { + if (zis != null) { + try { + zis.closeEntry(); + zis.close(); + } catch (IOException e) { + // TODO: add log + } + + } + } + + return fileNameToByteArray; + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java new file mode 100644 index 0000000000..dff0e3c729 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.mockito.Mockito.when; + +import java.util.EnumMap; +import java.util.UUID; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; + +public class AuditingManagerTest extends BaseConfDependentTest{ + + @InjectMocks + private AuditingManager auditingManager = Mockito.spy(AuditingManager.class); + public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class); + + public AuditingManagerTest() { + } + + @SuppressWarnings("unchecked") + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); + + } + + @Test + public void testNormalizeEmptyStringValuesAndUuid() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); + + String randomUUID = UUID.randomUUID().toString(); + ThreadLocalsHolder.setUuid(randomUUID); + + auditingManager.auditEvent(auditingFields); + // Checking normalization + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC), Constants.EMPTY_STRING); + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT), Constants.EMPTY_STRING); + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID), randomUUID); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java new file mode 100644 index 0000000000..ad5471e852 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.io.File; + +import org.junit.BeforeClass; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class BaseConfDependentTest { + protected static ConfigurationManager configurationManager; + + @BeforeClass + public static void setupBeforeClass() { + + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + configurationManager = new ConfigurationManager(configurationSource); + + configurationManager.getConfiguration().setTitanInMemoryGraph(true); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java new file mode 100644 index 0000000000..8f3234bc39 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.List; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class ComponentBusinessLogicTest { + ComponentBusinessLogic businessLogic = new ComponentBusinessLogic() { + + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + // TODO Auto-generated method stub + return null; + } + }; + + @Test + public void testGetRequirementsAndCapabilities() { + // businessLogic.getRequirementsAndCapabilities(componentId, + // componentTypeEnum); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java new file mode 100644 index 0000000000..6af338ebcf --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +public class HealthCheckBusinessLogicTest { + + HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); + + @Test + public void checkStausUpdated() { + + boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); + assertFalse("check false", statusChanged); + + List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>(); + List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>(); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, null); + + HealthCheckInfo checkInfoEsUp = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoEsDown = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.DOWN, null, null); + + /* + * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); + */ + + checkInfosLeft.add(checkInfoTitanUp); + checkInfosLeft.add(checkInfoEsUp); + + checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoEsUp); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + checkInfosRight.remove(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.add(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.remove(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.add(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); + assertTrue("check true", statusChanged); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java new file mode 100644 index 0000000000..aea29a6419 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.PropertyConstraint; +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.operations.api.IPropertyOperation; +import org.openecomp.sdc.be.model.operations.api.IResourceOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.EntryData; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; +import junit.framework.Assert; + +public class PropertyBusinessLogicTest { + + private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName()); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final IResourceOperation resourceOperation = Mockito.mock(IResourceOperation.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + PropertyBusinessLogic bl = new PropertyBusinessLogic(); + User user = null; + Resource resourceResponse = null; + ResourceBusinessLogic blResource = new ResourceBusinessLogic(); + PropertyBusinessLogic spy = null; + String resourceId = "resourceforproperty.0.1"; + + public PropertyBusinessLogicTest() { + + } + + @Before + public void setup() { + + 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); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + + // Resource Operation mock methods + // getCount + Either<Integer, StorageOperationStatus> eitherCount = Either.left(0); + when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); + Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); + Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + + Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true)); + when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); + + // // createResource + // resourceResponse = createResourceObject(true); + // Either<Resource, StorageOperationStatus> eitherCreate = + // Either.left(resourceResponse); + // when(resourceOperation.createResource(Mockito.any(Resource.class))).thenReturn(eitherCreate); + + // BL object + // bl = PropertyBusinessLogic.getInstance(servletContext); + // PropertyBusinessLogic spy = PowerMockito.spy(bl); + // when(spy, method(PropertyBusinessLogic.class, "getResource", + // String.class)).withArguments(resource).thenReturn(true); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName("MyResourceName"); + resource.addCategory("Generic", "VoIP"); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + 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("yavivi"); + resource.setIcon("MyIcon.jpg"); + + if (afterCreate) { + resource.setName(resource.getName().toLowerCase()); + resource.setVersion("0.1"); + ; + resource.setUniqueId(resourceId); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + // @Test + public void testHappyScenario() { + + String propertyName = "disk_size"; + PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); + Either<EntryData<String, PropertyDefinition>, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); + + if (either.isRight()) { + Assert.assertFalse(true); + } + Assert.assertEquals(newPropertyDefinition, either.left().value()); + } + + private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { + PropertyDefinition pd = new PropertyDefinition(); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + pd.setConstraints(null); + pd.setDefaultValue("100"); + pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); + pd.setPassword(false); + pd.setRequired(true); + pd.setType("Integer"); + pd.setUniqueId(resourceId + "." + propertyName); + return pd; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java new file mode 100644 index 0000000000..eee5c4dd32 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java @@ -0,0 +1,369 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtilsTest; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.PolicyException; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; + +import fj.data.Either; + +public class ResourceImportManagerTest { + + private static ConfigurationManager configurationManager; + static ResourceImportManager importManager; + static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class); + static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); + static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + static ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class); + static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + static Logger log = Mockito.spy(Logger.class); + + @BeforeClass + public static void beforeClass() throws IOException { + importManager = new ResourceImportManager(); + importManager.setAuditingManager(auditingManager); + when(resourceOperation.getLatestByToscaResourceName(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(Either.left(null)); + importManager.setResponseFormatManager(responseFormatManager); + importManager.setResourceBusinessLogic(resourceBusinessLogic); + importManager.setResourceOperation(resourceOperation); + ResourceImportManager.setLog(log); + + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + Configuration configuration = new Configuration(); + configuration.setTitanInMemoryGraph(true); + configurationManager.setConfiguration(configuration); + } + + @Before + public void beforeTest() { + Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log); + } + + @Test + public void testBasicResourceCreation() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + + User user = new User(); + user.setUserId(resourceMD.getContactId()); + user.setRole("ADMIN"); + user.setFirstName("Jhon"); + user.setLastName("Doh"); + Either<User, ActionStatus> eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + + testSetConstantMetaData(resource); + testSetMetaDataFromJson(resource, resourceMD); + + testSetDerivedFrom(resource); + testSetProperties(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + } + + @Test + public void testResourceCreationFailed() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); + + when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); + setResourceBusinessLogicMock(); + + String jsonContent = "this is an invalid yml!"; + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isRight()); + ResponseFormat errorInfoFromTest = createResource.right().value(); + assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); + assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); + assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); + Mockito.verify(log).debug(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Exception.class)); + // Mockito.verify(log).error(Mockito.anyString(), Mockito.anyString(), + // Mockito.anyString()); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true)); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + + } + + @Test + public void testResourceCreationWithCapabilities() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + testSetCapabilities(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true); + + } + + @Test + public void testResourceCreationWithRequirments() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either<User, ActionStatus> eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + testSetRequirments(createResource.left().value().left); + + } + + private void setResourceBusinessLogicMock() { + when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); + when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean())) + .thenAnswer(new Answer<Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat>>() { + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left(new ImmutablePair<Resource, ActionStatus>((Resource) args[0], ActionStatus.CREATED)); + + } + }); + when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true))) + .thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[1]); + + } + }); + when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean())).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() { + public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + + Either<Boolean, ResponseFormat> either = Either.left(true); + when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); + } + + public ResponseFormat createGeneralErrorInfo() { + ResponseFormat responseFormat = new ResponseFormat(500); + responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); + return responseFormat; + } + + private UploadResourceInfo createDummyResourceMD() { + UploadResourceInfo resourceMD = new UploadResourceInfo(); + resourceMD.setName("tosca.nodes.BlockStorage"); + resourceMD.addSubCategory("Generic", "Infrastructure"); + resourceMD.setContactId("ya107f"); + resourceMD.setResourceIconPath("defaulticon"); + resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); + resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); + return resourceMD; + } + + private void testSetProperties(Resource resource) { + List<PropertyDefinition> propertiesList = resource.getProperties(); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + for (PropertyDefinition propertyDefinition : propertiesList) { + properties.put(propertyDefinition.getName(), propertyDefinition); + } + + assertTrue(properties.size() == 3); + assertTrue(properties.containsKey("size")); + PropertyDefinition propertyDefinition = properties.get("size"); + assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); + assertTrue(propertyDefinition.getConstraints().size() == 1); + PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); + assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); + + assertTrue(properties.containsKey("volume_id")); + propertyDefinition = properties.get("volume_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + assertTrue(properties.containsKey("snapshot_id")); + propertyDefinition = properties.get("snapshot_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + } + + private void testSetCapabilities(Resource resource) { + Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities(); + assertTrue(capabilities.size() == 3); + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); + List<CapabilityDefinition> capabilityList = capabilities.get("tosca.capabilities.Endpoint"); + CapabilityDefinition capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); + assertTrue(capability.getName().equals("data_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); + assertTrue(capability.getName().equals("admin_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + capabilityList = capabilities.get("tosca.capabilities.Container"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Container")); + assertTrue(capability.getName().equals("host")); + + List<String> validSourceTypes = capability.getValidSourceTypes(); + assertTrue(validSourceTypes.size() == 1); + assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); + + } + + private void testSetRequirments(Resource resource) { + Map<String, List<RequirementDefinition>> requirements = resource.getRequirements(); + assertTrue(requirements.size() == 2); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); + List<RequirementDefinition> requirementList = requirements.get("tosca.capabilities.network.Linkable"); + RequirementDefinition requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); + assertTrue(requirement.getName().equals("link")); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); + requirementList = requirements.get("tosca.capabilities.network.Bindable"); + requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); + assertTrue(requirement.getName().equals("binding")); + + } + + private void testSetDerivedFrom(Resource resource) { + assertTrue(resource.getDerivedFrom().size() == 1); + assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); + + } + + private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { + + // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) + // ); + assertTrue(resource.getDescription().equals(resourceMD.getDescription())); + assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); + assertTrue(resource.getName().equals(resourceMD.getName())); + assertTrue(resource.getContactId().equals(resourceMD.getContactId())); + assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); + + // assertTrue( resource.isAbstract() == + // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); + + assertTrue(resourceMD.getTags().size() == resource.getTags().size()); + for (String tag : resource.getTags()) { + assertTrue(resourceMD.getTags().contains(tag)); + } + + } + + private void testSetConstantMetaData(Resource resource) { + assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); + assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); + assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); + assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java new file mode 100644 index 0000000000..9a8f1c5ad8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class ResourceTestUtils { + + public static Resource prepareResource(int resourceIndex) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.addCategory("Generic", "Infrastructure"); + List<String> arr = new ArrayList<String>(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List<String> arr1 = new ArrayList<String>(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } + + public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setToscaResourceName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.setResourceType(resourceType); + r.addCategory("Generic", "Infrastructure"); + List<String> arr = new ArrayList<String>(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List<String> arr1 = new ArrayList<String>(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } + + public static Service prepareService(int serviceIndex) { + Service service = new Service(); + service.setName("service_" + serviceIndex); + service.setDescription("desc"); + service.setIcon("icon-service-red1"); + List<String> tags = new ArrayList<String>(); + tags.add(service.getName()); + service.setTags(tags); + CategoryDefinition category = new CategoryDefinition(); + category.setName("Mobility"); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setContactId("as123y"); + service.setProjectCode("123456"); + + return service; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java new file mode 100644 index 0000000000..fd83af016a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java @@ -0,0 +1,931 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class ServiceBusinessLogicTest { + + private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IAuditingManager iAuditingManager = null; + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + ComponentsUtils componentsUtils = new ComponentsUtils(); + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class); + + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + User user = null; + Service serviceResponse = null; + private static final String CERTIFIED_VERSION = "1.0"; + private static final String UNCERTIFIED_VERSION = "0.2"; + private static final String COMPONNET_ID = "myUniqueId"; + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>(); + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>(); + private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>(); + + public ServiceBusinessLogicTest() { + + } + + @Before + public void setup() { + + 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.SERVICE_OPERATION_MANAGER)).thenReturn(serviceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either<Service, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); + when(serviceOperation.createService(Mockito.any(Service.class))).thenReturn(eitherCreate); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(true); + when(serviceOperation.validateServiceNameExists("Service")).thenReturn(eitherCount); + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(false); + when(serviceOperation.validateServiceNameExists("alreadyExist")).thenReturn(eitherCountExist); + + when(serviceOperation.validateComponentNameExists("alreadyExist")).thenReturn(eitherCountExist); + when(serviceOperation.validateComponentNameExists("Service")).thenReturn(eitherCount); + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setServiceOperation(serviceOperation); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + + componentsUtils.Init(); + componentsUtils.setAuditingManager(auditingManager); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + @Test + public void testGetComponentAuditRecordsCertifiedVersion() { + Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 3); + } + + @Test + public void testGetComponentAuditRecordsUnCertifiedVersion() { + Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 1); + } + + @Test + public void testHappyScenario() { + Service service = createServiceObject(false); + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); + } + + private void assertEqualsServiceObject(Service origService, Service newService) { + assertEquals(origService.getContactId(), newService.getContactId()); + assertEquals(origService.getCategories(), newService.getCategories()); + assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); + assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); + assertEquals(origService.getDescription(), newService.getDescription()); + assertEquals(origService.getIcon(), newService.getIcon()); + assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); + assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getUniqueId(), newService.getUniqueId()); + assertEquals(origService.getVersion(), newService.getVersion()); + assertEquals(origService.getArtifacts(), newService.getArtifacts()); + assertEquals(origService.getCreationDate(), newService.getCreationDate()); + assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); + assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); + assertEquals(origService.getTags(), newService.getTags()); + } + + private void assertResponse(Either<Service, 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()); + } + + /* CREATE validations - start ***********************/ + // Service name - start + + @Test + public void testFailedServiceValidations() { + testServiceNameAlreadyExists(); + testServiceNameEmpty(); + // testServiceNameExceedsLimit(); + testServiceNameWrongFormat(); + testServiceDescriptionEmpty(); + testServiceDescriptionMissing(); + testServiceDescExceedsLimitCreate(); + testServiceDescNotEnglish(); + testServiceIconEmpty(); + testServiceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + // testTagsExceedsLimitCreate(); + // testTagsSingleExcessLimit(); + testTagsNoServiceName(); + testInvalidTag(); + testServiceTagNotExist(); + testServiceTagEmpty(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testContactIdTooLong(); + //testContactIdWrongFormatCreate(); + testResourceContactIdMissing(); + testServiceCategoryExist(); + testServiceBadCategoryCreate(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testInvalidProjectCode(); + //testProjectCodeTooLong(); + //testProjectCodeTooShort(); + testMissingProjectCode(); + } + + private void testServiceNameAlreadyExists() { + String serviceName = "alreadyExist"; + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + serviceExccedsNameLimit.setName(serviceName); + List<String> tgs = new ArrayList<String>(); + tgs.add(serviceName); + serviceExccedsNameLimit.setTags(tgs); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); + } + + private void testServiceNameEmpty() { + Service serviceExccedsNameLimit = createServiceObject(false); + serviceExccedsNameLimit.setName(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceNameExceedsLimit() { + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse"; + serviceExccedsNameLimit.setName(tooLongServiceName); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testServiceNameWrongFormat() { + Service service = createServiceObject(false); + // contains : + String nameWrongFormat = "ljg\fd"; + service.setName(nameWrongFormat); + + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service name - end + // Service description - start + private void testServiceDescriptionEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(""); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescriptionMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescExceedsLimitCreate() { + Service serviceExccedsDescLimit = createServiceObject(false); + // 1025 chars, the limit is 1024 + String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + serviceExccedsDescLimit.setDescription(tooLongServiceDesc); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testServiceDescNotEnglish() { + Service notEnglish = createServiceObject(false); + // Not english + String tooLongServiceDesc = "\uC2B5"; + notEnglish.setDescription(tooLongServiceDesc); + + Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service description - stop + // Service icon - start + private void testServiceIconEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(""); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceIconMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconInvalid() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Service icon - stop + // Service tags - start + private void testTagsExceedsLimitCreate() { + Service serviceExccedsNameLimit = createServiceObject(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(serviceExccedsNameLimit.getName()); + + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExcessLimit() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a"; + String tag2 = serviceExccedsNameLimit.getName(); + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb%#%"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); + + } + + private void testServiceTagNotExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testServiceTagEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(new ArrayList<String>()); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + // Service tags - stop + // Service contactId - start + private void testContactIdTooLong() { + Service serviceContactId = createServiceObject(false); + // 7 chars instead of 6 + String contactIdTooLong = "yrt1234"; + serviceContactId.setContactId(contactIdTooLong); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Service serviceContactId = createServiceObject(false); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + serviceContactId.setContactId(contactIdTooLong); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceContactIdMissing() { + Service resourceExist = createServiceObject(false); + resourceExist.setContactId(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service contactId - stop + // Service category - start + private void testServiceCategoryExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setCategories(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + public void markDistributionAsDeployedTestAlreadyDeployed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String resultAction = "DResult"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>(); + Map<String, Object> params = new HashMap<String, Object>(); + DistributionDeployEvent event = new DistributionDeployEvent(); + + event.setAction(resultAction); + event.setDid(did); + event.setStatus("200"); + // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); + // deployEvent.setFields(params); + resultList.add(event); + Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList); + + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); + + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + + Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); + + } + + @Test + public void markDistributionAsDeployedTestSuccess() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + + } + + @Test + public void markDistributionAsDeployedTestNotDistributed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>(); + Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); + + Either<Service, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND); + Mockito.when(serviceOperation.getService(did)).thenReturn(notFound); + + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isRight()); + assertEquals(404, markDeployed.right().value().getStatus().intValue()); + + } + + private void testServiceBadCategoryCreate() { + + Service serviceExist = createServiceObject(false); + CategoryDefinition category = new CategoryDefinition(); + category.setName("koko"); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + serviceExist.setCategories(categories); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service category - stop + private void testInvalidProjectCode() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("koko"); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testProjectCodeTooLong() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("5555555555555"); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testProjectCodeTooShort() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("555"); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testMissingProjectCode() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode(null); + + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); + } + + @Test + public void testDeleteMarkedServicesNoServices() { + List<String> ids = new ArrayList<String>(); + Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + assertTrue(deleteMarkedResources.left().value().isEmpty()); + + Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); + + } + + @Test + public void testDeleteMarkedServices() { + 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(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + 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(serviceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); + + when(serviceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(serviceOperation.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); + when(serviceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete); + + when(artifactBl.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); + + 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(artifactBl, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); + } + + private Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List<String> tgs = new ArrayList<String>(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + // service.setContactId("ya5467"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug("{}", gson.toJson(service)); + return service; + } + + private void mockAuditingDaoLogic() { + FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); + + final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); + createResourceAudit.setModifier("Carlos Santana(cs0008)"); + createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + createResourceAudit.setCurrVersion("0.1"); + createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); + createResourceAudit.setDesc("OK"); + createResourceAudit.setResourceType("Resource"); + createResourceAudit.setStatus("201"); + createResourceAudit.setPrevVersion(""); + createResourceAudit.setAction("Create"); + // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + // createResourceAudit.setFields(fields); + + final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); + checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); + checkInResourceAudit.setCurrVersion("0.1"); + checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); + checkInResourceAudit.setDesc("OK"); + checkInResourceAudit.setComment("Stam"); + checkInResourceAudit.setResourceType("Resource"); + checkInResourceAudit.setStatus("200"); + checkInResourceAudit.setPrevVersion("0.1"); + checkInResourceAudit.setAction("Checkin"); + // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); + checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); + checkInResourceAudit.setResourceName("MyTestResource"); + + final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); + checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + checkOutResourceAudit.setCurrVersion("0.2"); + checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); + checkOutResourceAudit.setDesc("OK"); + checkOutResourceAudit.setComment(""); + checkOutResourceAudit.setResourceType("Resource"); + checkOutResourceAudit.setStatus("200"); + checkOutResourceAudit.setPrevVersion("0.1"); + checkOutResourceAudit.setAction("Checkout"); + // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + // checkOutResourceAudit.setFields(fields); + + // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>, + // ActionStatus> >() { + // public Either<List<ESTimeBasedEvent>, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either<List<ESTimeBasedEvent>, ActionStatus> either; + // final List<ESTimeBasedEvent> list; + // Object[] args = invocation.getArguments(); + // Map<AuditingFieldsKeysEnum, Object> filterMap = + // (Map<AuditingFieldsKeysEnum, Object>) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList<ESTimeBasedEvent>(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>(); + Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() { + { + add(checkOutResourceAudit); + } + }; + Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { + + DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); + notifyEvent.setAction(notifyAction); + notifyEvent.setDid(did); + notifyEvent.setStatus("200"); + + ResourceAdminEvent requestEvent = new ResourceAdminEvent(); + requestEvent.setAction(requestAction); + requestEvent.setDid(did); + requestEvent.setStatus("200"); + + ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>(); + List<DistributionNotificationEvent> notifyResults = arrayList; + notifyResults.add(notifyEvent); + Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults); + + Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); + + List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>(); + requestResults.add(requestEvent); + Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); + + Either<Service, StorageOperationStatus> eitherService = Either.left(createServiceObject(true)); + Mockito.when(serviceOperation.getService(Mockito.anyString())).thenReturn(eitherService); + + List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>(); + Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java new file mode 100644 index 0000000000..7ad93226c7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class DistributionEngineConfigTest { + + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } + + @Test + public void validateMissingEnvironments() { + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + + String uebPublicKey = "uebPublicKey"; + String uebSecretKey = "uebSecretKey"; + + DistributionEngine distributionEngine = new DistributionEngine(); + + List<String> environments = new ArrayList<String>(); + environments.add("PROD"); + deConfiguration.setEnvironments(environments); + + List<String> servers = new ArrayList<String>(); + servers.add("server1:80"); + servers.add("server2:8080"); + + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); + + ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); + + deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); + deConfiguration.setDistributionStatusTopicName("statusTopic"); + + DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); + distributionStatusTopic.setConsumerGroup("asdc-group"); + distributionStatusTopic.setConsumerId("asdc-id"); + distributionStatusTopic.setFetchTimeSec(20); + distributionStatusTopic.setPollingIntervalSec(20); + deConfiguration.setDistributionStatusTopic(distributionStatusTopic); + + deConfiguration.setUebServers(servers); + deConfiguration.setUebPublicKey(uebPublicKey); + deConfiguration.setUebSecretKey(uebSecretKey); + deConfiguration.setInitMaxIntervalSec(8); + deConfiguration.setInitRetryIntervalSec(3); + + boolean isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebServers(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebServers(servers); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setEnvironments(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setEnvironments(environments); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebPublicKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebPublicKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebSecretKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebSecretKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setDistributionNotifTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setDistributionNotifTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setDistributionStatusTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setDistributionStatusTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setInitMaxIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setInitMaxIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setInitRetryIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setInitRetryIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java new file mode 100644 index 0000000000..b3a254f531 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; +import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class DistributionEngineHealthCheckTest extends BaseConfDependentTest { + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); + + Gson gson = new Gson(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + // + // @Test + // public void validateDownWhenEnvAreDown() { + // + // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + // + // HealthCheckInfo healthCheckInfo = + // distributionEngineClusterHealth.getHealthCheckInfo(); + // assertEquals("verify down", HealthCheckStatus.DOWN, + // healthCheckInfo.getHealthCheckStatus()); + // assertEquals("verify DE component", HealthCheckComponent.DE, + // healthCheckInfo.getHealthCheckComponent()); + // + // } + + @Test + public void validateUpWhenQuerySucceed() { + + // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, + // false); + + CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); + + List<String> uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + + UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + Boolean call1 = healthCheckCall1.call(); + assertTrue("check response okay", call1); + + UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + Boolean call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java new file mode 100644 index 0000000000..de7b84fa82 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; +import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +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; + +import fj.data.Either; + +public class DistributionEngineInitTaskTest { + + @Mock + private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + // public static final IAuditingDao iAuditingDao = + // Mockito.mock(AuditingDao.class); + + @Before + public void setup() { + // ExternalConfiguration.setAppName("distribEngine1"); + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } + + @Test + public void checkIncrement() { + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + + for (int i = 1; i < 5; i++) { + initTask.incrementRetryInterval(); + assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); + } + + initTask.incrementRetryInterval(); + assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); + + } + + @Test + public void testInitFlowScenarioSuccess() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + + } + + @Test + public void testInitFlowScenarioSuccessTopicsAlreadyExists() { + + String envName = "PrOD"; + String notifTopic = "notif"; + String statusTopic = "status"; + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + + Set<String> topics = new HashSet<String>(); + topics.add(realNotifTopic); + topics.add(realStatusTopic); + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either<Set<String>, CambriaErrorResponse> left = Either.left(topics); + + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + try { + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + } catch (Exception e) { + assertTrue("Should not throw exception", false); + } + + } + + @Test + public void testInitFlowScenarioFailToRegister() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.eq(realNotifTopic), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.eq(realStatusTopic), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + @Test + public void testInitFlowScenario1GetTopicsFailed() { + + List<String> uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); + Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + +} 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 new file mode 100644 index 0000000000..0905b8cd19 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +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.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +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; +import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +import fj.data.Either; + +public class ArtifactBusinessLogicTest { + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + static ArtifactsBusinessLogic artifactBL = new ArtifactsBusinessLogic(); + + public static final ArtifactOperation artifactOperation = Mockito.mock(ArtifactOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IInterfaceLifecycleOperation lifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final IUserAdminOperation userOperation = Mockito.mock(IUserAdminOperation.class); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + // 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(); + + @BeforeClass + public static void setup() { + + Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult); + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.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); + + User userJH = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + Either<User, ActionStatus> getUserResult = Either.left(userJH); + + 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); + // when(informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts(Mockito.any(Resource.class))).thenReturn(new + // ArrayList<ArtifactDefinition>()); + } + + 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); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = gson.toJson(ad); + + 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", " 15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + // @Test + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL + // .convertAndValidate(resource, "resourceId", + // gson.toJson(createArtifactDef), "jh0003", null, null, true, + // null, NodeTypeEnum.Resource); + // + // 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/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java new file mode 100644 index 0000000000..776fe8864e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.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 org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; +import org.openecomp.sdc.be.components.impl.CommonImportManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +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; + +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); + + @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(); + } + + @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()); + + 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())); + } + + } + + 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 new file mode 100644 index 0000000000..05fc6a2948 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.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 org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CategoriesImportManager; +import org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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(new Answer<Either<CategoryDefinition, ActionStatus>>() { + public Either<CategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<CategoryDefinition, ActionStatus> ans = Either.left((CategoryDefinition) args[0]); + 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/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java new file mode 100644 index 0000000000..135caf2c82 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.components.impl.CompositionBusinessLogic; +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; + +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); + } +} 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 new file mode 100644 index 0000000000..84c8286f14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.CsarValidationUtils; + +public class CsarValidationUtilsTest { + 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))); + } +} 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 new file mode 100644 index 0000000000..6dd19cce57 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -0,0 +1,509 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +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 java.util.function.Function; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; +import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.yaml.snakeyaml.Yaml; + +import fj.data.Either; + +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 testCreateFullHeatParameterModuleWithMissingFields() { + + 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); + + 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); + + } + + @Test + public void testGetAttributesFromYml() throws IOException { + + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); + Either<Map<String, AttributeDefinition>, 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 { + + 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, AttributeDefinition> actual) { + + Map<String, Object> singleExpectedAttribute; + AttributeDefinition 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()); + + 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()); + + } + + } + + 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()) { + + 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()); + + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + + } + + } + + 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()); + + } + + 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/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java new file mode 100644 index 0000000000..6ba74ec133 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.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 org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CommonImportManager; +import org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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; + +public class InterfaceLifecycleTypeImportManagerTest { + + @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); + + static Logger log = Mockito.spy(Logger.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; + } + + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } + + @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()); + + } + + 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/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java new file mode 100644 index 0000000000..5a503dc97c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -0,0 +1,1423 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +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; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +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.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.CsarOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +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"; + + 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"; + + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IAuditingManager iAuditingManager = null; + IElementOperation mockElementDao; + TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + final ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.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; + ComponentsUtils componentsUtils = new ComponentsUtils(); + ArtifactsBusinessLogic artifactManager = Mockito.mock(ArtifactsBusinessLogic.class); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + + 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.AUDITING_MANAGER)).thenReturn(iAuditingManager); + when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + // Resource Operation mock methods + // getCount + /* + * Either<Integer, StorageOperationStatus> eitherCount = Either.left(0); when(resourceOperation.getNumberOfResourcesByName("MyResourceName")). thenReturn(eitherCount); Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1); + * when(resourceOperation.getNumberOfResourcesByName("alreadyExist")). thenReturn(eitherCountExist); + */ + Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(false); + when(resourceOperation.validateResourceNameExists(ValidationUtils.normaliseComponentName("Root"), ResourceTypeEnum.VFC)).thenReturn(eitherFalse); + + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(false); + when(resourceOperation.validateResourceNameExists("alreadyExists", ResourceTypeEnum.VFC)).thenReturn(eitherCountExist); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(true); + when(resourceOperation.validateResourceNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC)).thenReturn(eitherCount); + + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(false); + when(resourceOperation.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(true); + when(resourceOperation.validateToscaResourceNameExists(ValidationUtils.normaliseComponentName("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); + + ArtifactDefinition artifactDef = new ArtifactDefinition(); + artifactDef.setUniqueId("123.123"); + Either<ArtifactDefinition, StorageOperationStatus> returnEither = Either.left(artifactDef); + when(artifactManager.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyBoolean())).thenReturn(returnEither); + + // createResource + resourceResponse = createResourceObject(true); + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); + Either<List<ResourceMetadataData>, StorageOperationStatus> eitherValidate = Either.left(null); + when(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate); + when(resourceOperation.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setResourceOperation(resourceOperation); + 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); + + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either<Resource, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); + when(resourceOperation.getResource(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + when(resourceOperation.getLatestResourceByCsarOrName(resourceCsar.getCsarUUID(), resourceCsar.getSystemName())).thenReturn(oldResourceRes); + when(resourceOperation.updateResource(Mockito.any(Resource.class), Mockito.anyBoolean())).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); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + 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.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); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + 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, 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, 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(); + // testTagsSingleExceedsLimit(); + testTagsNoServiceName(); + testInvalidTag(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testContactIdTooLong(); + //testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); + + } + + // Resource tags - stop + // Resource contact info start + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 7 chars instead of 6 + String contactIdTooLong = "yrt1234"; + resourceContactId.setContactId(contactIdTooLong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, 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 + String contactIdTooLong = "yrt134"; + resourceContactId.setContactId(contactIdTooLong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, 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, 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, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(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, 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, 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, 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, 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, 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, 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(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, 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, 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, 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, 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, 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, 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + ; + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Test + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).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, 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + + 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); + } + + // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed +// @Test +// public void testContactIdWrongFormat_UPDATE() { +// Resource resource = createResourceObject(true); +// Resource updatedResource = createResourceObject(true); +// +// // this is in order to prevent failing with 403 earlier +// Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); +// // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); +// when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); +// +// String resourceId = resource.getUniqueId(); +// // 3 letters and 3 digits +// String contactIdTooLong = "yrt134"; +// updatedResource.setContactId(contactIdTooLong); +// 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List<String> list = null; + updatedResource.setDerivedFrom(list); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList<String>()); + + 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + + 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() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + resource.setVersion("1.0"); + ; + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); + when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult); + when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + 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, 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); + when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult); + when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).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); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + 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<Resource, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(resourceOperation.getLatestByName(resourceToUpdtae.getName(), true)).thenReturn(getLatestResult); + + Either<Resource, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(resourceOperation.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName(), true)).thenReturn(getLatestResult); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(0)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + 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); + + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + + @Test + public void testDeleteMarkedResourcesNoResources() { + List<String> ids = new ArrayList<String>(); + Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(resourceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + assertTrue(deleteMarkedResources.left().value().isEmpty()); + + 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(resourceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + 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(resourceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); + + when(resourceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(resourceOperation.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); + when(resourceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete); + + when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); + + 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); + } + +} 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 new file mode 100644 index 0000000000..d1597886d8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -0,0 +1,284 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.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 org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +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); + + 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(ComponentInstanceBusinessLogic.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)).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)).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)).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.anyBoolean())).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)); + + } + + @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); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + 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); + + List<HeatParameterDefinition> heatParameters = heatDefinition.getHeatParameters(); + assertNotNull(heatParameters); + + List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getHeatParameters(); + assertNotNull(heatEnvParameters); + + 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()); + + 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); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + 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.getHeatParameters(); + assertNull(heatParameters); + + List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getHeatParameters(); + assertNull(heatEnvParameters); + + } + + @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); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + 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.anyBoolean()); + } + + 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.setHeatParameters(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/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java new file mode 100644 index 0000000000..48cd83a7c8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CertificationChangeTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CertificationChangeTransitionTest extends LifecycleTestBase { + + private CertificationChangeTransition certifyTransitionObj = null; + private CertificationChangeTransition certificationCancelObj = null; + private CertificationChangeTransition certificationFailObj = null; + + private ComponentsUtils componentsUtils = new ComponentsUtils(); + private String resourceName = "myResource"; + private User owner = null; + + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class); + + Resource resource; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + + super.setup(); + componentsUtils.Init(); + // checkout transition object + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certifyTransitionObj.setConfigurationManager(configurationManager); + + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certificationCancelObj.setConfigurationManager(configurationManager); + + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certificationFailObj.setConfigurationManager(configurationManager); + + owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + when(artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + resource = createResourceObject(false); + } + + @Test + public void testStateValidationSuccess() { + + Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testStateValidationFail() { + + // checkout + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + assertValidationStateErrorResponse(validateBeforeTransition); + + // checkin + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertValidationStateErrorResponse(validateBeforeTransition); + + // rfc + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertValidationStateErrorResponse(validateBeforeTransition); + + // certified + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertValidationStateErrorResponse(validateBeforeTransition); + + } + + @Test + public void testRolesFail() { + Either<Resource, ResponseFormat> changeStateResult; + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRolesSuccess() { + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.ADMIN.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + } + + private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) { + assertEquals(validateBeforeTransition.isRight(), true); + ResponseFormat error = validateBeforeTransition.right().value(); + Either<Resource, ResponseFormat> changeStateResult = Either.right(error); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java new file mode 100644 index 0000000000..b45aa61de1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java @@ -0,0 +1,230 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CertificationRequestTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.tosca.ToscaError; +import org.openecomp.sdc.be.tosca.ToscaExportHandler; +import org.openecomp.sdc.be.tosca.ToscaRepresentation; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CertificationRequestTest extends LifecycleTestBase { + + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + protected ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = Mockito.mock(ServiceDistributionArtifactsBuilder.class); + protected ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class); + protected ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class); + protected CapabilityOperation capabilityOperation = Mockito.mock(CapabilityOperation.class); + protected ToscaExportHandler toscaExportUtils = Mockito.mock(ToscaExportHandler.class); + @InjectMocks + private CertificationRequestTransition rfcObj = new CertificationRequestTransition(componentsUtils, lcOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils); + + protected ToscaRepresentation toscaRepresentation = Mockito.mock(ToscaRepresentation.class); + + @Before + public void setup() { + Mockito.reset(resourceOperation); + MockitoAnnotations.initMocks(this); + super.setup(); + + // checkout transition object + rfcObj.setLifeCycleOperation(lcOperation); + // checkoutObj.setAuditingManager(iAuditingManager); + rfcObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation); + when(toscaExportUtils.exportComponent(Mockito.anyObject())).thenReturn(either); + + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testAlreadyRfc() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testAlreadyCertified() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { + Resource resource = new Resource(); + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { + Resource resource = new Resource(); + List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); + ComponentInstance ri = new ComponentInstance(); + ri.setComponentVersion("2.0"); + riList.add(ri); + resource.setComponentInstances(riList); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { + Resource resource = createVFWithRI("0.3"); + + simulateCertifiedVersionExistForRI(); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { + Resource resource = createVFWithRI("1.3"); + + simulateCertifiedVersionExistForRI(); + + Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + private void simulateCertifiedVersionExistForRI() { + Resource dummyResource = new Resource(); + Either<List<Resource>, StorageOperationStatus> result = Either.left(new ArrayList<Resource>() { + { + add(dummyResource); + } + }); + Mockito.when(resourceOperation.getResource(Mockito.anyString())).thenReturn(Either.left(dummyResource)); + Mockito.when(resourceOperation.findLastCertifiedResourceByUUID(Mockito.any(Resource.class))).thenReturn(result); + } + + private Resource createVFWithRI(String riVersion) { + Resource resource = new Resource(); + List<ComponentInstance> riList = new ArrayList<ComponentInstance>(); + ComponentInstance ri = new ComponentInstance(); + + ri.setComponentVersion(riVersion); + ri.setComponentUid("someUniqueId"); + riList.add(ri); + resource.setComponentInstances(riList); + return resource; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java new file mode 100644 index 0000000000..e0d942e2bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.lifecycle.CheckinTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CheckinTest extends LifecycleTestBase { + + private CheckinTransition checkinObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + checkinObj = new CheckinTransition(componentsUtils, lcOperation); + checkinObj.setLifeCycleOperation(lcOperation); + checkinObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + } + + @Test + public void testSimpleCheckin() { + Either<Boolean, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testSimpleServiceCheckin() { + Either<Boolean, ResponseFormat> changeStateResult; + Service service = createServiceObject(false); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testCheckinTwiceValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(owner.isLeft()); + // changeStateResult = checkinObj.changeStateOperation(resource, user, + // owner.left().value()); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckinTwiceValidation() { + Either<Service, ResponseFormat> changeStateResult; + Service service = createServiceObject(false); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(owner.isLeft()); + + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCheckoutByAnotherUserValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkinObj.changeStateOperation(resource, + // modifier, owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckoutByAnotherUserValidation() { + Either<Service, ResponseFormat> changeStateResult; + Service service = createServiceObject(false); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java new file mode 100644 index 0000000000..4a81653e14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CheckoutTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CheckoutTest extends LifecycleTestBase { + + private CheckoutTransition checkoutObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + checkoutObj = new CheckoutTransition(componentsUtils, lcOperation); + checkoutObj.setLifeCycleOperation(lcOperation); + checkoutObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testAlreadyCheckout() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testReadyForCertification() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // if modifier = owner + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // else + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + + // admin + modifier.setRole(Role.ADMIN.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // designer + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRoles() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isLeft(), true); + + modifier.setRole(Role.TESTER.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java new file mode 100644 index 0000000000..734a3d9bde --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.AuditingMockManager; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; +import junit.framework.Assert; + +public class LifecycleTestBase { + private static Logger log = LoggerFactory.getLogger(LifecycleTestBase.class.getName()); + @InjectMocks + protected final ServletContext servletContext = Mockito.mock(ServletContext.class); + protected IAuditingManager iAuditingManager = null; + protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + protected LifecycleOperation lcOperation = Mockito.mock(LifecycleOperation.class); + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; + protected User user = null; + protected Resource resourceResponse; + protected Service serviceResponse; + protected ConfigurationManager configurationManager = null; + protected ResponseFormatManager responseManager = null; + + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + + // Init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + // Auditing + iAuditingManager = new AuditingMockManager("lll"); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + // when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(LifecycleOperation.class)).thenReturn(lcOperation); + when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); + + // Resource Operation mock methods + // getCount + + // createResource + resourceResponse = createResourceObject(true); + serviceResponse = createServiceObject(true); + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); + Either<? extends Component, StorageOperationStatus> eitherCreateComponent = Either.left(resourceResponse); + when((Either<Resource, StorageOperationStatus>) lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + when(lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent)); + + when((Either<Resource, StorageOperationStatus>) lcOperation.checkinComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + + when((Either<Resource, StorageOperationStatus>) lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + when(lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Component.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent)); + + Either<User, StorageOperationStatus> getOwnerResult = Either.left(user); + when(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Boolean.class))).thenReturn(getOwnerResult); + when(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.any(Boolean.class))).thenReturn(getOwnerResult); + + responseManager = ResponseFormatManager.getInstance(); + + } + + public static <T> Answer<T> createAnswer(final T value) { + Answer<T> dummy = new Answer<T>() { + @Override + public T answer(InvocationOnMock invocation) throws Throwable { + return value; + } + + }; + return dummy; + } + + protected Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName("MyResourceName"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + 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("yavivi"); + resource.setIcon("MyIcon.jpg"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + protected Service createServiceObject(boolean b) { + Service service = new Service(); + service.setName("MyServiceName"); + service.addCategory("VoIP", null); + service.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + service.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + service.setContactId("aa0001"); + service.setIcon("MyIcon.jpg"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(service)); + return service; + } + + protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + Assert.assertTrue(createResponse.isRight()); + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + Assert.assertTrue(createResponse.isRight()); + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + protected 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/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java new file mode 100644 index 0000000000..6cc0385667 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.lifecycle.UndoCheckoutTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class UndoCheckoutTest extends LifecycleTestBase { + + private UndoCheckoutTransition undoCheckoutObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, lcOperation); + undoCheckoutObj.setLifeCycleOperation(lcOperation); + undoCheckoutObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + } + + @Test + public void testResourceNotCheckedOutValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testDifferentResourceOwnerValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java new file mode 100644 index 0000000000..104cd14e7a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.distribution; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.core.Response; + +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; +import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.distribution.AuditHandler; +import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; +import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; +import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; +import org.openecomp.sdc.common.datastructure.Wrapper; + +public class DistributionBusinessLogicTest extends BaseConfDependentTest { + + @InjectMocks + DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class); + + CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + AuditHandler auditHandler = Mockito.mock(AuditHandler.class); + + @Test + public void testHandleRegistrationHappyScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity(); + + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + } + + @Test + public void testHandleRegistrationFailedScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, HttpStatus.SC_SERVICE_UNAVAILABLE); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + + Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); + Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) + .thenReturn(errorResponse); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + } + + @Test + public void testHandleUnRegistrationHappyScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + + Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); + + Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + + } + + @Test + public void testHandleUnRegistrationFailedScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) + .thenReturn(errorResponse); + + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.AUTHENTICATION_ERROR); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + + } + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + Mockito.reset(cambriaHandler); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java new file mode 100644 index 0000000000..d6274ad90e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.distribution.servlet; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.http.HttpStatus; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.distribution.AuditHandler; +import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; +import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; +import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; +import org.openecomp.sdc.be.distribution.servlet.DistributionServlet; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class DistributionServletTest extends JerseyTest { + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class); + public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); + + public static final String ENV_NAME = "myEnv"; + public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification"; + public static final String STATUS_TOPIC = ENV_NAME + "_Status"; + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic); + when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine); + when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK); + when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK); + + mockBusinessLogicResponse(); + + } + + private static void mockBusinessLogicResponse() { + // Mock Register + Mockito.doAnswer(new Answer<Object>() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + + // Mock Unregister + Mockito.doAnswer(new Answer<Object>() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + } + + @Test + public void registerSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); + Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Test + public void unRegisterSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); + Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(DistributionServlet.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java new file mode 100644 index 0000000000..e4f46dd4dd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.ecomp; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.common.config.EcompClassification; +import org.openecomp.sdc.common.config.EcompErrorCode; +import org.openecomp.sdc.common.config.EcompErrorEnum; +import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv; + +import static org.junit.Assert.assertTrue; + +public class GenerateEcompErrorFileTest { + + @Test + public void verifyNoDuplicatesInEcompErrorCodes() { + + EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); + + Map<EcompErrorCode, List<EcompClassification>> map = new HashMap<EcompErrorCode, List<EcompClassification>>(); + for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) { + + List<EcompClassification> list = map.get(ecompErrorEnum.getEcompErrorCode()); + if (list == null) { + list = new ArrayList<>(); + + list.add(ecompErrorEnum.getClassification()); + + map.put(ecompErrorEnum.getEcompErrorCode(), list); + } else { + if (list.contains(ecompErrorEnum.getClassification())) { + assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false); + } else { + list.add(ecompErrorEnum.getClassification()); + } + + } + + } + + } + + @Test + public void generateEcompErrorFileInTarget() { + + GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); + boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false); + assertTrue("check result from file generation", result); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java new file mode 100644 index 0000000000..d41e95da9d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; +import org.apache.commons.codec.binary.Base64; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +import static org.mockito.Mockito.mock; + +public class AbstractValidationsServletTest { + private static AbstractValidationsServlet servlet = mock(AbstractValidationsServlet.class); + + @SuppressWarnings("unchecked") + @Test + public void testGetScarFromPayload() { + + String payloadName = "valid_vf.csar"; + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + Either<Map<String, byte[]>, ResponseFormat> returnValue = null; + try { + path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + UploadResourceInfo resourceInfo = new UploadResourceInfo(); + resourceInfo.setPayloadName(payloadName); + resourceInfo.setPayloadData(payloadData); + Method privateMethod = null; + privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload", UploadResourceInfo.class); + privateMethod.setAccessible(true); + returnValue = (Either<Map<String, byte[]>, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo); + } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + Assert.assertTrue(returnValue.isLeft()); + Map<String, byte[]> csar = returnValue.left().value(); + Assert.assertTrue(csar != null); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java new file mode 100644 index 0000000000..2dda0f5d14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import java.util.HashSet; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Application; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.mockito.Mockito; +import org.openecomp.sdc.be.servlets.ResourceUploadServlet; + +public class ApplicationConfig extends Application { + + public Set<Class<?>> getClasses() { + final Set<Class<?>> resources = new HashSet<Class<?>>(); + + // Add your resources. + resources.add(ResourceUploadServlet.class); + resources.add(MultiPart.class); + resources.add(FormDataContentDisposition.class); + + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + ResourceConfig resourceConfig = ResourceConfig.forApplication(this); + + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // TODO Auto-generated method stub + bind(request).to(HttpServletRequest.class); + } + }); + + return resources; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java new file mode 100644 index 0000000000..5e1e4577e2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.Arrays; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.ResourcesServlet; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class ResourceServletTest extends JerseyTest { + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); + final static HttpSession session = Mockito.mock(HttpSession.class); + final static ServletContext servletContext = Mockito.mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either<User, ActionStatus> eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + + ImmutablePair<Resource, ActionStatus> pair = new ImmutablePair<Resource, ActionStatus>(new Resource(), ActionStatus.OK); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> ret = Either.left(pair); + when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(ret); + + } + + @Before + public void beforeTest() { + Mockito.reset(componentUtils); + + Mockito.doAnswer(new Answer<ResponseFormat>() { + public ResponseFormat answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + ActionStatus action = (ActionStatus) args[0]; + ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value()); + return resp; + } + }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class)); + + } + + @Test + public void testHappyScenarioTest() { + UploadResourceInfo validJson = buildValidJson(); + setMD5OnRequest(true, validJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK); + assertTrue(response.getStatus() == HttpStatus.CREATED.value()); + + } + + @Test + public void testNonValidMd5Fail() { + UploadResourceInfo validJson = buildValidJson(); + + setMD5OnRequest(false, validJson); + + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + + } + + @Test + public void testNonValidPayloadNameFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadName("myCompute.xml"); + + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + + } + + @Test + public void testNullPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadData(null); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD); + + } + + @Test + public void testNonYmlPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + String payload = "{ json : { isNot : yaml } "; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE); + + } + + @Test + public void testNonToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE); + + } + + @Test + public void testServiceToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n" + + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); + + } + + @Test + public void testMultipleResourcesInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE); + + } + + @Test + public void testNonValidNameSpaceInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE); + + } + + private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) { + Base64.encodeBase64(payload.getBytes()); + mdJson.setPayloadData(payload); + } + + private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) { + setMD5OnRequest(true, mdJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) { + String md5 = (isValid) ? GeneralUtility.calculateMD5ByString(gson.toJson(json)) : "stam="; + when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + + } + + private UploadResourceInfo buildValidJson() { + UploadResourceInfo ret = new UploadResourceInfo(); + ret.setName("MyCompute"); + ret.setPayloadName("MyCompute.yml"); + ret.addSubCategory("Application Layer 4+", "Application Servers"); + ret.setDescription("ResourceDescription"); + ret.setVendorName("VendorName"); + ret.setVendorRelease("VendorRelease"); + ret.setContactId("AT1234"); + ret.setIcon("router"); + ret.setTags(Arrays.asList(new String[] { "MyCompute" })); + ret.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); + return ret; + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(ResourcesServlet.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java new file mode 100644 index 0000000000..252e9d8fbc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.resources.api.IResourceUploader; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.servlets.ResourceUploadServlet; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; + +public class ResourceUploadServletTest extends JerseyTest { + private static Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class.getName()); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpSession session = Mockito.mock(HttpSession.class); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class); + final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class); + + Gson gson = new Gson(); + + public void zipDirectory() { + + } + + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader); + when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK); + when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager); + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(ResourceUploadServlet.class); + + resourceConfig.register(MultiPartFeature.class); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }); + + return resourceConfig; + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + public class DelegatingServletInputStream extends ServletInputStream { + + private final InputStream sourceStream; + + /** + * Create a DelegatingServletInputStream for the given source stream. + * + * @param sourceStream + * the source stream (never <code>null</code>) + */ + public DelegatingServletInputStream(InputStream sourceStream) { + // Assert.notNull(sourceStream, + // "Source InputStream must not be null"); + this.sourceStream = sourceStream; + } + + /** + * Return the underlying source stream (never <code>null</code>). + */ + public final InputStream getSourceStream() { + return this.sourceStream; + } + + public int read() throws IOException { + return this.sourceStream.read(); + } + + public void close() throws IOException { + super.close(); + this.sourceStream.close(); + } + + } + + @Test + public void testMultipart() { + FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip")); + + List<String> tags = new ArrayList<String>(); + tags.add("tag1"); + tags.add("tag2"); + UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null); + + FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + multipartEntity.bodyPart(metadataPart); + + Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + log.debug("{}", response); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java new file mode 100644 index 0000000000..420cbcca6b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.grizzly.http.util.HttpStatus; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.TypesUploadServlet; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.web.context.WebApplicationContext; + +import fj.data.Either; + +public class TypesUploadServletTest extends JerseyTest { + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either<User, ActionStatus> eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); + when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); + + } + + @Test + public void creatingCapabilityTypeSuccessTest() { + List<CapabilityTypeDefinition> emptyList = new ArrayList<CapabilityTypeDefinition>(); + Either<List<CapabilityTypeDefinition>, ResponseFormat> either = Either.left(emptyList); + when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either); + FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", new File("src/test/resources/types/capabilityTypes.zip")); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + + Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + + assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode()); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @Override + protected Application configure() { + ResourceConfig resourceConfig = new ResourceConfig(TypesUploadServlet.class); + + resourceConfig.register(MultiPartFeature.class); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java new file mode 100644 index 0000000000..ed69f104d2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Application; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.BeforeClass; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.UserAdminServlet; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; + +import fj.data.Either; + +public class UserAdminServletTest extends JerseyTest { + + final static HttpServletRequest request = mock(HttpServletRequest.class); + final static HttpSession session = mock(HttpSession.class); + final static ServletContext servletContext = mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class); + final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class); + final static AuditingManager auditingManager = mock(AuditingManager.class); + final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + final static ResponseFormat okResponseFormat = mock(ResponseFormat.class); + + final static String ADMIN_ATT_UID = "jh0003"; + Gson gson = new Gson(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + + when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager); + when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils); + when(componentsUtils.getAuditingManager()).thenReturn(auditingManager); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat); + when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value()); + + } + + @Before + public void beforeTest() { + reset(userAdminManager); + doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false); + + reset(request); + when(request.getSession()).thenReturn(session); + when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID); + } + + /* + * @Test public void deactivateUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); Either<User, ActionStatus> eitherActiveUser = buildEitherUser(userToDeleteUserId, true); + * User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either<User, ActionStatus> eitherInactiveUser = buildEitherUser(userToDeleteUserId, false); doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser( adminUser, userToDelete.getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(1)).deActivateUser(adminUser, userToDelete.getUserId()); } + * + * + * @Test public void forceDeleteUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User. FORCE_DELETE_HEADER_FLAG); + * + * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); + * + * Either<User, ActionStatus> eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either<User, ActionStatus> eitherUser = buildEitherUser(userToDeleteUserId, true); doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete. getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(0)).deActivateUser(adminUser, userToDelete.getUserId()); + * verify(userAdminManager, times(1)).deleteUser(userToDelete.getUserId()); } + */ + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class); + + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } + + private static Either<User, ActionStatus> buildEitherUser(String userId, boolean isActive) { + User user = new User(); + user.setUserId(userId); + user.setRole(UserRoleEnum.ADMIN.getName()); + if (!isActive) { + user.setStatus(UserStatusEnum.INACTIVE); + } + return Either.left(user); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java new file mode 100644 index 0000000000..4b01b4fd61 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.user; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IUsersDAO; +import org.openecomp.sdc.be.dao.impl.Neo4jUsersDAO; +import org.openecomp.sdc.be.resources.data.UserData; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class UserAdminManagerTest { + + final IUsersDAO usersDao = Mockito.mock(Neo4jUsersDAO.class); + Gson gson; + + @Before + public void setup() { + Either<UserData, ActionStatus> eitherOk = Either.right(ActionStatus.OK); + gson = new GsonBuilder().setPrettyPrinting().create(); + when(usersDao.getUserData(anyString())).thenReturn(eitherOk); + when(usersDao.saveUserData((UserData) anyObject())).thenReturn(ActionStatus.OK); + when(usersDao.updateUserData((UserData) anyObject())).thenReturn(ActionStatus.OK); + when(usersDao.deleteUserData(anyString())).thenReturn(ActionStatus.OK); + } + + // @Test + // public void testCreateUser() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": + // \"jb1234u@sdc.com\",\"role\": \"ADMIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either<UserData,ActionStatus> either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.OK, either.right().value()); + // } + // + // + // @Test + // public void testCreateUserInvalidEmail() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": \"@sdc.com\",\"role\": + // \"ADMIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either<UserData,ActionStatus> either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.INVALID_EMAIL_ADDRESS, either.right().value()); + // } + // + // @Test + // public void testCreateUserInvalidRole() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": + // \"jb1234u@sdc.com\",\"role\": \"MIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either<UserData,ActionStatus> either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.INVALID_EMAIL_ADDRESS, either.right().value()); + // } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java new file mode 100644 index 0000000000..bf87033bfe --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java @@ -0,0 +1,437 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.transaction.mngr; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; +import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.transaction.api.IDBAction; +import org.openecomp.sdc.common.transaction.api.RollbackHandler; +import org.openecomp.sdc.common.transaction.api.TransactionUtils; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.ActionTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; +import org.openecomp.sdc.common.transaction.mngr.CommitManager; +import org.openecomp.sdc.common.transaction.mngr.TransactionSdncImpl; +import org.slf4j.Logger; + +import fj.data.Either; + +public class SdncTransactionTest { + private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); + private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static Logger log = Mockito.spy(Logger.class); + private static int transactionId = 0; + private static ConfigurationManager configurationManager; + + public enum TestAction { + TitanAction, Rollback, GeneralAction + } + + public enum TestResponse { + TitanResponseSuccess, GeneralSuccess + } + + @BeforeClass + public static void beforeClass() { + TransactionSdncImpl.setLog(log); + CommitManager.setLog(log); + RollbackHandler.setLog(log); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + } + + @Before + public void beforeTest() { + reset(log); + reset(esCatalogDao); + reset(titanGenericDao); + } + + @Test + public void testInvokeTitanAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testInvokeESAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testfinishTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + } + + @Test + public void testFinishOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + TransactionCodeEnum finishTransaction = tx.finishTransaction(); + assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED); + // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, + // transactionId, TransactionStatusEnum.CLOSED.name(), + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testCallingLastActionTwice() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doBasicTitanAction(transactionId, tx, true, true); + Either<TestResponse, TransactionCodeEnum> doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false); + assertTrue(doBasicTitanAction.isRight()); + assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION, + // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testActionOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + Either<DBActionCodeEnum, TransactionCodeEnum> eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + assertTrue(eitherESResult.isRight()); + assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either<Object, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + assertTrue(eitherTitanResult.isRight()); + assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either<Object, TransactionCodeEnum> eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess), + createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess)); + assertTrue(eitherGeneralDBAction.isRight()); + assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + @Test + public void testBasicHappyScenario() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doFinishTransaction(transactionId, tx, true); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testRollbackSucceededOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String crushMessage = "DB Crush Simulation"; + Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED); + String crushMessage = "DB Crush Simulation"; + Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackSucceededOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String esError = "No Connection to Es"; + Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString()); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, + // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, + // DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testInvokeGeneralAction() { + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess); + IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess); + String crushMessage = "No DB Connection"; + IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage); + + Either<TestResponse, TransactionCodeEnum> eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction); + assertTrue(eitherResult.isLeft()); + assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction); + + assertTrue(eitherResult.isRight()); + assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + private Either<TestResponse, TransactionCodeEnum> doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Add Titan Action + Either<TestResponse, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherTitanResult.isLeft()); + assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess); + verify(log).debug(TestAction.TitanAction.name()); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + return eitherTitanResult; + } + + private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) { + // Prerequisite finishTransaction + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + if (isVerifyAction) { + // Check finishTransaction + verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(transactionCode == TransactionCodeEnum.SUCCESS); + } + return transactionCode; + } + + private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Prerequisite ES Action + Either<ESArtifactData, ResourceUploadStatus> eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST); + when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact); + + // Add ES Action + Either<DBActionCodeEnum, TransactionCodeEnum> eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherEsAction.isLeft()); + assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + } + + private ESArtifactData createDummyArtifactData() { + String strData = "qweqwqweqw34e4wrwer"; + String myNodeType = "MyNewNodeType"; + ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes()); + return arData; + } + + private void verifyNoErrorsInLog() { + verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).error(Mockito.anyString()); + } + + private void verifyNoInfoInLog() { + verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).info(Mockito.anyString()); + } + + private IDBAction createBasicAction(TestAction action, TestResponse resp) { + final TestAction finalAction = action; + final TestResponse finalResp = resp; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + return finalResp; + } + }; + } + + private IDBAction createCrushingAction(TestAction action, final String crushMessage) { + final TestAction finalAction = action; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + throw new RuntimeException(crushMessage); + } + }; + } + + public int getNextTransactionId() { + transactionId++; + return transactionId; + } +} |