diff options
author | Michael Lando <ml636r@att.com> | 2018-03-04 14:53:33 +0200 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2018-03-07 13:19:05 +0000 |
commit | a5445100050e49e83f73424198d73cd72d672a4d (patch) | |
tree | cacf4df817df31be23e4e790d1dda857bdae061e /catalog-be/src/test/java | |
parent | 51157f92c21976cba4914c378aaa3cba49826931 (diff) |
Sync Integ to Master
Change-Id: I71e3acc26fa612127756ac04073a522b9cc6cd74
Issue-ID: SDC-977
Signed-off-by: Gitelman, Tal (tg851x) <tg851x@intl.att.com>
Diffstat (limited to 'catalog-be/src/test/java')
164 files changed, 21487 insertions, 9666 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 deleted file mode 100644 index 272f0d6a1d..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============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 index 45b2317cd6..2088e8071a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java @@ -20,10 +20,7 @@ package org.openecomp.sdc; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; 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; @@ -38,228 +35,230 @@ 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; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; 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; - } + 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 index 5b86b9cc69..7f5b7f9853 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java @@ -20,10 +20,6 @@ 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; @@ -37,41 +33,45 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; + +import static org.junit.Assert.assertTrue; + public class ErrorConfigurationTest { - ConfigurationSource configurationSource = null; - private static Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class.getName()); + ConfigurationSource configurationSource = null; + private static final Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class); - @Before - public void setup() { + @Before + public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - } + } - @Test - public void testReadConfigurationFile() { + @Test + public void testReadConfigurationFile() { - ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { + ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { - public void reconfigure(BasicConfiguration obj) { - // TODO Auto-generated method stub - log.debug("In reconfigure of {}", obj); - } + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } - }); + }); - ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener); + 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); + 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 index f9819c72e5..4698c0eea9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java @@ -20,8 +20,6 @@ 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; @@ -31,32 +29,34 @@ import org.openecomp.sdc.common.impl.ConfigFileChangeListener; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.io.IOException; + public class TestExternalConfiguration<T extends Object> { - public static void main(String[] args) throws IOException { + 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(); + 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() { + ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() { - @Override - public void reconfigure(BasicConfiguration obj) { - // TODO Auto-generated method stub + @Override + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub - } - }); + } + }); - ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); - configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); + ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); + configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); - try { - Thread.currentThread().sleep(100 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + try { + Thread.currentThread().sleep(100 * 1000); + } catch (InterruptedException e) { + 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 index c3f211f7ab..9ee123a840 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java @@ -20,6 +20,9 @@ package org.openecomp.sdc; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.ByteArrayOutputStream; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; @@ -30,100 +33,97 @@ 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) { + public static void main(String[] args) { - String zipFileName = "/src/test/resources/config/config.zip"; + 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"; + 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); + Path path = Paths.get(zipFileName); - try { - byte[] zipAsBytes = Files.readAllBytes(path); - // encode to base + try { + byte[] zipAsBytes = Files.readAllBytes(path); + // encode to base - byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); - String decodedStr = new String(decodedMd5); + byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); + String decodedStr = new String(decodedMd5); - zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); + zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); - // String str = new String(zipAsBytes); + // String str = new String(zipAsBytes); - // readZip(str.getBytes()); - readZip(zipAsBytes); + // readZip(str.getBytes()); + readZip(zipAsBytes); - } catch (IOException e) { - e.printStackTrace(); - } + } catch (IOException e) { + e.printStackTrace(); + } - } + } - private static Map<String, byte[]> readZip(byte[] zipAsBytes) { + private static Map<String, byte[]> readZip(byte[] zipAsBytes) { - Map<String, byte[]> fileNameToByteArray = new HashMap<String, byte[]>(); + Map<String, byte[]> fileNameToByteArray = new HashMap<String, byte[]>(); - byte[] buffer = new byte[1024]; - ZipInputStream zis = null; - try { + 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(); + zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes)); + // get the zipped file list entry + ZipEntry ze = zis.getNextEntry(); - while (ze != null) { + while (ze != null) { - String fileName = ze.getName(); + String fileName = ze.getName(); - if (false == ze.isDirectory()) { + if (false == ze.isDirectory()) { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - int len; - while ((len = zis.read(buffer)) > 0) { - os.write(buffer, 0, len); - } + 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"); + // aClass.outputStreamMethod(os); + String aString = new String(os.toByteArray(), "UTF-8"); - fileNameToByteArray.put(fileName, os.toByteArray()); + fileNameToByteArray.put(fileName, os.toByteArray()); - } finally { - if (os != null) { - os.close(); - } - } - } - ze = zis.getNextEntry(); + } finally { + if (os != null) { + os.close(); + } + } + } + ze = zis.getNextEntry(); - } + } - zis.closeEntry(); - zis.close(); + 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 - } + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } finally { + if (zis != null) { + try { + zis.closeEntry(); + zis.close(); + } catch (IOException e) { + // TODO: add log + } - } - } + } + } - return fileNameToByteArray; + return fileNameToByteArray; - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java index a6c8dc4f0c..84c6fc118d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be; -import static org.mockito.Mockito.mock; - import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.common.api.ConfigurationListener; import org.openecomp.sdc.common.api.ConfigurationSource; +import static org.mockito.Mockito.mock; + public class DummyConfigurationManager { private DistributionEngineConfiguration distributionConfigurationMock = mock(DistributionEngineConfiguration.class); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java new file mode 100644 index 0000000000..9bdf784f1c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java @@ -0,0 +1,132 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.junit.Test; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.common.api.Constants; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; + +public class AuditBaseEventFactoryTest { + + private User user = new User(); + + @Test + public void buildUserNameWhenFullNameAndUserIdNotSet() { + assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsNotSetAndUserIdIsSet() { + user.setUserId(USER_ID); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsNullNullAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(Constants.NULL_STRING); + user.setLastName(Constants.NULL_STRING); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirtsNameIsNotSetAndLastNameIsNull() { + user.setUserId(USER_ID); + user.setLastName(Constants.NULL_STRING); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenLastNameIsNull() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(Constants.NULL_STRING); + assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirstNameIsNullAndLastNameIsSet() { + user.setUserId(USER_ID); + user.setFirstName(Constants.NULL_STRING); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_LAST_NAME + "(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsSetAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_UID, AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirstNameIsSetAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildExtendedUserNameWhenNothingIsSet() { + assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyUserIdIsSet() { + user.setUserId(USER_ID); + assertEquals(USER_ID, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameAllSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + user.setEmail(USER_EMAIL); + user.setRole(DESIGNER_USER_ROLE); + assertEquals(USER_EXTENDED_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenFirstNameAndUserIdAreSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + assertEquals(USER_ID + ", " + USER_FIRST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenLastNameAndUserIdAreSet() { + user.setUserId(USER_ID); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_ID + ", " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyEmailAndRoleAreSet() { + user.setEmail(USER_EMAIL); + user.setRole(DESIGNER_USER_ROLE); + assertEquals(USER_EMAIL + ", " + DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyNameIsSet() { + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_FIRST_NAME + " " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyRoleIsSet() { + user.setRole(DESIGNER_USER_ROLE); + assertEquals(DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java new file mode 100644 index 0000000000..0a90ffd915 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java @@ -0,0 +1,200 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.ConsumerDefinition; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_PASSWORD; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_SALT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ECOMP_USER_CRED_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditConsumerEventFuncTest { + private AuditingManager auditingManager; + + private ConsumerDefinition consumer; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + consumer = new ConsumerDefinition(); + consumer.setConsumerName(USER_ID); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddEcompUserCredEvent() { + AuditEventFactory factory = new AuditConsumerEventFactory( + AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, consumer); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName()); + } + + @Test + public void testOldAddEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName()); + + } + + @Test + public void testNewGetEcompUserCredEvent() { + AuditEventFactory factory = new AuditConsumerEventFactory( + AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, consumer); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName()); + } + + @Test + public void testOldGetEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName()); + + } + + @Test + public void buildConsumerNameWhenAllFieldsAreProvided() { + consumer.setConsumerName(CONSUMER_NAME); + consumer.setConsumerSalt(CONSUMER_SALT); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_NAME + "," + CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenSaltIsNull() { + consumer.setConsumerName(CONSUMER_NAME); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_NAME + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameIsNull() { + consumer.setConsumerName(null); + consumer.setConsumerSalt(CONSUMER_SALT); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameAndPwAreNull() { + consumer.setConsumerName(null); + consumer.setConsumerSalt(CONSUMER_SALT); + assertEquals(CONSUMER_SALT, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameAndSaltAreNull() { + consumer.setConsumerName(null); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenConsumerObjectIsNull() { + assertEquals("", AuditConsumerEventFactory.buildConsumerName(null)); + } + + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, USER_ID); + + return auditingFields; + } + + private void verifyConsumerEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ConsumerEvent storedEvent = (ConsumerEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getEcompUser()).isEqualTo(USER_ID); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java new file mode 100644 index 0000000000..04bd34f289 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java @@ -0,0 +1,236 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + + +public class AuditTestUtils { + public final static String USER_FIRST_NAME = "Carlos"; + public final static String USER_LAST_NAME = "Santana"; + public final static String USER_ID = "cs0008"; + public final static String DESCRIPTION = "OK"; + public final static String STATUS_OK = "200"; + public final static String STATUS_CREATED = "201"; + public final static String REQUEST_ID = "123456"; + public final static String USER_UID = "Carlos Santana(cs0008)"; + public final static String SERVICE_INSTANCE_ID = "d07fdc15-122d-4476-a349-8c9a2d80b485"; + public final static String CURRENT_STATE = "CERTIFIED"; + public final static String CURRENT_VERSION = "1.1"; + public final static String RESOURCE_TYPE = ResourceTypeEnum.VF.name(); + public final static String RESOURCE_TYPE_VFC = ResourceTypeEnum.VFC.name(); + public final static String RESOURCE_NAME = "ciServicea184822c06e6"; + public final static String DIST_ID = "e5765a82-e7cd-4c5c-91a0-eae58d6ae08f"; + public final static String TOPIC_NAME = "ASDC-DISTR-NOTIF-TOPIC-PROD_TEST"; + public final static String DESIGNER_USER_ROLE = "DESIGNER"; + public final static String TESTER_USER_ROLE = "TESTER"; + public final static String USER_EMAIL = "carlos@email.com"; + public final static String MODIFIER_FIRST_NAME = "Jimmy"; + public final static String MODIFIER_LAST_NAME = "Hendrix"; + public final static String MODIFIER_ID = "jh0003"; + public final static String MODIFIER_UID = "Jimmy Hendrix(jh0003)"; + public final static String USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, DESIGNER"; + public final static String UPDATED_USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, TESTER"; + public final static String VNF_WORKLOAD_CONTEXT = "WORKLOAD"; + public final static String DPREV_STATUS = "DPREV_STATUS"; + public final static String DCURR_STATUS = "DCURR_STATUS"; + + public final static String CONSUMER_NAME = "consumer"; + public final static String CONSUMER_SALT = "2a1f887d607d4515d4066fe0f5452a50"; + public final static String CONSUMER_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"; + + public final static String PREV_RESOURCE_VERSION = "1.0"; + public final static String PREV_RESOURCE_STATE = "READY_FOR_CERTIFICATION"; + public final static String COMMENT = "Attempt to perform"; + public final static String ARTIFACT_DATA = "123456qwertasdfgljkPIPIPIOPI"; + public final static String TOSCA_NODE_TYPE = "tosca.node.Root"; + public final static String ARTIFACT_UUID = "1234-ASDFG_7894443"; + public final static String INVARIANT_UUID = "INV-123456"; + public final static String USER_DETAILS = "All"; + + public final static String STATUS_500 = "500"; + public final static String DESC_ERROR = "Error"; + public final static String MSG_ERROR = "Error: "; + public final static String MSG_OK = "OK: "; + + public final static String DIST_CONSUMER_ID = "ABC-123445678"; + public final static String DIST_RESOURCE_URL = "http://abc.com/res"; + public final static String DIST_STATUS_TOPIC = "STopic"; + public final static String DIST_NOTIFY_TOPIC = "NTopic"; + public final static String DIST_API_KEY = "Key111"; + public final static String DIST_ENV_NAME = "Env111"; + public final static String DIST_ROLE = "Governer"; + public final static String DIST_STATUS_TIME = "154567890123"; + + public final static String AUTH_URL = "http://abc.com/auth"; + public final static String REALM = "12345ABSDF"; + public final static String AUTH_STATUS = "AUTHENTICATED"; + + public final static String CATEGORY = "VFs"; + public final static String SUB_CATEGORY = "Network"; + public final static String GROUPING_NAME = "Group1"; + + public final static String OP_ENV_ID = "12345678"; + public final static String OP_ENV_NAME = "Op1"; + public final static String OP_ENV_TYPE = "ECOMP"; + public final static String OP_ENV_ACTION = "Create"; + public final static String TENANT_CONTEXT = "TENANT"; + + public final static String EXPECTED_USER_ACCESS_LOG_STR = "ACTION = \"" + AuditingActionEnum.USER_ACCESS.getName() + "\" USER = \"" + USER_UID + + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DISTRIB_NOTIFICATION_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_NOTIFY.getName() + + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + + "\" DID = \"" + DIST_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + + "\" TENANT = \"" + TENANT_CONTEXT + "\" VNF_WORKLOAD_CONTEXT = \"" + VNF_WORKLOAD_CONTEXT + "\" ENV_ID = \"" + OP_ENV_ID + "\""; + + public final static String EXPECTED_ADD_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"\" USER_AFTER = \"" + USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_CREATED + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_UPDATE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.UPDATE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"" + UPDATED_USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DELETE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.DELETE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CHECK_IN_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHECKIN_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" COMMENT = \"" + COMMENT + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CREATE_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_IMPORT_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.IMPORT_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" TOSCA_NODE_TYPE = \"" + + TOSCA_NODE_TYPE + "\""; + + public final static String EXPECTED_ARTIFACT_UPLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_UPLOAD.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" + + ARTIFACT_UUID + "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_STATE_CHANGE_REQUEST = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + + MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" + + DCURR_STATUS + "\" DID = \"" + DIST_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_STATE_CHANGE_APPROV = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + + MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" + + DCURR_STATUS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" COMMENT = \"" + COMMENT + "\""; + + public final static String EXPECTED_GET_USER_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_USERS_LIST.getName() + "\" MODIFIER = \"" + USER_UID + + "\" DETAILS = \"" + USER_DETAILS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_ACTIVATE_SERVICE_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName() + "\" RESOURCE_TYPE = \"" + + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" MODIFIER = \"" + + MODIFIER_UID + "\" STATUS = \"" + STATUS_OK + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" INVARIANT_UUID = \"" + INVARIANT_UUID + + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR = "CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + + "\" PREV_STATE = \"" + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + + "\" INVARIANT_UUID = \"" + INVARIANT_UUID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" + ARTIFACT_UUID + + "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_ASSET_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ASSET_LIST.getName() + "\" CONSUMER_ID = \"" + + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_TOSCA_MODEL_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_TOSCA_MODEL.getName() + "\" CONSUMER_ID = \"" + + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_AUTH_REQUEST_LOG_STR = "ACTION = \"" + AuditingActionEnum.AUTH_REQUEST.getName() + "\" URL = \"" + + AUTH_URL + "\" USER = \"" + USER_ID + "\" AUTH_STATUS = \"" + AUTH_STATUS + "\" REALM = \"" + REALM + "\""; + + public final static String EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_ADD_CATEGORY_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_CATEGORY.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" CATEGORY_NAME = \"" + CATEGORY + "\" SUB_CATEGORY_NAME = \"" + SUB_CATEGORY + + "\" GROUPING_NAME = \"" + GROUPING_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + private final static String OP_ENV_LOG = "\" OPERATIONAL_ENVIRONMENT_ACTION = \"" + OP_ENV_ACTION + "\" OPERATIONAL_ENVIRONMENT_ID = \"" + OP_ENV_ID + + "\" OPERATIONAL_ENVIRONMENT_NAME = \"" + OP_ENV_NAME + "\" OPERATIONAL_ENVIRONMENT_TYPE = \"" + OP_ENV_TYPE + + "\" TENANT_CONTEXT = \"" + TENANT_CONTEXT + "\""; + + public final static String EXPECTED_CREATE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_ENVIRONMENT.getName() + OP_ENV_LOG; + + public final static String EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName() + OP_ENV_LOG; + + public final static String EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName() + OP_ENV_LOG; + + public final static String EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName() + + "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" ROLE = \"" + DIST_ROLE + "\" API_KEY = \"" + + DIST_API_KEY + "\" STATUS = \"" + STATUS_OK + "\""; + + public final static String EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName() + + "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" STATUS = \"" + STATUS_OK + "\""; + + public final static String EXPECTED_DIST_REG_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_REGISTER.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" API_KEY = \"" + DIST_API_KEY + "\" D_ENV = \"" + DIST_ENV_NAME + "\" STATUS = \"" + + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" DNOTIF_TOPIC = \"" + DIST_NOTIFY_TOPIC + "\" DSTATUS_TOPIC = \"" + DIST_STATUS_TOPIC + "\""; + + public final static String EXPECTED_DIST_STATUS_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATUS.getName() + + "\" DID = \"" + DIST_ID + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME + + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS_TIME = \"" + DIST_STATUS_TIME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_DOWNLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DISTRIB_DEPLOY_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_DEPLOY.getName() + + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" DID = \"" + DIST_ID + + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_UEB_CLUSTER_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_UEB_CLUSTER.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" STATUS = \"" + STATUS_OK + "\" STATUS_DESC = \"" + DESCRIPTION + "\""; + + + public static User user; + public static User modifier; + + public static void init(Configuration.ElasticSearchConfig esConfig) { + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + configurationManager.getConfiguration().setDisableAudit(false); + configurationManager.getConfiguration().setElasticSearch(esConfig); + + user = new User(); + modifier = new User(); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + user.setUserId(USER_ID); + + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java new file mode 100644 index 0000000000..a774dea352 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CATEGORY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_CATEGORY_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.GROUPING_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SUB_CATEGORY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditCategoryEventFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddCategoryEvent() { + AuditEventFactory builder = new AuditAddCategoryEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, CATEGORY, SUB_CATEGORY, GROUPING_NAME, RESOURCE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR); + verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName()); + } + + @Test + public void testOldAddEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_CATEGORY))).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR); + verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName()); + + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, CATEGORY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, SUB_CATEGORY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, GROUPING_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + private void verifyCategoryEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + CategoryEvent storedEvent = (CategoryEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); +// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getCategoryName()).isEqualTo(CATEGORY); + assertThat(storedEvent.getSubCategoryName()).isEqualTo(SUB_CATEGORY); + assertThat(storedEvent.getGroupingName()).isEqualTo(GROUPING_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java new file mode 100644 index 0000000000..199597b82c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java @@ -0,0 +1,191 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_API_KEY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_NOTIFY_TOPIC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TOPIC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_REG_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; + +@RunWith(MockitoJUnitRunner.class) +public class AuditDistrEngineFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddKeyEvent() { + AuditEventFactory factory = new AuditAddKeyDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName()); + } + + @Test + public void testOldAddKeyEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL))).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName()); + + } + + @Test + public void testNewCreateTopicEvent() { + AuditEventFactory factory = new AuditCreateTopicDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName()); + } + + @Test + public void testOldCreateTopicEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC))).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName()); + } + + @Test + public void testNewRegisterEvent() { + AuditEventFactory factory = new AuditRegisterDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName()); + } + + @Test + public void testOldRegisterEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_REGISTER))).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName()); + } + + private void verifyEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionEngineEvent storedEvent = (DistributionEngineEvent) eventCaptor.getValue(); + assertThat(storedEvent.getDnotifTopic()).isEqualTo(DIST_NOTIFY_TOPIC); + assertThat(storedEvent.getDstatusTopic()).isEqualTo(DIST_STATUS_TOPIC); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getEnvironmentName()).isEqualTo(DIST_ENV_NAME); + assertThat(storedEvent.getApiKey()).isEqualTo(DIST_API_KEY); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getRole()).isEqualTo(DIST_ROLE); + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, DIST_ENV_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, DIST_STATUS_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, DIST_NOTIFY_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, DIST_NOTIFY_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, DIST_API_KEY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, DIST_ROLE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java new file mode 100644 index 0000000000..09a168a132 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java @@ -0,0 +1,387 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TIME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_DEPLOY_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_NOTIFICATION_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_DOWNLOAD_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATUS_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_UEB_CLUSTER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOPIC_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.VNF_WORKLOAD_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user; + +@RunWith(MockitoJUnitRunner.class) +public class AuditDistrEventFuncTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewNotifyEvent() { + AuditEventFactory factory = new AuditDistribNotificationEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + CURRENT_STATE, CURRENT_VERSION, DIST_ID, user, + RESOURCE_NAME, RESOURCE_TYPE, TOPIC_NAME, + new OperationalEnvAuditData(OP_ENV_ID, VNF_WORKLOAD_CONTEXT, TENANT_CONTEXT)); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR); + verifyNotifyEvent(); + } + + @Test + public void testOldNotifyEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillNotifyMap())).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR); + verifyNotifyEvent(); + + } + + @Test + public void testNewStatusEvent() { + AuditEventFactory factory = new AuditDistribStatusEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_ID, DIST_CONSUMER_ID, TOPIC_NAME, DIST_RESOURCE_URL, DIST_STATUS_TIME); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR); + verifyStatusEvent(); + } + + @Test + public void testOldStatusEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillStatusMap())).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR); + verifyStatusEvent(); + } + + @Test + public void testNewDownloadEvent() { + AuditEventFactory factory = new AuditDistribDownloadEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR); + verifyDownloadsEvent(); + } + + @Test + public void testOldDownloadEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillDownloadMap())).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR); + verifyDownloadsEvent(); + } + + @Test + public void testNewDeployEvent() { + AuditEventFactory factory = new AuditDistribDeployEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + CURRENT_VERSION, + DIST_ID, user, RESOURCE_NAME, RESOURCE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR); + verifyDeployEvent(); + } + + @Test + public void testOldDeployEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillDeployMap())).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR); + verifyDeployEvent(); + } + + @Test + public void testNewGetUebClusterEvent() { + AuditEventFactory factory = new AuditGetUebClusterEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR); + verifyGetUebClusterEvent(); + } + + @Test + public void testOldGetUebClusterEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillGetUebClusterMap())).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR); + verifyGetUebClusterEvent(); + } + + private void verifyNotifyEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionNotificationEvent storedEvent = (DistributionNotificationEvent) eventCaptor.getValue(); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME); + assertThat(storedEvent.getVnfWorkloadContext()).isEqualTo(VNF_WORKLOAD_CONTEXT); + assertThat(storedEvent.getEnvId()).isEqualTo(OP_ENV_ID); + assertThat(storedEvent.getTenant()).isEqualTo(TENANT_CONTEXT); + } + + private void verifyStatusEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionStatusEvent storedEvent = (DistributionStatusEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_STATUS.getName()); + assertThat(storedEvent.getStatusTime()).isEqualTo(DIST_STATUS_TIME); + assertThat(storedEvent.getResoureURL()).isEqualTo(DIST_RESOURCE_URL); + assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME); + } + + private void verifyDownloadsEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionDownloadEvent storedEvent = (DistributionDownloadEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + } + + private void verifyDeployEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionDeployEvent storedEvent = (DistributionDeployEvent) eventCaptor.getValue(); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + } + + private void verifyGetUebClusterEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + AuditingGetUebClusterEvent storedEvent = (AuditingGetUebClusterEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillNotifyMap() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, VNF_WORKLOAD_CONTEXT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, TENANT_CONTEXT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, OP_ENV_ID); + + return auditingFields; + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillStatusMap() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_STATUS.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, DIST_STATUS_TIME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + + return auditingFields; + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillDownloadMap() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillDeployMap() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME); + + return auditingFields; + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillGetUebClusterMap() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_UEB_CLUSTER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java new file mode 100644 index 0000000000..f859b75607 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java @@ -0,0 +1,156 @@ +package org.openecomp.sdc.be.auditing.impl.ecompopenv; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; + +@RunWith(MockitoJUnitRunner.class) +public class AuditEcompOpEnvEventTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewCreateOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.CREATE_ENVIRONMENT, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + } + + @Test + public void testOldCreateOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_ENVIRONMENT))).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + + } + + @Test + public void testNewUnsupportedTypeOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName()); + } + + @Test + public void testOldUnsupportedTypeOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE))).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName()); + } + + @Test + public void testNewUnknownNotificationOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName()); + } + + @Test + public void testOldUnknownNotificationOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION))).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName()); + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID, OP_ENV_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE, OP_ENV_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME, OP_ENV_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION, OP_ENV_ACTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT, TENANT_CONTEXT); + + return auditingFields; + } + + private void verifyEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + EcompOperationalEnvironmentEvent storedEvent = (EcompOperationalEnvironmentEvent) eventCaptor.getValue(); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(storedEvent.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(storedEvent.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(storedEvent.getTenantContext()).isEqualTo(TENANT_CONTEXT); + + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java new file mode 100644 index 0000000000..7ddc9a0606 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java @@ -0,0 +1,368 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ACTIVATE_SERVICE_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ASSET_LIST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_TOSCA_MODEL_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditExternalApiEventFuncTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewActivateServiceEvent() { + AuditEventFactory builder = new AuditActivateServiceExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName()); + } + + @Test + public void testOldActivateServiceEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ACTIVATE_SERVICE_BY_API))).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName()); + + } + + @Test + public void testNewDownloadArtifactEvent() { + AuditEventFactory builder = new AuditDownloadArtifactExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName()); + } + + @Test + public void testOldDownloadArtifactEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DOWNLOAD_ARTIFACT))).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR + " "); + verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName()); + } + + @Test + public void testNewChangeLifecycleEvent() { + AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + } + + @Test + public void testOldChangeLifecycleEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API))).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + + } + + @Test + public void testNewDeleteArtifactEvent() { + AuditEventFactory factory = new AuditDeleteArtByApiCrudExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName()); + } + + @Test + public void testOldDeleteArtifactEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_DELETE_BY_API))).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR + " "); + verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName()); + + } + + @Test + public void testNewGetAssetsListEvent() { + AuditEventFactory factory = new AuditGetAssetListExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName()); + } + + @Test + public void testOldGetAssetsListEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ASSET_LIST))).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName()); + } + + @Test + public void testNewGetToscaModelEvent() { + AuditEventFactory factory = new AuditGetToscaModelExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName()); + } + + @Test + public void testOldGetToscaModelEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_TOSCA_MODEL))).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName()); + } + + private void verifyExternalApiEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ExternalApiEvent storedEvent = (ExternalApiEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA); + assertThat(storedEvent.getCurrArtifactUuid()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevArtifactUuid()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getInvariantUuid()).isEqualTo(INVARIANT_UUID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + return auditingFields; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java new file mode 100644 index 0000000000..18bd41c765 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java @@ -0,0 +1,432 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +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.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ARTIFACT_UPLOAD_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHECK_IN_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_APPROV; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_REQUEST; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_IMPORT_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE_VFC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditResourceAdminEventFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static ConfigurationSource configurationSource; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewCheckInResourceAdminEvent() { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + AuditEventFactory factory = new AuditCertificationResourceAdminEventFactory( + AuditingActionEnum.CHECKIN_RESOURCE, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName()); + } + + @Test + public void testOldCheckInResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHECKIN_RESOURCE))).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName()); + + } + + private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE_VFC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, COMMENT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, DCURR_STATUS); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, DPREV_STATUS); + + if (action == AuditingActionEnum.IMPORT_RESOURCE) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, TOSCA_NODE_TYPE); + } + else { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, Constants.EMPTY_STRING); + } + + return auditingFields; + } + + @Test + public void testNewCreateResourceAdminEvent() { + + AuditEventFactory factory = new AuditCreateUpdateResourceAdminEventFactory( + AuditingActionEnum.CREATE_RESOURCE, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID, Constants.EMPTY_STRING); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName()); + } + + @Test + public void testOldCreateResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_RESOURCE))).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName()); + + } + + @Test + public void testNewImportResourceAdminEvent() { + + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.setVersion(CURRENT_VERSION); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setState(LifecycleStateEnum.CERTIFIED); + resource.setToscaType(TOSCA_NODE_TYPE); + + AuditEventFactory factory = new AuditImportResourceAdminEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID, TOSCA_NODE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName()); + } + + @Test + public void testOldImportResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.IMPORT_RESOURCE))).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName()); + + } + + @Test + public void testNewArtifactUploadResourceAdminEvent() { + + AuditEventFactory factory = new AuditArtifactResourceAdminEventFactory( + AuditingActionEnum.ARTIFACT_UPLOAD, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_UPLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName()); + } + + @Test + public void testOldArtifactUploadResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_UPLOAD))).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName()); + + } + + @Test + public void testNewDistStateChangeRequestResourceAdminEvent() { + + AuditEventFactory factory = new AuditDistStateChangeRequestResourceAdminEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + } + + @Test + public void testOldDistStateChangeRequestResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + } + + @Test + public void testNewDistStateChangeApprovResourceAdminEvent() { + + AuditEventFactory factory = new AuditDistStateChangeResourceAdminEventFactory( + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName()); + } + + @Test + public void testOldDistStateChangeApprovResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName()); + } + + + private void verifyResourceAdminEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ResourceAdminEvent storedEvent = (ResourceAdminEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA); + assertThat(storedEvent.getComment()).isEqualTo(COMMENT); + assertThat(storedEvent.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(storedEvent.getDprevStatus()).isEqualTo(DPREV_STATUS); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE_VFC); + + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(storedEvent.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } else { + assertThat(storedEvent.getToscaNodeType()).isEmpty(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java new file mode 100644 index 0000000000..4a5b1bbd59 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java @@ -0,0 +1,395 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuthEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_AUTH_REQUEST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_USER_LIST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UPDATE_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_USER_ACCESS_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REALM; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_CREATED; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_DETAILS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user; + +@RunWith(MockitoJUnitRunner.class) +public class AuditUserEventFuncTest { + @Mock + private static AuditCassandraDao cassandraDao; + @Captor + private ArgumentCaptor<AuditingGenericEvent> eventCaptor; + @Mock + private static AuditingDao auditingDao; + @Mock + private Configuration.ElasticSearchConfig esConfig; + + private AuditingManager auditingManager; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewUserAccessEvent() { + AuditEventFactory factory = new AuditUserAccessEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + user); + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR); + verifyUserAccessEvent(); + } + + @Test + public void testOldUserAccessEvent() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.USER_ACCESS.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')'); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR); + verifyUserAccessEvent(); + } + + @Test + public void testNewUserAdminEventForAddUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.ADD_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_CREATED) + .requestId(REQUEST_ID) + .build(), + modifier, null, user); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.ADD_USER.getName()); + } + + @Test + public void testOldUserAdminEventForAddUser() { + user.setRole(TESTER_USER_ROLE); + user.setEmail(USER_EMAIL); + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.ADD_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_CREATED); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, USER_EXTENDED_NAME); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_ADD_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.ADD_USER.getName()); + } + + @Test + public void testNewUserAdminEventForUpdateUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + User updated = new User(user); + updated.setRole(TESTER_USER_ROLE); + + AuditEventFactory builder = new AuditUserAdminEventFactory(AuditingActionEnum.UPDATE_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + modifier, user, updated); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName()); + } + + @Test + public void testOldUserAdminEventForUpdateUser() { + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + User updated = new User(user); + updated.setRole(TESTER_USER_ROLE); + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.UPDATE_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, UPDATED_USER_EXTENDED_NAME); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName()); + } + + @Test + public void testNewUserAdminEventForDeleteUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.DELETE_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + modifier, user, null); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.DELETE_USER.getName()); + } + + @Test + public void testOldUserAdminEventForDeleteUser() { + user.setRole(TESTER_USER_ROLE); + user.setEmail(USER_EMAIL); + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DELETE_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, null); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.DELETE_USER.getName()); + } + + @Test + public void testNewGetUserListEvent() { + + AuditEventFactory factory = new AuditGetUsersListEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + user, USER_DETAILS); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR); + verifyGetUserListEvent(); + } + + @Test + public void testOldGetUserListEvent() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_USERS_LIST.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, USER_DETAILS); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR); + verifyGetUserListEvent(); + } + + @Test + public void testNewAuthRequestEvent() { + + AuditEventFactory factory = new AuditAuthRequestEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + USER_ID, AUTH_URL, REALM, AUTH_STATUS); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR); + verifyAuthRequestEvent(); + } + + @Test + public void testOldAuthRequestEvent() { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.AUTH_REQUEST.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, REALM); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, AUTH_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, AUTH_STATUS); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR); + verifyAuthRequestEvent(); + } + + + private void verifyUserEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + UserAdminEvent storedEvent = (UserAdminEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); +// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); - it is not filled out by the old code!!! + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(action); + if (action.equals(AuditingActionEnum.ADD_USER.getName())) { + //TODO enable this test after deleting the old auditEvent method +// assertThat(storedEvent.getUserBefore()).isNull(); + assertThat(storedEvent.getUserAfter()).isEqualTo(USER_EXTENDED_NAME); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_CREATED); + } + else if (action.equals(AuditingActionEnum.UPDATE_USER.getName())){ + assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME); + assertThat(storedEvent.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + } + else { + assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME); + //TODO enable this test after deleting the old auditEvent method +// assertThat(storedEvent.getUserAfter()).isNull(); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + } + } + + private void verifyGetUserListEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + GetUsersListEvent storedEvent = (GetUsersListEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.GET_USERS_LIST.getName()); + } + + private void verifyUserAccessEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + UserAccessEvent storedEvent = (UserAccessEvent) eventCaptor.getValue(); + assertThat(storedEvent.getUserUid()).isEqualTo(USER_UID); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isNotBlank(); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.USER_ACCESS.getName()); + } + + private void verifyAuthRequestEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + AuthEvent storedEvent = (AuthEvent) eventCaptor.getValue(); + assertThat(storedEvent.getUser()).isEqualTo(USER_ID); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isNotBlank(); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAuthStatus()).isEqualTo(AUTH_STATUS); + assertThat(storedEvent.getUrl()).isEqualTo(AUTH_URL); + assertThat(storedEvent.getRealm()).isEqualTo(REALM); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.AUTH_REQUEST.getName()); + } + +} 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 index 87dfbc45de..06c22bca69 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,56 +20,53 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import java.util.EnumMap; -import java.util.UUID; - import org.junit.Before; import org.junit.Test; -import org.mockito.InjectMocks; +import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; 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 junit.framework.Assert; +import java.util.EnumMap; +import java.util.UUID; -public class AuditingManagerTest extends BaseConfDependentTest{ +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; - @InjectMocks - private AuditingManager auditingManager = Mockito.spy(AuditingManager.class); - public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class); +@RunWith(MockitoJUnitRunner.class) +public class AuditingManagerTest extends BeConfDependentTest { - public AuditingManagerTest() { - } + private AuditingManager auditingManager; + @Mock + private AuditingDao auditingDao; - @SuppressWarnings("unchecked") - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); + @Before + public void setup() { + auditingManager = new AuditingManager(auditingDao, null); + 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 "); + @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); + 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); - } + auditingManager.auditEvent(auditingFields); + // Checking normalization + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)).isEqualTo(randomUUID); + } } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java new file mode 100644 index 0000000000..bbd827eb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java @@ -0,0 +1,355 @@ +package org.openecomp.sdc.be.components; + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +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.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +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.ComponentInstance; +import org.openecomp.sdc.be.model.GroupInstance; +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.jsontitan.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +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.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +public class BaseServiceBusinessLogicTest { + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + ForwardingPathOperation forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = null; + + protected static final String CERTIFIED_VERSION = "1.0"; + protected static final String UNCERTIFIED_VERSION = "0.2"; + protected static final String COMPONNET_ID = "myUniqueId"; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<>(); + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<>(); + protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<>(); + @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); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // 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<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + //forwardingPath + when(forwardingPathOperation.addForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.updateForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.deleteForwardingPath(any(),any())).thenReturn(Either.left(Sets.newHashSet("Wow-It-Works"))); + when(toscaOperationFacade.getToscaElement("delete_forward_test")).thenReturn(Either.left(createServiceObject(true))); + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setForwardingPathOperation(forwardingPathOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + protected Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i<listSize; ++i){ + ci = new ComponentInstance(); + ci.setName("ciName" + i); + ci.setUniqueId("ciId" + i); + List<GroupInstance> groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j<listSize; ++j){ + gi = new GroupInstance(); + gi.setName(ci.getName( )+ "giName" + j); + gi.setUniqueId(ci.getName() + "giId" + j); + groupInstances.add(gi); + } + ci.setGroupInstances(groupInstances); + componentInstances.add(ci); + } + service.setComponentInstances(componentInstances); + 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); + + } + + protected 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.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()); + } + return service; + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected static ForwardingPathDataDefinition forwardingPathDataDefinition; + + protected static ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null){ + return forwardingPathDataDefinition ; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol("http"); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode","toNode", "333","444","2222","5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode","toNode2", "4444","44444","4","44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } +} 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/BeConfDependentTest.java index ad5471e852..01d003f2a4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java @@ -20,29 +20,15 @@ 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); +import org.openecomp.sdc.common.test.BaseConfDependent; - configurationManager.getConfiguration().setTitanInMemoryGraph(true); +public class BeConfDependentTest extends BaseConfDependent { + @BeforeClass + public static void setupBeforeClass() { + componentName = "catalog-be"; + confPath = "src/test/resources/config"; + setUp(); + } - } } 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 index 7774b7f412..d7bfdcd1a4 100644 --- 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 @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,80 +42,85 @@ import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ComponentBusinessLogicTest { - private static final User USER = new User(); - private static final String ARTIFACT_LABEL = "toscaArtifact1"; - private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; - - @InjectMocks - private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - return null; - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return null; - } - - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - @Override - public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) { - return null; - } - }; - - @Mock - private ArtifactsBusinessLogic artifactsBusinessLogic; - - @BeforeClass - public static void setUp() throws Exception { - new DummyConfigurationManager(); - } - - @SuppressWarnings("unchecked") - @Test - public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { - Resource resource = new ResourceBuilder().setUniqueId("uid") - .setComponentType(ComponentTypeEnum.RESOURCE) - .setSystemName("myResource") - .build(); - Map<String, Object> artifactsFromConfig = new HashMap<>(); - artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); - artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); - when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); - testInstance.setToscaArtifactsPlaceHolders(resource, USER); - - Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts(); - assertThat(toscaArtifacts).hasSize(2); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); - assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); - ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); - assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); - } - - private Map<String, Object> buildArtifactMap(String artifactName) { - Map<String, Object> artifact = new HashMap<>(); - artifact.put("artifactName", artifactName); - return artifact; - } - - private ArtifactDefinition buildArtifactDef(String artifactLabel) { - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - artifactDefinition.setArtifactLabel(artifactLabel); - return artifactDefinition; - } + private static final User USER = new User(); + private static final String ARTIFACT_LABEL = "toscaArtifact1"; + private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; + + @InjectMocks + private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + return null; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return null; + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + @Override + public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) { + return null; + } + }; + + @Mock + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @BeforeClass + public static void setUp() throws Exception { + new DummyConfigurationManager(); + } + + @SuppressWarnings("unchecked") + @Test + public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { + Resource resource = new ResourceBuilder().setUniqueId("uid") + .setComponentType(ComponentTypeEnum.RESOURCE) + .setSystemName("myResource") + .build(); + Map<String, Object> artifactsFromConfig = new HashMap<>(); + artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); + artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); + testInstance.setToscaArtifactsPlaceHolders(resource, USER); + + Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts(); + assertThat(toscaArtifacts).hasSize(2); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); + assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); + ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); + assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); + } + + private Map<String, Object> buildArtifactMap(String artifactName) { + Map<String, Object> artifact = new HashMap<>(); + artifact.put("artifactName", artifactName); + return artifact; + } + + private ArtifactDefinition buildArtifactDef(String artifactLabel) { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactLabel(artifactLabel); + return artifactDefinition; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java index 9bf7f16a50..c114f340b8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java @@ -20,10 +20,6 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,206 +42,193 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import javax.servlet.ServletContext; + +import static org.mockito.Mockito.when; /** * tests GroupBusinessLogic class * @author ns019t * */ public class GroupBusinessLogicTest { - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); - ComponentsUtils componentsUtils = new ComponentsUtils(); - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - final ServletContext servletContext = Mockito.mock(ServletContext.class); - private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); - private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); - private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); - private static User user = Mockito.mock(User.class); - private static String componentId = "vfUniqueId-xxxx"; - private static String groupUniqueId = "groupUniqueId-xxxx"; - @InjectMocks - static GroupBusinessLogic bl = new GroupBusinessLogic(); - - - @Before - public void setupBeforeMethod() { - MockitoAnnotations.initMocks(this); - ExternalConfiguration.setAppName("catalog-be"); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - } - @BeforeClass - public static void setupBeforeClass() { - when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); -// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); - } - - public enum ResponseEnum{ - INVALID_MIN_MAX("SVC4654"), - INVALID_INITIAL_COUNT("SVC4655"); - - String messageId; - - private ResponseEnum(String messageId){ - this.messageId = messageId; - } - public String getMessageId() { - return messageId; - } - - } - /** - * tests the ValidateMinMaxAndInitialCountPropertyValues() method - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testValidateMinMaxAndInitialCountPropertyValues(){ - -// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class; -// String methodName = "validateMinMaxAndInitialCountPropertyValues"; -// Either<Boolean, ResponseFormat> validationRes; -// -// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); -// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); -// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); -// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); -// -// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); -// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); -// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); -// -// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); -// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); -// -// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); -// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); -// -// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); -// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); -// -// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); -// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); -// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); -// -// -// Class[] argClasses = {Map.class, Map.class}; -// try { -// Method method = targetClass.getDeclaredMethod(methodName, argClasses); -// method.setAccessible(true); -// -// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// -// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; -// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// } -// catch (Exception e) { -// e.printStackTrace(); -// } - } + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + ComponentsUtils componentsUtils; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); + private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); + private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); + private static User user = Mockito.mock(User.class); + private static String componentId = "vfUniqueId-xxxx"; + private static String groupUniqueId = "groupUniqueId-xxxx"; + @InjectMocks + static GroupBusinessLogic bl = new GroupBusinessLogic(); + + + @Before + public void setupBeforeMethod() { + MockitoAnnotations.initMocks(this); + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + + bl.setComponentsUtils(componentsUtils); + } + @BeforeClass + public static void setupBeforeClass() { + when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); +// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); + } + + /** + * tests the ValidateMinMaxAndInitialCountPropertyValues() method + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void testValidateMinMaxAndInitialCountPropertyValues(){ + +// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class; +// String methodName = "validateMinMaxAndInitialCountPropertyValues"; +// Either<Boolean, ResponseFormat> validationRes; +// +// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); +// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); +// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); +// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); +// +// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); +// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); +// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); +// +// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); +// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); +// +// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); +// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); +// +// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); +// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); +// +// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); +// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); +// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); +// +// +// Class[] argClasses = {Map.class, Map.class}; +// try { +// Method method = targetClass.getDeclaredMethod(methodName, argClasses); +// method.setAccessible(true); +// +// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// +// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; +// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// } +// catch (Exception e) { +// e.printStackTrace(); +// } + } } 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 index 2a34baeb0f..04c2100ed8 100644 --- 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 @@ -20,66 +20,66 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - import org.junit.Test; -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HealthCheckBusinessLogicTest { - HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); - - @Test - public void checkStausUpdated() { + HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); + + @Test + public void checkStausUpdated() { - boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); - assertFalse("check false", statusChanged); + boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); + assertFalse("check false", statusChanged); - List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>(); - List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>(); + List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>(); + List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>(); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); - HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); + HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); - /* - * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, 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(checkInfoTitanUp); - checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - checkInfosRight.remove(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", 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.add(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.remove(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); + checkInfosRight.add(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); - assertTrue("check true", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); + assertTrue("check true", statusChanged); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java new file mode 100644 index 0000000000..f9412c1643 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java @@ -0,0 +1,143 @@ +package org.openecomp.sdc.be.components; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datamodel.ServiceRelations; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class PathTest extends BaseServiceBusinessLogicTest { + public static final String fromNode = "fromNode"; + + @Override + protected Service createServiceObject(boolean afterCreate) { + Service service = super.createServiceObject(afterCreate); + ArrayList<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + String toNode = "toNode"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode, "1", toNode, "2", "capability", "3", "requirement", "4")); + String fromNode1 = "fromNode1"; + String toNode1 = "toNode1"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode1, "11", toNode1, "21", "capability1", "31", "requirement1", "41")); + service.setComponentInstances(new java.util.ArrayList<>()); + service.getComponentInstances().add(getComponentInstance(fromNode, "fromNode")); + service.getComponentInstances().add(getComponentInstance(fromNode1, "fromNode1")); + service.getComponentInstances().add(getComponentInstance(toNode, toNode)); + service.getComponentInstances().add(getComponentInstance(toNode1, toNode1)); + + service.setComponentInstancesRelations(resourceInstancesRelations); + return service; + } + + private ComponentInstance getComponentInstance(String uniquId, String normalizedName) { + ComponentInstance ci = new ComponentInstance(); + ci.setUniqueId(uniquId); + ci.setNormalizedName(normalizedName); + ci.setName(normalizedName); + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + ci.setCapabilities(capabilities); + return ci; + } + + private static int i = 0; + + private CapabilityDefinition getCapabilityDefinition(ComponentInstance ci) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setUniqueId(UUID.randomUUID().toString()); + capabilityDefinition.setName("My name " + i++); + capabilityDefinition.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + capabilityDefinition.setOwnerId(ci.getUniqueId()); + return capabilityDefinition; + } + + + protected RequirementCapabilityRelDef createRequirementCapabilityRelDef(String fromNode, String fromNodeId, String toNode, String toNodeId, String capability, String capabilityId, String requirement, String requirementId) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(fromNode); + requirementCapabilityRelDef.setRelationships(new ArrayList<>()); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("something.LINK"); + requirementCapabilityRelDef.getRelationships().add(capabilityRequirementRelationship); + requirementCapabilityRelDef.setToNode(toNode); + return requirementCapabilityRelDef; + } + + @Test + public void validateSerialization() throws IOException { + Service service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("Name"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + ObjectMapper mapper = new ObjectMapper(); + String jsonResult = mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(service); + System.out.println(jsonResult); + + Either<Service, ResponseFormat> serviceResponseFormatEither = new ComponentsUtils(Mockito.mock(AuditingManager.class)).convertJsonToObjectUsingObjectMapper(jsonResult, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + assertTrue(serviceResponseFormatEither.isLeft()); + Map<String, ForwardingPathDataDefinition> paths = serviceResponseFormatEither.left().value().getForwardingPaths(); + assertEquals(paths.size(), 1); + ForwardingPathDataDefinition forwardingPathDataDefinition = paths.values().stream().findAny().get(); + assertEquals(protocol, forwardingPathDataDefinition.getProtocol()); + List<ForwardingPathElementDataDefinition> listToscaDataDefinition = forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition(); + assertEquals(3, listToscaDataDefinition.size()); + assertTrue(listToscaDataDefinition.get(0).getFromNode().equals(nodeA)); + } + + @Test + public void shouldReturnEmptyRelationsObjectsWhenNoComponentInstanceExist() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(super.createServiceObject(false)); + assertTrue(serviceRelations.isEmpty()); + } + + @Test + public void convertServiceToServiceRelations() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(createServiceObject(false)); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String resultString = gson.toJson(serviceRelations); + System.out.println(" RESPONSE BODY: " + resultString); + assertTrue(resultString.contains(fromNode)); + } +} 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 index 572804636d..38aaf92335 100644 --- 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 @@ -20,17 +20,8 @@ package org.openecomp.sdc.be.components; -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.Arrays; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; +import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -38,6 +29,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -60,171 +52,152 @@ 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 javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; -import fj.data.Either; -import junit.framework.Assert; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class PropertyBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName()); - @Mock - private ServletContext servletContext; - @Mock - private IPropertyOperation propertyOperation; - @Mock - private WebAppContextWrapper webAppContextWrapper; - @Mock - private UserBusinessLogic mockUserAdmin; - @Mock - private WebApplicationContext webAppContext; - @Mock - private ComponentsUtils componentsUtils; - @Mock - private ToscaOperationFacade toscaOperationFacade; - - @InjectMocks - private PropertyBusinessLogic bl = new PropertyBusinessLogic(); - private User user = null; - private String resourceId = "resourceforproperty.0.1"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - 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); + private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class); + @Mock + private ServletContext servletContext; + @Mock + private IPropertyOperation propertyOperation; + @Mock + private WebAppContextWrapper webAppContextWrapper; + @Mock + private UserBusinessLogic mockUserAdmin; + @Mock + private WebApplicationContext webAppContext; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private UserValidations userValidations; + + @InjectMocks + private PropertyBusinessLogic bl = new PropertyBusinessLogic(); + private User user = null; + private String resourceId = "resourceforproperty.0.1"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + 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); + when(userValidations.validateUserExists(eq("jh003"), anyString(), eq(false))).thenReturn(Either.left(user)); + + // 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); - - } - - 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()); - } - - @Test - public void getProperty_propertyNotFound() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); - resource.setProperties(Arrays.asList(property1, property2)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); - assertTrue(nonExistingProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty_propertyNotBelongsToResource() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - resource.setProperties(Arrays.asList(property1)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); - assertTrue(notFoundProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty() throws Exception { - Resource resource = new Resource(); - resource.setUniqueId(resourceId); - PropertyDefinition property1 = createPropertyObject("someProperty", null); - resource.setProperties(Arrays.asList(property1)); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); - assertTrue(foundProperty.isLeft()); - assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); - } - - 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.setOwnerId(resourceId); - pd.setUniqueId(resourceId + "." + propertyName); - return pd; - } +// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true)); +// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); + + } + + // @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()); + } + + @Test + public void getProperty_propertyNotFound() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); + resource.setProperties(Arrays.asList(property1, property2)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); + assertTrue(nonExistingProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty_propertyNotBelongsToResource() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + resource.setProperties(Arrays.asList(property1)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); + assertTrue(notFoundProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty() throws Exception { + Resource resource = new Resource(); + resource.setUniqueId(resourceId); + PropertyDefinition property1 = createPropertyObject("someProperty", null); + resource.setProperties(Arrays.asList(property1)); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); + assertTrue(foundProperty.isLeft()); + assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); + } + + 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.setOwnerId(resourceId); + 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 index 30e12e85d0..82389822f3 100644 --- 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 @@ -20,16 +20,7 @@ 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.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.BeforeClass; @@ -37,7 +28,7 @@ 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.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ImportUtils; import org.openecomp.sdc.be.components.impl.ImportUtilsTest; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; @@ -63,310 +54,313 @@ 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; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; 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 UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); - static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - static Logger log = Mockito.spy(Logger.class); - - @BeforeClass - public static void beforeClass() throws IOException { - importManager = new ResourceImportManager(); - importManager.setAuditingManager(auditingManager); - when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); - importManager.setResponseFormatManager(responseFormatManager); - importManager.setResourceBusinessLogic(resourceBusinessLogic); - importManager.setToscaOperationFacade(toscaOperationFacade); - 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); - } + private static ConfigurationManager configurationManager; + static ResourceImportManager importManager; + static AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); + static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + @BeforeClass + public static void beforeClass() throws IOException { + importManager = new ResourceImportManager(); + importManager.setAuditingManager(auditingManager); + when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); + importManager.setResponseFormatManager(responseFormatManager); + importManager.setResourceBusinessLogic(resourceBusinessLogic); + importManager.setToscaOperationFacade(toscaOperationFacade); + + 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); + } + + @Test + public void testBasicResourceCreation() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); - @Before - public void beforeTest() { - Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log); - } + User user = new User(); + user.setUserId(resourceMD.getContactId()); + user.setRole("ADMIN"); + user.setFirstName("Jhon"); + user.setLastName("Doh"); + Either<User, ActionStatus> eitherUser = Either.left(user); - @Test - public void testBasicResourceCreation() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - user.setRole("ADMIN"); - user.setFirstName("Jhon"); - user.setLastName("Doh"); - Either<User, ActionStatus> eitherUser = Either.left(user); + setResourceBusinessLogicMock(); - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); - 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), Mockito.eq(false)); - } - - @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.eq(null), Mockito.eq(null), Mockito.eq(false)); - - Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - - } - - @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.eq(false)); - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); - - } - - @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(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) - .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), 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[1]); - - } - }); - when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(EnumMap.class))).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), Mockito.eq(null))).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.setPayloadName("payLoad"); - 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)); - } + 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), Mockito.eq(false)); + } + + @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(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + + } + + @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.eq(false)); + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); + + } + + @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(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) + .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), 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[1]); + + } + }); + when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), 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), Mockito.eq(null))).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.setPayloadName("payLoad"); + 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."); + resourceMD.setResourceVendorModelNumber("vendorReleaseNumber"); + 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())); + assertEquals(resource.getResourceVendorModelNumber(), resourceMD.getResourceVendorModelNumber()); + 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 index 9a8f1c5ad8..e750d3ab51 100644 --- 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 @@ -20,71 +20,71 @@ 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; +import java.util.ArrayList; +import java.util.List; + 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) { + 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 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"); + 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; - } + 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 index 1af1ac3070..bbb381bad3 100644 --- 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 @@ -20,31 +20,19 @@ 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.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; 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.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -83,940 +71,881 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -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); - 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); - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - - User user = null; - Service serviceResponse = null; - Resource genericService = 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 final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; - 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(new ServiceOperation()); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - - // artifact bussinesslogic - ArtifactDefinition artifactDef = new ArtifactDefinition(); - when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); - - // createService - serviceResponse = createServiceObject(true); - Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); - - genericService = setupGenericServiceMock(); - Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); - - - bl = new ServiceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setArtifactBl(artifactBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - 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); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); - 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(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testInvalidProjectCode(); - testProjectCodeTooLong(); - testProjectCodeTooShort(); - - testResourceContactIdMissing(); - testServiceCategoryExist(); - testServiceBadCategoryCreate(); - 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); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - 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 and special characters - 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()); - } +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; - public void markDistributionAsDeployedTestAlreadyDeployed() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String resultAction = "DResult"; - String did = "123456"; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; - setupBeforeDeploy(notifyAction, requestAction, did); - List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>(); - Map<String, Object> params = new HashMap<String, Object>(); - DistributionDeployEvent event = new DistributionDeployEvent(); +public class ServiceBusinessLogicTest { - 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); + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = 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 final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + 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); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); +// when(userValidations.validateUserRole(user)) + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setUserValidations(userValidations); + + 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); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); + 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 validateUserRoles(Role ... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + 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(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testInvalidProjectCode(); + testProjectCodeTooLong(); + testProjectCodeTooShort(); + + testResourceContactIdMissing(); + testServiceCategoryExist(); + testServiceBadCategoryCreate(); + 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); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + 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 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); + } + + 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); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + 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 and special characters + 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"; - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); + setupBeforeDeploy(notifyAction, requestAction, did); + List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>(); + Map<String, Object> params = new HashMap<String, Object>(); + DistributionDeployEvent event = new DistributionDeployEvent(); - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + 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.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); + 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()); - @Test - public void markDistributionAsDeployedTestSuccess() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String did = "123456"; + Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); - setupBeforeDeploy(notifyAction, requestAction, did); + } - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + @Test + public void markDistributionAsDeployedTestSuccess() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; - } + setupBeforeDeploy(notifyAction, requestAction, did); + List<Role> roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.OPS); + when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true)); + 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"; + //@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); + 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<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND); - Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); + Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND); + Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); - Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isRight()); - assertEquals(404, markDeployed.right().value().getStatus().intValue()); + Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isRight()); + assertEquals(404, markDeployed.right().value().getStatus().intValue()); - } + } - private void testServiceBadCategoryCreate() { + 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); + 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()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - } + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } - // Service category - stop - // Service projectCode - start - private void testInvalidProjectCode() { + // Service category - stop + // Service projectCode - start + private void testInvalidProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("koko!!"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("koko!!"); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooLong() { + private void testProjectCodeTooLong() { - Service serviceExist = createServiceObject(false); - String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; - serviceExist.setProjectCode(tooLongProjectCode); + Service serviceExist = createServiceObject(false); + String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; + serviceExist.setProjectCode(tooLongProjectCode); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooShort() { + private void testProjectCodeTooShort() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("333"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("333"); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testMissingProjectCode() { + private void testMissingProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode(null); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode(null); - Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); - } + 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(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// @Test +// public void testDeleteMarkedServicesNoServices() { +// List<String> ids = new ArrayList<String>(); +// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// } - - @Test - @Ignore - 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(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).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(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); - - when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); - when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); - - Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); - when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); - - Either<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)); - - } - - 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.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()); - } - 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<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true)); - Mockito.when(toscaOperationFacade.getToscaElement(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); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testFindGroupInstanceOnRelatedComponentInstance() { - - Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class; - String methodName = "findGroupInstanceOnRelatedComponentInstance"; - Object invalidId = "invalidId"; - - Component service = createNewService(); - List<ComponentInstance> componentInstances = service.getComponentInstances(); - - Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; - Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - Class[] argClasses = {Component.class, String.class,String.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); - assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); - - Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); - - Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; - - findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private Component createNewService() { - - Service service = new Service(); - int listSize = 3; - service.setName("serviceName"); - service.setUniqueId("serviceUniqueId"); - List<ComponentInstance> componentInstances = new ArrayList<>(); - ComponentInstance ci; - for(int i= 0; i<listSize; ++i){ - ci = new ComponentInstance(); - ci.setName("ciName" + i); - ci.setUniqueId("ciId" + i); - List<GroupInstance> groupInstances= new ArrayList<>(); - GroupInstance gi; - for(int j = 0; j<listSize; ++j){ - gi = new GroupInstance(); - gi.setName(ci.getName( )+ "giName" + j); - gi.setUniqueId(ci.getName() + "giId" + j); - groupInstances.add(gi); - } - ci.setGroupInstances(groupInstances); - componentInstances.add(ci); - } - service.setComponentInstances(componentInstances); - return service; - } - - - @Test - public void testDerivedFromGeneric() { - Service service = createServiceObject(true); - when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); - Either<Service, ResponseFormat> createResponse = bl.createService(service, user); - assertTrue(createResponse.isLeft()); - service = createResponse.left().value(); - assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); - assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); - } - - - private Resource setupGenericServiceMock(){ - Resource genericService = new Resource(); - genericService.setVersion("1.0"); - genericService.setToscaResourceName(GENERIC_SERVICE_NAME); - return genericService; - } +// } + + @Test + @Ignore + 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(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).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(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); + + when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); + when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); + + Either<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)); + + } + + private Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setUniqueId("sid"); + 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.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()); + } + 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<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true)); + Mockito.when(toscaOperationFacade.getToscaElement(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); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test @Ignore + public void testFindGroupInstanceOnRelatedComponentInstance() { + + Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class; + String methodName = "findGroupInstanceOnRelatedComponentInstance"; + Object invalidId = "invalidId"; + + Component service = createNewService(); + List<ComponentInstance> componentInstances = service.getComponentInstances(); + + Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; + Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + Class[] argClasses = {Component.class, String.class,String.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); + assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); + + Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); + + Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; + + findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i<listSize; ++i){ + ci = new ComponentInstance(); + ci.setName("ciName" + i); + ci.setUniqueId("ciId" + i); + List<GroupInstance> groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j<listSize; ++j){ + gi = new GroupInstance(); + gi.setName(ci.getName( )+ "giName" + j); + gi.setUniqueId(ci.getName() + "giId" + j); + groupInstances.add(gi); + } + ci.setGroupInstances(groupInstances); + componentInstances.add(ci); + } + service.setComponentInstances(componentInstances); + return service; + } + + + @Test + public void testDerivedFromGeneric() { + Service service = createServiceObject(true); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); + Either<Service, ResponseFormat> createResponse = bl.createService(service, user); + assertTrue(createResponse.isLeft()); + service = createResponse.left().value(); + assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); + assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); + } + + + private Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java new file mode 100644 index 0000000000..fe7152608c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java @@ -0,0 +1,202 @@ +package org.openecomp.sdc.be.components; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionBLTest { + + @InjectMocks + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + + @Mock + ServiceDistributionValidation serviceDistributionValidation; + + @Mock + HealthCheckBusinessLogic healthCheckBusinessLogic; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + ComponentsUtils componentsUtils; + + @Mock + DistributionEngine distributionEngine; + + private Service serviceToActivate; + private ActivationRequestInformation activationRequestInformation; + private String WORKLOAD_CONTEXT = "vnfContext"; + private String TENANT = "tenant"; + private String DID = "distributionId"; + private User modifier; + + + public ServiceDistributionBLTest() { + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + MockitoAnnotations.initMocks(this); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + bl.setComponentsUtils(componentsUtils); + serviceToActivate = new Service(); + serviceToActivate.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + activationRequestInformation = new ActivationRequestInformation(serviceToActivate, WORKLOAD_CONTEXT, TENANT); + when(toscaOperationFacade.getToscaElement(anyString(), any(ComponentParametersView.class))) + .thenReturn(Either.left(serviceToActivate)); + when(distributionEngine.buildServiceForDistribution(any(Service.class), anyString(), anyString())) + .thenReturn(new NotificationDataImpl()); + modifier = new User(); + modifier.setUserId("uid"); + modifier.setFirstName("user"); + } + + @Test + public void testActivateServiceOnTenantValidationFails() { + int VALIDATION_FAIL_STATUS = 666; + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS))); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == VALIDATION_FAIL_STATUS); + } + + @Test + public void testNoDeploymentArtifacts() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 409); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4139")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionAuthenticationFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.AUTHENTICATION_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionUnknownHostFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.UNKNOWN_HOST); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionConnectionErrorFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.CONNNECTION_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionObjectNotFoundFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.OBJECT_NOT_FOUND); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionGeneralFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.GENERAL_ERROR); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionOk() { + mockAllMethodsUntilDENotification(); + ThreadLocalsHolder.setUuid(DID); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.OK); + Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isLeft()); + assertTrue(stringResponseFormatEither.left().value().equals(DID)); + } + + private void mockAllMethodsUntilDENotification() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.OK); + } + + private Either<String, ResponseFormat> callActivateServiceOnTenantWIthDefaults() { + return bl.activateServiceOnTenantEnvironment("serviceId", "envId", modifier, new ServiceDistributionReqInfo("workload")); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java deleted file mode 100644 index 90a02a2fc5..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.openecomp.sdc.be.components.clean; - -import org.junit.Test; - - -public class AsdcComponentsCleanerTaskTest { - - private AsdcComponentsCleanerTask createTestSubject() { - return new AsdcComponentsCleanerTask(); - } - - - @Test - public void testInit() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.init(); - } - - - @Test - public void testDestroy() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.destroy(); - } - - - @Test - public void testStartTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.startTask(); - } - - - @Test - public void testStopTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.stopTask(); - } - - - - - - @Test - public void testRun() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.run(); - } -}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java new file mode 100644 index 0000000000..7df88c1cd9 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.http.HttpStatus; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static org.junit.Assert.assertTrue; + +public class AaiMockRequestHandlerTest extends BeConfDependentTest { + + @Ignore + @Test + public void testGetOperationalEnvJson() { + String id = "OEid4"; + AaiRequestHandler aaiRequestHandler = new AaiRequestHandler(); + aaiRequestHandler.init(); + HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id); + + if (resp.getStatusCode() == HttpStatus.SC_OK) { + try { + String response = resp.getResponse(); + System.out.println("The rest response is:"); + System.out.println(response); + + OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(response); + + System.out.println(String.format("Get \"%s\" operational environment. %s", id, operationalEnvInfo)); + System.out.println(operationalEnvInfo); + } + catch (Exception e) { + System.out.println(String.format("Json convert to OperationalEnvInfo failed with exception %s", e)); + System.out.println(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + else { + System.out.println("The rest response is:"); + String response = resp.getResponse(); + System.out.println(response); + System.out.println(String.format("Get \"%s\" operational environment failed with statusCode: %s, response: %s, description: %s", id, resp.getStatusCode(), resp.getResponse(), resp.getDescription())); + System.out.println(resp.getStatusCode()); + } + + assertTrue(true); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java new file mode 100644 index 0000000000..d425e6d0f5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java @@ -0,0 +1,77 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaIdentityManager; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class CambriaHandlerTest { + @Spy + private CambriaHandler handler = new CambriaHandler(); + + @Mock + private CambriaIdentityManager createIdentityManager; + + private ApiCredential apiCredential = new ApiCredential("apiKey", "apiSecret"); + + @BeforeClass + public static void beforeClass() { + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + new ConfigurationManager(configurationSource); + } + + + @Before + public void startUp() throws MalformedURLException, GeneralSecurityException { + doReturn(createIdentityManager).when(handler).buildCambriaClient(any()); + } + + @Test + public void testCreateUebKeys() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenReturn(apiCredential); + Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + + Mockito.verify(createIdentityManager).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isLeft()); + + } + + @Test + public void testCreateUebKeys_FAIL() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenThrow(new CambriaApiException("Error Message")); + Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + Mockito.verify(createIdentityManager, Mockito.never()).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isRight()); + CambriaErrorResponse response = eitherCreateUebKeys.right().value(); + assertEquals("Unexpected Operational Status", CambriaOperationStatus.CONNNECTION_ERROR, response.getOperationStatus()); + assertEquals("Unexpected HTTP Code", 500, response.getHttpCode().intValue()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java new file mode 100644 index 0000000000..45906c6f30 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRConsumer; +import com.google.gson.GsonBuilder; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.concurrent.ExecutorService; +import java.util.stream.IntStream; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class Dev2DevDmaapConsumerTest { + @Autowired + private ExecutorFactory executorFactory; + @Autowired + private DmaapClientFactory dmaapClientFactory; + + static ExecutorService notificationExecutor; + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @Test + public void runConsumer() throws Exception{ + boolean isRunConsumer = false ; //change this to true if you wish to run consumer,default should be false + if ( isRunConsumer ){ + consumeDmaapTopic(); + }else{ + System.out.println( "CONSUMER TEST is disabled!!!! "); + } + assert true; + } + //@Ignore + //@Test + public void consumeDmaapTopic() throws Exception { + Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + System.out.println("uncaughtException -> "); + } + }; + + DmaapConsumerConfiguration dmaapConsumerParams = configurationManager.getConfiguration().getDmaapConsumerConfiguration(); + String topic = dmaapConsumerParams.getTopic(); + System.out.println(String.format( "Starting to consume topic %s for DMAAP consumer with the next parameters %s. ", topic, dmaapConsumerParams) ); + MRConsumer consumer = dmaapClientFactory.create( dmaapConsumerParams ); + notificationExecutor = executorFactory.create(topic + "Consumer", handler); + final int LIMIT = 2; + IntStream.range(0,LIMIT).forEach( i -> { + System.out.println("Trying to fetch messages from topic: "+ topic); + try { + Iterable<String> messages = consumer.fetch(); + if (messages != null) { + for (String msg : messages) { + System.out.println(String.format( "The DMAAP message %s received. The topic is %s.", msg, topic) ); + handleMessage(msg); + } + } + } + catch (Exception e) { + System.out.println("The exception occured upon fetching DMAAP message "+ e); + } + } + ); + + + } + private void handleMessage(String msg){ + try{ + DmaapNotificationDataImpl notificationData = new GsonBuilder().create().fromJson(msg,DmaapNotificationDataImpl.class); + System.out.println( "successfully parsed notification for environemnt "+notificationData.getOperationalEnvironmentId()); + }catch (Exception e){ + System.out.println( "failed to parse notification"); + } + } + @After + public void after(){ + if (notificationExecutor!=null && !notificationExecutor.isTerminated()) + notificationExecutor.shutdown(); + } +}
\ No newline at end of file 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 index 8d48a4c320..04aa242b03 100644 --- 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 @@ -20,13 +20,6 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -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.config.ConfigurationManager; @@ -38,131 +31,138 @@ import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class DistributionEngineConfigTest { - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); + @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()); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } - @Test - public void validateMissingEnvironments() { + @Test + public void validateMissingEnvironments() { - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - String uebPublicKey = "uebPublicKey"; - String uebSecretKey = "uebSecretKey"; + String uebPublicKey = "uebPublicKey"; + String uebSecretKey = "uebSecretKey"; - DistributionEngine distributionEngine = new DistributionEngine(); + DistributionEngine distributionEngine = new DistributionEngine(); - List<String> environments = new ArrayList<String>(); - environments.add("PROD"); - deConfiguration.setEnvironments(environments); + 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"); + 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); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); - ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); + ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); - ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); + ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); - deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); - deConfiguration.setDistributionStatusTopicName("statusTopic"); + 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); + 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); + 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); + boolean isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebServers(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("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.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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setEnvironments(environments); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebPublicKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebSecretKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionNotifTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionStatusTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitMaxIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitRetryIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("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 index 990ea4f99b..1fa0fc60b7 100644 --- 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 @@ -20,115 +20,114 @@ 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; 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.BeConfDependentTest; 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; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; -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); - - } +public class DistributionEngineHealthCheckTest extends BeConfDependentTest { + + @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 index 5bf12d56bc..03a6625cae 100644 --- 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 @@ -20,19 +20,9 @@ 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.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.BeforeClass; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -41,224 +31,252 @@ 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.be.resources.data.OperationalEnvironmentEntry; 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); - - @BeforeClass - public static 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(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .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(); +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; - Set<String> topics = new HashSet<String>(); - topics.add(realNotifTopic); - topics.add(realStatusTopic); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - List<String> uebServers = new ArrayList<>(); - uebServers.add("server1"); - 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 cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .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); - } - - } +public class DistributionEngineInitTaskTest { - @Test - public void testInitFlowScenarioFailToRegister() { + @Mock + private ComponentsUtils componentsUtils; - 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); + @Mock + private CambriaHandler cambriaHandler; - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + new ConfigurationManager(configurationSource); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + componentsUtils = Mockito.mock(ComponentsUtils.class); + cambriaHandler = Mockito.mock(CambriaHandler.class); + } + + @Test + public void checkIncrement() { - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + 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, readEnvFromConfig(deConfiguration)); + + 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); + + } + + @SuppressWarnings("unchecked") + @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); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); + 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(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); - boolean initFlow = initTask.initFlow(); - assertFalse("check init flow failed", initFlow); + } - } + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioSuccessTopicsAlreadyExists() { - @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); - - } + 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"); + 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 cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + try { + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + } catch (Exception e) { + assertTrue("Should not throw exception", false); + } + + } + + @SuppressWarnings("unchecked") + @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(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + @SuppressWarnings("unchecked") + @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, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + private OperationalEnvironmentEntry readEnvFromConfig(DistributionEngineConfiguration distributionEngineConfiguration) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey()); + entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey()); + Set<String> puebEndpoints = new HashSet<>(); + if(distributionEngineConfiguration.getUebServers() != null) + puebEndpoints.addAll(distributionEngineConfiguration.getUebServers()); + entry.setDmaapUebAddress(puebEndpoints); + String envName = "UNKNOWN"; + if(CollectionUtils.isNotEmpty(distributionEngineConfiguration.getEnvironments())) + envName = distributionEngineConfiguration.getEnvironments().get(0); + entry.setEnvironmentId(envName); + return entry; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java new file mode 100644 index 0000000000..b1a43eaa57 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.OperationalEnvironmentBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class DistributionEngineTest { + + public static final String DISTRIBUTION_ID = "distId"; + public static final String ENV_ID = "envId"; + public static final String USER_ID = "userId"; + public static final String MODIFIER = "modifier"; + + @InjectMocks + private DistributionEngine testInstance; + + @Mock + private EnvironmentsEngine environmentsEngine; + + @Mock + private DistributionNotificationSender distributionNotificationSender; + + private DummyDistributionConfigurationManager distributionEngineConfigurationMock; + + private Map<String, OperationalEnvironmentEntry> envs; + + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + envs = getEnvs(ENV_ID); + } + + @Test + public void notifyService() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.OK, actionStatus); + } + + @Test + public void notifyService_couldNotResolveEnvironment() throws Exception { + when(environmentsEngine.getEnvironments()).thenReturn(envs); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, new Service(), new NotificationDataImpl(), "someNonExisitngEnv", USER_ID, MODIFIER); + assertEquals(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, actionStatus); + verifyZeroInteractions(distributionNotificationSender); + } + + @Test + public void notifyService_failedWhileSendingNotification() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); + } + + private Map<String, OperationalEnvironmentEntry> getEnvs(String ... environmentIds) { + Set<String> uebAddress = new HashSet<>(); + uebAddress.add("someAddress"); + return Stream.of(environmentIds) + .map(id -> new OperationalEnvironmentBuilder().setEnvId(id).setDmaapUebAddress(uebAddress).build()) + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java new file mode 100644 index 0000000000..1118385143 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; + +public class DummyDistributionConfigurationManager { + + private DistributionEngineConfiguration configurationMock = Mockito.mock(DistributionEngineConfiguration.class); + + public DummyDistributionConfigurationManager() { + new ConfigurationManager(new DummyConfigurationSource()); + } + + public class DummyConfigurationSource implements ConfigurationSource { + + @SuppressWarnings("unchecked") + @Override + public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + if (className.equals(DistributionEngineConfiguration.class)) { + return (T)configurationMock; + } + return null; + } + + @Override + public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + + } + } + + public DistributionEngineConfiguration getConfigurationMock() { + return configurationMock; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java new file mode 100644 index 0000000000..514618c89a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java @@ -0,0 +1,190 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import fj.data.Either; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(value = MockitoJUnitRunner.class) +public class EnvironmentsEngineTest { + + @InjectMocks + private EnvironmentsEngine envEngine; + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ConfigurationManager configurationManager; + @Mock + private DistributionEngineConfiguration distributionEngineConfiguration; + @Mock + private AaiRequestHandler aaiRequestHandler; + + @Before + public void preStart() { + when(configurationManager.getDistributionEngineConfiguration()).thenReturn(distributionEngineConfiguration); + envEngine.setConfigurationManager(configurationManager); + } + + @Test + public void testInit() { + List<OperationalEnvironmentEntry> entryList = Arrays.asList(createOpEnvEntry("Env1"), createOpEnvEntry("Env2")); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> successEither = Either.left(entryList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(successEither); + + when(distributionEngineConfiguration.getEnvironments()).thenReturn(Arrays.asList("Env Loaded From Configuration")); + when(distributionEngineConfiguration.getUebPublicKey()).thenReturn("Dummy Public Key"); + when(distributionEngineConfiguration.getUebSecretKey()).thenReturn("Dummy Private Key"); + when(distributionEngineConfiguration.getUebServers()).thenReturn( + Arrays.asList("uebsb91kcdc.it.att.com:3904", "uebsb92kcdc.it.att.com:3904", "uebsb91kcdc.it.att.com:3904")); + + envEngine.init(); + + Map<String, OperationalEnvironmentEntry> mapEnvs = envEngine.getEnvironments(); + assertEquals("unexpected size of map",3, mapEnvs.size()); + } + + + @Test + public void testGetFullOperationalEnvByIdSuccess() { + String json = getFullOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + @Test + public void testGetPartialOperationalEnvByIdSuccess() { + String json = getPartialOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + + @Test + public void testGetOperationalEnvByIdFailedByJsonConvert() { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + + HttpResponse<String> restResponse = new HttpResponse<String>(jsonCorrupted, HttpStatus.SC_OK, "Successfully Completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_INTERNAL_SERVER_ERROR, response.right().value()); + } + + @Test + public void testGetOperationalEnvByIdFailed404() { + String json = getFullOperationalEnvJson(); + HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_NOT_FOUND, "Not Found"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_NOT_FOUND, response.right().value()); + } + + + @Test(expected = IOException.class) + public void testCorruptedOperationalEnvJson() throws IOException { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + OperationalEnvInfo.createFromJson(jsonCorrupted); + } + + private String getCorruptedOperationalEnvJson() { + return "{\"OPERATIONAL-environment-name\":\"Op Env Name\"," + + "\"OPERATIONAL-environment-type\":\"VNF\"," + + "\"OPERATIONAL-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"}"; + } + + private String getPartialOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"UUID of Operational Environment\"," + + "\"operational-environment-name\":\"Op Env Name\"," + + "\"operational-environment-type\":\"VNF\"," + + "\"operational-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"," + + "\"workload-context\":\"VNF_Development\"," + + "\"resource-version\":\"1505228226913\"," + + "\"relationship-list\":{" + + "\"relationship\":[]" + + "}" + + "}"; + } + + private String getFullOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"OEid1\"," + + "\"operational-environment-name\":\"OEname1\"," + + "\"operational-environment-type\":\"OEtype1\"," + + "\"operational-environment-status\":\"OEstatus1\"," + + "\"tenant-context\":\"OEtenantcontext1\"," + + "\"workload-context\":\"OEworkloadcontext1\"," + + "\"resource-version\":\"1511363173278\"," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-to\":\"operational-environment\"," + + "\"relationship-label\":\"managedBy\"," + + "\"related-link\":\"/aai/v12/cloud-infrastructure/operational-environments/operational-environment/OEid3\"," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"operational-environment.operational-environment-id\"," + + "\"relationship-value\":\"OEid3\"" + + "}" + + "]," + + "\"related-to-property\":[" + + "{" + + "\"property-key\":\"operational-environment.operational-environment-name\"," + + "\"property-value\":\"OEname3\"" + + "}]}]}}"; + } + + private OperationalEnvironmentEntry createOpEnvEntry(String name) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setEnvironmentId(name); + return entry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java new file mode 100644 index 0000000000..1a2ca4840d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java @@ -0,0 +1,310 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import cucumber.api.java.Before; +import cucumber.api.java.en.Given; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; +import fj.data.Either; +import org.apache.commons.lang.NotImplementedException; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.http.HttpStatus; +import org.junit.Assert; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static java.util.Objects.isNull; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class StepsTenantIsolation { + + // Notification Fields + private String operationalEnvironmentId = "28122015552391"; + private String operationalEnvironmentName = "Operational Environment Name"; + private String operationalEnvironmentType; + private String tenantContext ; + private String workloadContext; + private String action; + + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private AaiRequestHandler aaiRequestHandler; + @Mock + private CambriaHandler cambriaHandler; + @InjectMocks + @Spy + private EnvironmentsEngine envEngine; + + private boolean isSuccessful; + private boolean cassandraUp; + + @Before + public void beforeScenario() { + MockitoAnnotations.initMocks(this); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)) + .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND)); + doNothing().when(envEngine).createUebTopicsForEnvironments(); + envEngine.init(); + } + + // ############################# Given - Start ############################# + @Given("^Dmaap consumer recieved notification with fields (.*)$") + public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable { + Gson gson = new GsonBuilder().create(); + IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class); + if (!isNull(notification.getOperationalEnvironmentType())) { + this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName(); + } + if( !isEmpty(notification.getOperationalEnvironmentId()) ){ + this.operationalEnvironmentId = notification.getOperationalEnvironmentId(); + } + if( !isNull(notification.getAction()) ){ + this.action = notification.getAction().getActionName(); + } + + } + + @Given("^Cassandra service status is (.*)$") + public void cassandra_service_status_is(String status) throws Throwable { + switch (status) { + case "UP": + this.cassandraUp = true; + break; + case "DOWN": + when(operationalEnvironmentDao.get(operationalEnvironmentId)) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.GENERAL_ERROR); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^Record status is (.*)$") + public void record_status_is(String status) throws Throwable { + if (!cassandraUp) { + return; + } + Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherResult; + final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class); + switch (status) { + case "FOUND_IN_PROGRESS": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_COMPLETED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_FAILED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName()); + eitherResult = Either.left(entryMock); + break; + case "NOT_FOUND": + eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND); + break; + default: + throw new NotImplementedException(); + } + + when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.OK); + } + + @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$") + public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable { + this.tenantContext = tenant; + this.workloadContext = workload; + HttpResponse<String> resp = Mockito.mock(HttpResponse.class); + when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp); + switch (aaiServiceStatus) { + case "UP": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK); + String aaiResponseTemplate = + //@formatter:off + "{\r\n" + + " \"operational-environment-id\": \"%s\",\r\n" + + " \"operational-environment-name\": \"%s\",\r\n" + + " \"operational-environment-type\": \"%s\",\r\n" + + " \"operational-environment-status\": \"IN-PROGRESS\",\r\n" + + " \"tenant-context\": \"%s\",\r\n" + + " \"workload-context\": \"%s\"\r\n" + + " }"; + //@formatter:on + when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId, + operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext)); + + break; + case "DOWN": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^AFT_DME service status is (.*)$") + public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable { + switch (aftDmeStatus) { + case "UP": + DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class); + when(mockItr.hasNext()).thenReturn(false); + when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr); + break; + case "DOWN": + when(epIterCreator.create(Mockito.anyString())) + .thenThrow(new DME2Exception("dummyCode", new NotImplementedException())); + break; + default: + throw new NotImplementedException(); + } + } + + @SuppressWarnings("unchecked") + @Given("^UEB service status is (.*)$") + public void ueb_service_status_is(String status) throws Throwable { + + Either<ApiCredential, CambriaErrorResponse> response; + switch (status) { + case "UP": + ApiCredential apiCredential = Mockito.mock(ApiCredential.class); + when(apiCredential.getApiKey()).thenReturn("MockAPIKey"); + when(apiCredential.getApiSecret()).thenReturn("MockSecretKey"); + response = Either.left(apiCredential); + break; + case "DOWN": + CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class); + response = Either.right(cambriaError); + break; + default: + throw new NotImplementedException(); + } + when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response); + } + // ############################# Given - End ############################# + + // ############################# When - Start ############################# + + @When("^handle message is activated$") + public void handle_message_is_activated() throws Throwable { + this.isSuccessful = envEngine.handleMessage(buildNotification()); + } + // ############################# When - End ############################# + + // ############################# Then - Start ############################# + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of eventType (.*)$") + public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class), + Mockito.any(IDmaapAuditNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to write message to audit log and table (.*)$") + public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable { + int count = isUnsupportedTypeEventRecorded ? 2 : 1; + verify(componentsUtils, Mockito.atLeast(count)) + .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId), + Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of action (.*)$") + public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of state (.*)$") + public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to save in-progress record (.*)$") + public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to get environment info from A&AI API (.*)$") + public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$") + public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts( + Mockito.anyString(), Mockito.anyString()); + + } + + @SuppressWarnings("unchecked") + @Then("^trying to create Ueb keys (.*)$") + public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^trying to create Ueb Topics (.*)$") + public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^handle message finished successfully (.*)$") + public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable { + Assert.assertTrue(this.isSuccessful == isSuccessfull); + } + + // ############################# Then - End ############################# + + private String buildNotification() { + String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n" + + " \"operationalEnvironmentName\": \"%s\",\r\n" + + " \"operationalEnvironmentType\": \"%s\",\r\n" + " \"tenantContext\": \"%s\",\r\n" + + " \"workloadContext\": \"%s\",\r\n" + " \"action\": \"%s\"}"; + + String notification = String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + return notification; + } + + private int getNumberOfCallsToValidate(boolean isValidated) { + return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java deleted file mode 100644 index 712e16d97a..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.openecomp.sdc.be.components.distribution.engine; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses( - -{ DistributionEngineInitTaskTest.class, DistributionEngineConfigTest.class, DistributionEngineHealthCheckTest.class, - VfModuleArtifactPayloadTest.class }) -public class TestSuite { // nothing -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java new file mode 100644 index 0000000000..9d0e8cd683 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java @@ -0,0 +1,135 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.matching.AnythingPattern; +import com.github.tomakehurst.wiremock.matching.UrlPattern; +import fj.data.Either; +import org.apache.http.HttpHeaders; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum; +import org.openecomp.sdc.be.components.distribution.engine.DummyDistributionConfigurationManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.*; +import org.openecomp.sdc.security.SecurityUtil; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +public class MsoRestClientTest { + + private static final String MSO_HOST = "127.0.0.1"; + private static final String MSO_API_URL = "onap/mso/infra/modelDistributions/v1"; + private static final String DISTRIBUTION_ID = "1000"; + + private MSORestClient msoRestClient; + + @ClassRule + public static WireMockRule msoRestServer = new WireMockRule(options() + .dynamicPort() + .bindAddress(MSO_HOST)); + + @Before + public void setupMsoServer() throws Exception { + String encodedPw = ""; + Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(getPwd()); + if(passkey.isLeft()) { + encodedPw = passkey.left().value(); + } + else { + throw new IllegalArgumentException(passkey.right().value()); + } + + msoRestServer.resetToDefaultMappings(); + msoRestServer.stubFor(patch(urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl()))) + .withBasicAuth(getUserName(), encodedPw) + .withHeader(HttpHeaders.CONTENT_TYPE, containing("application/json")) + .withRequestBody(matchingJsonPath("$.status")) + .withRequestBody(matchingJsonPath("$.errorReason", new AnythingPattern()))//error reason is not mandatory + .willReturn(aResponse().withStatus(200))); + } + + @Before + public void setUp() throws Exception { + DummyDistributionConfigurationManager distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + when(distributionEngineConfigurationMock.getConfigurationMock().getMsoConfig()).thenReturn(new MsoDummyConfig(msoRestServer.port())); + msoRestClient = new MSORestClient(); + } + + @Test + public void notifyDistributionComplete_emptyErrReason() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, ""); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + private int getNumOfRetries() { + return ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getNumOfRetries(); + } + + @Test + public void notifyDistributionComplete_noErrReason() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, null); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void notifyDistributionComplete_completeWithError() throws Exception { + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void testRetries() throws Exception { + int readTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getTimeouts().getReadTimeoutMs(); + int expectedNumOfRetries = getNumOfRetries(); + + UrlPattern msoReqUrlPattern = urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl())); + msoRestServer.stubFor(patch(msoReqUrlPattern) + .willReturn(new ResponseDefinitionBuilder().withFixedDelay(readTimeout + 1))); + HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + verify(expectedNumOfRetries + 1, patchRequestedFor(msoReqUrlPattern)); + assertThat(response.getStatusCode()).isEqualTo(500); + } + + private static String getDistributionsUrl() { + return "/distributions"; + } + + private static String getUserName() { + return "asdc"; + } + + private static String getPwd() { + return "OTLEp5lfVhYdyw5EAtTUBQ=="; + } + + private static class MsoDummyConfig extends ExternalServiceConfig { + int port; + + MsoDummyConfig(int port) { + this.port = port; + + BasicAuthorization basicAuthorization = new BasicAuthorization(); + basicAuthorization.setUserName(MsoRestClientTest.getUserName()); + basicAuthorization.setPassword(getPwd()); + HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(500, 2000), basicAuthorization); + httpClientConfig.setNumOfRetries(getNumOfRetries()); + super.setHttpClientConfig(httpClientConfig); + + HttpRequestConfig httpRequestConfig = new HttpRequestConfig(); + httpRequestConfig.setServerRootUrl(String.format("http://%s:%s/%s", MSO_HOST, this.port, MSO_API_URL)); + httpRequestConfig.getResourceNamespaces().put(MSORestClient.DISTRIBUTIONS_RESOURCE_CONFIG_PARAM, getDistributionsUrl()); + super.setHttpRequestConfig(httpRequestConfig); + } + + int getNumOfRetries() { + return 1; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index c57f2a65af..bebe29f13e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -20,28 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -55,6 +41,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -70,6 +57,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -84,294 +72,359 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; public class ArtifactBusinessLogicTest { - public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - @InjectMocks - private static ArtifactsBusinessLogic artifactBL; - @Mock - private ArtifactOperation artifactOperation; - @Mock - public ComponentsUtils componentsUtils; - @Mock - private IInterfaceLifecycleOperation lifecycleOperation; - @Mock - private IUserAdminOperation userOperation; - @Mock - private IElementOperation elementOperation; - @Mock - private ArtifactCassandraDao artifactCassandraDao; - @Mock - public ToscaOperationFacade toscaOperationFacade; - @Mock - private UserBusinessLogic userBusinessLogic; - @Mock - private NodeTemplateOperation nodeTemplateOperation; - @Mock - private ArtifactsOperations artifactsOperations; - - // public static final InformationDeployedArtifactsBusinessLogic - // informationDeployedArtifactsBusinessLogic = - // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); - - public static final Resource resource = Mockito.mock(Resource.class); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - - private static List<ArtifactType> getAllTypes() { - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); - for (String artifactType : artifactTypesList) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return artifactTypes; - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); - - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); - when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); - - Either<User, ActionStatus> getUserResult = Either.left(USER); - - when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); - - Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); - when(elementOperation.getAllArtifactTypes()).thenReturn(getType); - - when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); - } - - @Test - public void testValidJson() { - ArtifactDefinition ad = createArtifactDef(); - - String jsonArtifact = ""; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - try { - jsonArtifact = mapper.writeValueAsString(ad); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); - assertEquals(ad, afterConvert); - } - - private ArtifactDefinition createArtifactDef() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1.yaml"); - ad.setArtifactLabel("label1"); - ad.setDescription("description"); - ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - return ad; - } - - @Test - public void testInvalidStringGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidNumberGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidGroupTypeWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidTimeoutWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testValidMibAritactsConfiguration() { - Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - } - - @Test - public void testDownloadServiceArtifactByNames() { - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); - esArtifactData.setDataAsArray(payload); - Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); - when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); - List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); - serviceList.add(service); - Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); - when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); - Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = - artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - assertTrue(downloadServiceArtifactByNamesRes.isLeft()); - assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); - } - - @Test - public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) - .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) - .build(); - - Resource component = new Resource(); - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); - assertTrue(heatEnvPlaceHolder.isLeft()); - assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); - } - - @Test - public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { - HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); - HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); - HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(heatParam1) - .addHeatParam(heatParam2) - .addHeatParam(heatParam3) - .build(); - - Resource component = new Resource(); - - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - - Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); - - assertTrue(heatEnvPlaceHolder.isLeft()); - ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); - List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); - assertEquals(listHeatParameters.size(), 3); - verifyHeatParam(listHeatParameters.get(0), heatParam1); - verifyHeatParam(listHeatParameters.get(1), heatParam2); - verifyHeatParam(listHeatParameters.get(2), heatParam3); - } - - private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { - assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); - assertNull(heatEnvParam.getCurrentValue()); - } + public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + private final static String RESOURCE_INSTANCE_NAME = "Service-111"; + private final static String INSTANCE_ID = "S-123-444-ghghghg"; + + private final static String ARTIFACT_NAME = "service-Myservice-template.yml"; + private final static String ARTIFACT_LABEL = "assettoscatemplate"; + private final static String ES_ARTIFACT_ID = "123123dfgdfgd0"; + private final static byte[] PAYLOAD = "some payload".getBytes(); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + private static ArtifactsBusinessLogic artifactBL; + @Mock + private ArtifactOperation artifactOperation; + @Mock + public ComponentsUtils componentsUtils; + @Mock + private IInterfaceLifecycleOperation lifecycleOperation; + @Mock + private IUserAdminOperation userOperation; + @Mock + private IElementOperation elementOperation; + @Mock + private ArtifactCassandraDao artifactCassandraDao; + @Mock + public ToscaOperationFacade toscaOperationFacade; + @Mock + private UserBusinessLogic userBusinessLogic; + @Mock + private NodeTemplateOperation nodeTemplateOperation; + @Mock + private ArtifactsOperations artifactsOperations; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + TitanDao titanDao; + + // public static final InformationDeployedArtifactsBusinessLogic + // informationDeployedArtifactsBusinessLogic = + // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); + + public static final Resource resource = Mockito.mock(Resource.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + + private static List<ArtifactType> getAllTypes() { + List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); + List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return artifactTypes; + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); + when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); + + Either<User, ActionStatus> getUserResult = Either.left(USER); + + when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); + + Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes()); + when(elementOperation.getAllArtifactTypes()).thenReturn(getType); + + when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = ""; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try { + jsonArtifact = mapper.writeValueAsString(ad); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); + assertEquals(ad, afterConvert); + } + + private ArtifactDefinition createArtifactDef() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1.yaml"); + ad.setArtifactLabel("label1"); + ad.setDescription("description"); + ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + return ad; + } + + @Test + public void testInvalidStringGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidNumberGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidGroupTypeWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidTimeoutWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testValidMibAritactsConfiguration() { + Map<String, ArtifactTypeConfig> componentDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + } + + @Test + public void testDownloadServiceArtifactByNames() { + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); + + ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); + esArtifactData.setDataAsArray(payload); + Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData); + when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); + List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>(); + serviceList.add(service); + Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList); + when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); + Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes = + artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + assertTrue(downloadServiceArtifactByNamesRes.isLeft()); + assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); + } + + @Test + public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) + .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) + .build(); + + Resource component = new Resource(); + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); + assertTrue(heatEnvPlaceHolder.isLeft()); + assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); + } + + @Test + public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { + HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); + HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); + HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(heatParam1) + .addHeatParam(heatParam2) + .addHeatParam(heatParam3) + .build(); + + Resource component = new Resource(); + + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + + Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); + + assertTrue(heatEnvPlaceHolder.isLeft()); + ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); + List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters(); + assertEquals(listHeatParameters.size(), 3); + verifyHeatParam(listHeatParameters.get(0), heatParam1); + verifyHeatParam(listHeatParameters.get(1), heatParam2); + verifyHeatParam(listHeatParameters.get(2), heatParam3); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, true); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndNotInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, false); + verify(titanDao, times(1)).commit(); + } + + private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { + assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); + assertNull(heatEnvParam.getCurrentValue()); + } // @Test - // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ - // ArtifactDefinition createArtifactDef = createArtifactDef(); - // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); - // - // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL - // - // assertTrue(validateResult.isLeft()); - // ArtifactDefinition validatedArtifact = validateResult.left().value(); - // - // assertEquals(createArtifactDef.getArtifactGroupType(), - // validatedArtifact.getArtifactGroupType()); - // assertEquals(new Integer(0), validatedArtifact.getTimeout()); - // assertFalse(validatedArtifact.getMandatory()); - // assertFalse(validatedArtifact.getServiceApi()); - // - // } + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL + // + // assertTrue(validateResult.isLeft()); + // ArtifactDefinition validatedArtifact = validateResult.left().value(); + // + // assertEquals(createArtifactDef.getArtifactGroupType(), + // validatedArtifact.getArtifactGroupType()); + // assertEquals(new Integer(0), validatedArtifact.getTimeout()); + // assertFalse(validatedArtifact.getMandatory()); + // assertFalse(validatedArtifact.getServiceApi()); + // + // } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java index 8ad9bf80b2..18af7a035a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.Collections; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,12 +28,21 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + public class ArtifactResolverTest { private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); - private Service service, noArtifactsService; - private Resource resource, noArtifactsResource; - private ComponentInstance componentInstance, noArtifactsInstance; + private Service service; + private Service noArtifactsService; + private Resource resource; + private Resource noArtifactsResource; + private ComponentInstance componentInstance; + private ComponentInstance noArtifactsInstance; @Before public void setUp() throws Exception { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java index 41835a6cdc..9b2fb3773b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -20,17 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,58 +36,68 @@ import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.common.util.CapabilityTypeNameEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class CapabilityTypeImportManagerTest { - @InjectMocks - private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + @InjectMocks + private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() { - when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { - public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() { + when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() { + public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void testCreateCapabilityTypes() throws IOException { - String ymlContent = getCapabilityTypesYml(); - Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void testCreateCapabilityTypes() throws IOException { + String ymlContent = getCapabilityTypesYml(); + Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); - assertTrue(capabilityTypesList.size() == 14); - Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); - for (CapabilityTypeDefinition capType : capabilityTypesList) { - capibilityTypeMap.put(capType.getType(), capType); - } - assertTrue(capabilityTypesList.size() == 14); + List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value(); + assertTrue(capabilityTypesList.size() == 14); + Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>(); + for (CapabilityTypeDefinition capType : capabilityTypesList) { + capibilityTypeMap.put(capType.getType(), capType); + } + assertTrue(capabilityTypesList.size() == 14); - for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { - assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); - } + for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { + assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); + } - } + } - private String getCapabilityTypesYml() throws IOException { - Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getCapabilityTypesYml() throws IOException { + Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java index 2c83c60fc6..8a07e26161 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -45,64 +36,66 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; - -import fj.data.Either; - -public class CategoriesImportManagerTest { - @InjectMocks - static CategoriesImportManager importManager = new CategoriesImportManager(); - public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - static Logger log = Mockito.spy(Logger.class); - private static SubCategoryDefinition subcategory; - - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId("123"); - - when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { - Object[] args = invocation.getArguments(); - CategoryDefinition category = (CategoryDefinition) args[0]; - category.setUniqueId("123"); - Either<CategoryDefinition, ActionStatus> ans = Either.left(category); - return ans; - }); - when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { - public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); - Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); - return ans; - } - - }); - - // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void importCategoriesTest() throws IOException { - String ymlContent = getYmlContent(); - Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; - } +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } +public class CategoriesImportManagerTest { + @InjectMocks + static CategoriesImportManager importManager = new CategoriesImportManager(); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + private static SubCategoryDefinition subcategory; + + @BeforeClass + public static void beforeClass() throws IOException { + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId("123"); + + when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> { + Object[] args = invocation.getArguments(); + CategoryDefinition category = (CategoryDefinition) args[0]; + category.setUniqueId("123"); + Either<CategoryDefinition, ActionStatus> ans = Either.left(category); + return ans; + }); + when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() { + public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); + Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory); + return ans; + } + + }); + + // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importCategoriesTest() throws IOException { + String ymlContent = getYmlContent(); + Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 65f7ac46b6..a5d05eff2c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -1,23 +1,22 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiPredicate; - +import fj.data.Either; import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; @@ -32,214 +31,354 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiPredicate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceBusinessLogic class */ public class ComponentInstanceBusinessLogicTest { - - private final static String USER_ID = "jh0003"; - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - private static ToscaOperationFacade toscaOperationFacade; - private static UserBusinessLogic userAdmin; - - private static ComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentInstanceBusinessLogic resourceBusinessLogic; - private static User user; - private static Component service; - private static Component resource; - private static ComponentInstance toInstance; - private static ComponentInstance fromInstance; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - @BeforeClass - public static void setup() { - createMocks(); - setMocks(); - stubMethods(); - createComponents(); - } - - @Test - public void testGetRelationByIdSuccess(){ - getServiceRelationByIdSuccess(service); - getServiceRelationByIdSuccess(resource); - } - - @Test - public void testGetRelationByIdUserValidationFailure(){ - getServiceRelationByIdUserValidationFailure(service); - getServiceRelationByIdUserValidationFailure(resource); - } - - @Test - public void testGetRelationByIdComponentNotFoundFailure(){ - getRelationByIdComponentNotFoundFailure(service); - getRelationByIdComponentNotFoundFailure(resource); - } - - @SuppressWarnings("unchecked") - private void getServiceRelationByIdSuccess(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); - when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); - - Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); - when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isLeft()); - } - - private void getServiceRelationByIdUserValidationFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private void getRelationByIdComponentNotFoundFailure(Component component){ - Either<User, ActionStatus> eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private static void createMocks() { - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - userAdmin = Mockito.mock(UserBusinessLogic.class); - user = Mockito.mock(User.class); - } - - private static void setMocks() { - serviceBusinessLogic = new ServiceComponentInstanceBusinessLogic(); - serviceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - serviceBusinessLogic.setUserAdmin(userAdmin); - serviceBusinessLogic.setComponentsUtils(componentsUtils); - - resourceBusinessLogic = new VFComponentInstanceBusinessLogic(); - resourceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - resourceBusinessLogic.setUserAdmin(userAdmin); - resourceBusinessLogic.setComponentsUtils(componentsUtils); - } - - private static void stubMethods() { - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); - } - - private static void createComponents() { - createRelation(); - createInstances(); - createService(); - createResource(); - } - - private static void createResource() { - resource = new Resource(); - resource.setUniqueId(COMPONENT_ID); - resource.setComponentInstancesRelations(Lists.newArrayList(relation)); - resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - resource.setCapabilities(toInstance.getCapabilities()); - resource.setRequirements(fromInstance.getRequirements()); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - } - - - private static void createService() { - service = new Service(); - service.setUniqueId(COMPONENT_ID); - service.setComponentInstancesRelations(Lists.newArrayList(relation)); - service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - service.setCapabilities(toInstance.getCapabilities()); - service.setRequirements(fromInstance.getRequirements()); - service.setComponentType(ComponentTypeEnum.SERVICE); - } - - - private static void createInstances() { - toInstance = new ComponentInstance(); - toInstance.setUniqueId(TO_INSTANCE_ID); - - fromInstance = new ComponentInstance(); - fromInstance.setUniqueId(FROM_INSTANCE_ID); - - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - - Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); - capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); - - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - - - Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); - requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); - - toInstance.setCapabilities(capabilities); - fromInstance.setRequirements(requirements); - } - - - private static void createRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } + + private final static String USER_ID = "jh0003"; + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + private static ToscaOperationFacade toscaOperationFacade; + private static UserBusinessLogic userAdmin; + + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ForwardingPathOperation forwardingPathOperation; + private static User user; + private static UserValidations userValidations; + private static Component service; + private static Component resource; + private static ComponentInstance toInstance; + private static ComponentInstance fromInstance; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + @BeforeClass + public static void setup() { + createMocks(); + setMocks(); + stubMethods(); + createComponents(); + + } + + @Before + public void init(){ + MockitoAnnotations.initMocks(this); + } + @Test + public void testGetRelationByIdSuccess(){ + getServiceRelationByIdSuccess(service); + getServiceRelationByIdSuccess(resource); + } + + @Test + public void testGetRelationByIdUserValidationFailure(){ + getServiceRelationByIdUserValidationFailure(service); + getServiceRelationByIdUserValidationFailure(resource); + } + + @Test + public void testGetRelationByIdComponentNotFoundFailure(){ + getRelationByIdComponentNotFoundFailure(service); + getRelationByIdComponentNotFoundFailure(resource); + } + + + + + @Test + public void testForwardingPathOnVersionChange(){ + getforwardingPathOnVersionChange(); + } + + private void getforwardingPathOnVersionChange(){ + String containerComponentParam="services"; + String containerComponentID="121-cont"; + String componentInstanceID="121-cont-1-comp"; + Service component=new Service(); + Map<String, ForwardingPathDataDefinition> forwardingPaths = generateForwardingPath(componentInstanceID); + + //Add existing componentInstance to component + List<ComponentInstance> componentInstanceList=new ArrayList<>(); + ComponentInstance oldComponentInstance=new ComponentInstance(); + oldComponentInstance.setName("OLD_COMP_INSTANCE"); + oldComponentInstance.setUniqueId(componentInstanceID); + oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,"1-comp"); + componentInstanceList.add(oldComponentInstance); + component.setComponentInstances(componentInstanceList); + component.setForwardingPaths(forwardingPaths); + + List<ComponentInstance> componentInstanceListNew=new ArrayList<>(); + ComponentInstance newComponentInstance=new ComponentInstance(); + String new_Comp_UID="2-comp"; + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,new_Comp_UID); + newComponentInstance.setUniqueId(new_Comp_UID); + componentInstanceListNew.add(newComponentInstance); + Component component2=new Service(); + component2.setComponentInstances(componentInstanceListNew); + + //Mock for getting component + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE)); + //Mock for getting component for componentInstance + when(toscaOperationFacade.getToscaFullElement(eq("1-comp"))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaFullElement(eq(new_Comp_UID))).thenReturn(Either.left(component2)); + + Either<Set<String>, ResponseFormat> resultOp = componentInstanceBusinessLogic.forwardingPathOnVersionChange + (containerComponentParam,containerComponentID,componentInstanceID,newComponentInstance); + Assert.assertEquals(1,resultOp.left().value().size()); + Assert.assertEquals("FP-ID-1",resultOp.left().value().iterator().next()); + + } + + + @Test + public void testDeleteForwardingPathsWhenComponentinstanceDeleted(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.left(new ComponentInstance())); + Assert.assertTrue(responseFormatEither.isLeft()); + + } + + @Test + public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.right(new ResponseFormat())); + Assert.assertTrue(responseFormatEither.isRight()); + + } + + + private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode , String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol("protocol"); + forwardingPath.setDestinationPortNumber("port"); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(fromNode, toNode, + "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } + + + + private Map<String, ForwardingPathDataDefinition> generateForwardingPath(String componentInstanceID) { + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + forwardingPath.setUniqueId("FP-ID-1"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = + new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY", + "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("1122", forwardingPath); + return forwardingPaths; + } + + @SuppressWarnings("unchecked") + private void getServiceRelationByIdSuccess(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.left(component); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement); + when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); + + Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability); + when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isLeft()); + } + + private void getServiceRelationByIdUserValidationFailure(Component component){ + //Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); + //when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.right(new ResponseFormat(404))); + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private void getRelationByIdComponentNotFoundFailure(Component component){ + Either<User, ActionStatus> eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private static void createMocks() { + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + userAdmin = Mockito.mock(UserBusinessLogic.class); + user = Mockito.mock(User.class); + userValidations = Mockito.mock(UserValidations.class); + forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + } + + private static void setMocks() { + componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic(); + componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); + componentInstanceBusinessLogic.setUserAdmin(userAdmin); + componentInstanceBusinessLogic.setComponentsUtils(componentsUtils); + componentInstanceBusinessLogic.setUserValidations(userValidations); + componentInstanceBusinessLogic.setForwardingPathOperation(forwardingPathOperation); + } + + private static void stubMethods() { + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.left(user)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); + } + + private static void createComponents() { + createRelation(); + createInstances(); + createService(); + createResource(); + } + + private static void createResource() { + resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setComponentInstancesRelations(Lists.newArrayList(relation)); + resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + resource.setCapabilities(toInstance.getCapabilities()); + resource.setRequirements(fromInstance.getRequirements()); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + } + + + private static void createService() { + service = new Service(); + service.setUniqueId(COMPONENT_ID); + service.setComponentInstancesRelations(Lists.newArrayList(relation)); + service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + service.setCapabilities(toInstance.getCapabilities()); + service.setRequirements(fromInstance.getRequirements()); + service.setComponentType(ComponentTypeEnum.SERVICE); + } + + + private static void createInstances() { + toInstance = new ComponentInstance(); + toInstance.setUniqueId(TO_INSTANCE_ID); + + fromInstance = new ComponentInstance(); + fromInstance.setUniqueId(FROM_INSTANCE_ID); + + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); + + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + + + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); + + toInstance.setCapabilities(capabilities); + fromInstance.setRequirements(requirements); + } + + + private static void createRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java new file mode 100644 index 0000000000..a9245d2897 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java @@ -0,0 +1,402 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESC_ERROR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_500; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentsUtilsTest { + + private static User modifier = new User(); + private Component service = new Service(); + private Resource resource = new Resource(); + + @Mock + private AuditingManager manager; + + @Mock + private ResponseFormat responseFormat; + + @Captor + private ArgumentCaptor<AuditBaseEventFactory> factoryCaptor; + + @InjectMocks + private static ComponentsUtils utils; + + @BeforeClass + public static void setUpClass() { + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + @Before + public void setUp() { + ThreadLocalsHolder.setUuid(REQUEST_ID); + utils = new ComponentsUtils(manager); + } + + @Test + public void auditComponentWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + } + + @Test + public void auditComponentWhenAllParamsPassedAndMostFromComponent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + + } + + @Test + public void auditComponentDistStateWithoutArtDataCommentAndDid() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build()); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), + STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, false, false, true); + } + + @Test + public void auditComponentWhenError() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE, + ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(PREV_RESOURCE_STATE).version(PREV_RESOURCE_VERSION).artifactUuid(ARTIFACT_UUID).build()); + verifyResourceAdminEvent(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName(), STATUS_500, DESC_ERROR, + service.getComponentType().getValue(), false, true, false, false, false, false); + } + + @Test + public void auditComponentWhenCompIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE, + RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT); + verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + true, false, false, false, true, false); + } + + @Test + public void auditComponentAdmin() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setName(RESOURCE_NAME); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponentAdmin(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType()); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + resource.setToscaResourceName(TOSCA_NODE_TYPE); + utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .build(), + ARTIFACT_UUID, ARTIFACT_DATA); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(), + false, true, true, true, false, false); + } + + @Test + public void auditResourceWithoutPrevFields() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + utils.auditResource(responseFormat, modifier, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + verifyResourceAdminEvent(AuditingActionEnum.UPDATE_RESOURCE_METADATA.getName(), STATUS_500, DESC_ERROR, resource.getResourceType().name(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenResourceIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditResource(responseFormat, modifier, RESOURCE_NAME, AuditingActionEnum.CHECKOUT_RESOURCE); + verifyResourceAdminEvent(AuditingActionEnum.CHECKOUT_RESOURCE.getName(), STATUS_500, DESC_ERROR, ComponentTypeEnum.RESOURCE.getValue(), + true, false, false, false, false, false); + } + + @Test + public void auditUserAdminEvent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + User userAfter = new User(); + userAfter.setFirstName(USER_FIRST_NAME); + userAfter.setUserId(USER_ID); + userAfter.setLastName(USER_LAST_NAME); + userAfter.setRole(TESTER_USER_ROLE); + userAfter.setEmail(USER_EMAIL); + + utils.auditAdminUserAction(AuditingActionEnum.ADD_USER, modifier, null, userAfter, responseFormat); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + UserAdminEvent event = (UserAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.ADD_USER.getName()); + assertThat(event.getUserBefore()).isNull(); + assertThat(event.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + } + + @Test + public void auditEcompOpEnvEvent() { + utils.auditEnvironmentEngine(AuditingActionEnum.CREATE_ENVIRONMENT, OP_ENV_ID, OP_ENV_TYPE, OP_ENV_ACTION, OP_ENV_NAME, TENANT_CONTEXT); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + EcompOperationalEnvironmentEvent event = (EcompOperationalEnvironmentEvent)factory.getDbEvent(); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + assertThat(event.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(event.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(event.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(event.getOperationalEnvironmentAction()).isEqualTo(OP_ENV_ACTION); + assertThat(event.getTenantContext()).isEqualTo(TENANT_CONTEXT); + } + + @Test + public void auditDistrDownloadEvent(){ + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + utils.auditDistributionDownload(responseFormat, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + DistributionDownloadEvent event = (DistributionDownloadEvent)factory.getDbEvent(); + assertThat(event.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + } + + private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull, + boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided, + boolean isDistStatusProvided) { + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(status); + assertThat(event.getDesc()).isEqualTo(desc); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(action); + assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME); + + if (isComponentNull) { + assertThat(event.getServiceInstanceId()).isNull(); + assertThat(event.getCurrState()).isNull(); + assertThat(event.getCurrVersion()).isNull(); + assertThat(event.getInvariantUUID()).isNull(); + assertThat(event.getResourceType()).isEqualTo(resourceType); + } + else { + assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(event.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(event.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + } + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(event.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } + else { + assertThat(event.getToscaNodeType()).isEmpty(); + } + if (isPrevStateAndVersionSet) { + assertThat(event.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(event.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getPrevState()).isNull(); + assertThat(event.getPrevVersion()).isNull(); + assertThat(event.getPrevArtifactUUID()).isNull(); + } + if (isCurrFieldsProvided) { + assertThat(event.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getCurrArtifactUUID()).isNull(); + } + if (isArtDataProvided) { + assertThat(event.getArtifactData()).isEqualTo(ARTIFACT_DATA); + if (resourceType.equals(ResourceTypeEnum.VFC.name())) { + assertThat(event.getDid()).isNull(); + } + else { + assertThat(event.getDid()).isEqualTo(DIST_ID); + } + } + else { + assertThat(event.getArtifactData()).isNull(); + assertThat(event.getDid()).isNull(); + } + if (isCommentProvided) { + assertThat(event.getComment()).isEqualTo(COMMENT); + } + else { + assertThat(event.getComment()).isEmpty(); + } + if (isDistStatusProvided) { + assertThat(event.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(event.getDprevStatus()).isEqualTo(DPREV_STATUS); + } + else { + assertThat(event.getDcurrStatus()).isNull(); + assertThat(event.getDprevStatus()).isNull(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java index 4f1f929382..7b37b0e96a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -20,7 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; import java.util.ArrayList; import java.util.HashMap; @@ -29,126 +35,120 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; +import static org.junit.Assert.assertTrue; public class CompositionBusinessLogicTest { - CompositionBusinessLogic compBl = new CompositionBusinessLogic(); - - @Test - public void testBuildSpiralPatternPositioningForComponentInstances() { - int instancesNum = 10; - Resource createVF = FactoryUtils.createVF(); - for (int i = 0; i < instancesNum; i++) { - FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); - } - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); - assertTrue(componentInstances.size() == instancesNum); - // Verify Spiral Pattern - ImmutablePair<Double, Double> key; - key = new ImmutablePair<>(0D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-2D, -1D); - assertTrue(componentInstances.containsKey(key)); - } - - @Test - public void testGetCpsConnectedToVFC() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); - - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - assertTrue(cpsConnectedToVFC.size() == 1); - assertTrue(cpsConnectedToVFC.containsKey(vfc)); - Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); - assertTrue(cps.size() == 3); - cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); - - } - - @Test - public void testBuildCirclePatternForCps() { - List<ComponentInstance> allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); - Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); - componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); - compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); - assertTrue(componentInstLocations.size() == 4); - - Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); - // Verify that all cps are located at different positions - assertTrue(cpsLocations.size() == 3); - Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); - // Verify that all cps are at the same distance from center - assertTrue(distances.size() == 1); - - } - - /** - * Adds 4 instances to the vf.<br> - * vfc instance and 3 cps instances.<br> - * the cp instances are connected to the vfc instance.<br> - * - * @param allComponentInstances - * @param createVF - * @return vfc instance - */ - private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { - ComponentInstance vfc = FactoryUtils.createResourceInstance(); - vfc.setOriginType(OriginTypeEnum.VFC); - FactoryUtils.addComponentInstanceToVF(createVF, vfc); - allComponentInstances.add(vfc); - - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - return vfc; - } - - private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { - List<RequirementCapabilityRelDef> allRelations; - if (createVF.getComponentInstancesRelations() != null) { - allRelations = createVF.getComponentInstancesRelations(); - } else { - allRelations = new ArrayList<>(); - createVF.setComponentInstancesRelations(allRelations); - } - ComponentInstance cp1 = FactoryUtils.createResourceInstance(); - cp1.setOriginType(OriginTypeEnum.CP); - addVfcCpRelation(vfc, cp1, allRelations); - FactoryUtils.addComponentInstanceToVF(createVF, cp1); - allComponentInstances.add(cp1); - } - - private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { - RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); - rel.setToNode(vfc.getComponentUid()); - rel.setFromNode(cp.getComponentUid()); - allRelations.add(rel); - } + CompositionBusinessLogic compBl = new CompositionBusinessLogic(); + + @Test + public void testBuildSpiralPatternPositioningForComponentInstances() { + int instancesNum = 10; + Resource createVF = FactoryUtils.createVF(); + for (int i = 0; i < instancesNum; i++) { + FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); + } + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); + assertTrue(componentInstances.size() == instancesNum); + // Verify Spiral Pattern + ImmutablePair<Double, Double> key; + key = new ImmutablePair<>(0D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-2D, -1D); + assertTrue(componentInstances.containsKey(key)); + } + + @Test + public void testGetCpsConnectedToVFC() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); + + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + assertTrue(cpsConnectedToVFC.size() == 1); + assertTrue(cpsConnectedToVFC.containsKey(vfc)); + Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); + assertTrue(cps.size() == 3); + cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); + + } + + @Test + public void testBuildCirclePatternForCps() { + List<ComponentInstance> allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); + Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>(); + componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance); + compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); + assertTrue(componentInstLocations.size() == 4); + + Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); + // Verify that all cps are located at different positions + assertTrue(cpsLocations.size() == 3); + Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); + // Verify that all cps are at the same distance from center + assertTrue(distances.size() == 1); + + } + + /** + * Adds 4 instances to the vf.<br> + * vfc instance and 3 cps instances.<br> + * the cp instances are connected to the vfc instance.<br> + * + * @param allComponentInstances + * @param createVF + * @return vfc instance + */ + private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) { + ComponentInstance vfc = FactoryUtils.createResourceInstance(); + vfc.setOriginType(OriginTypeEnum.VFC); + FactoryUtils.addComponentInstanceToVF(createVF, vfc); + allComponentInstances.add(vfc); + + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + return vfc; + } + + private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) { + List<RequirementCapabilityRelDef> allRelations; + if (createVF.getComponentInstancesRelations() != null) { + allRelations = createVF.getComponentInstancesRelations(); + } else { + allRelations = new ArrayList<>(); + createVF.setComponentInstancesRelations(allRelations); + } + ComponentInstance cp1 = FactoryUtils.createResourceInstance(); + cp1.setOriginType(OriginTypeEnum.CP); + addVfcCpRelation(vfc, cp1, allRelations); + FactoryUtils.addComponentInstanceToVF(createVF, cp1); + allComponentInstances.add(cp1); + } + + private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) { + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + rel.setToNode(vfc.getComponentUid()); + rel.setFromNode(cp.getComponentUid()); + allRelations.add(rel); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java index 50ad990560..d91fa7995b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -20,18 +20,18 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Arrays; - import org.junit.Assert; import org.junit.Test; +import java.util.Arrays; + public class CsarValidationUtilsTest { - private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; - private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; + private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; + private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; - @Test - public void testIsCsarPayloadName() { - Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); - Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); - } + @Test + public void testIsCsarPayloadName() { + Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); + Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java new file mode 100644 index 0000000000..46ee852aa0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 12/7/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class ElementBLTest { + + private static final String CATAGORY_NAME = "categoryName"; + private static final String CATEGORY_UNIQUE_ID = "catUniqueId"; + private static final String SERVICE_NOT_DELETED_ID = "notDeletedId"; + private static final String DELETED_SERVICE_ID = "deletedId"; + private List<CategoryData> categories = new ArrayList<>(); + private List<ImmutablePair<ServiceMetadataData, GraphEdge>> services = new ArrayList<>(); + private List<ImmutablePair<ResourceMetadataData, GraphEdge>> resources = new ArrayList<>(); + private Service notDeletedService = new Service(); + private Resource notDeletedResource = new Resource(); + + @Mock + private TitanGenericDao titanGenericDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private TitanDao titanDao; + + @InjectMocks + private ElementBusinessLogic elementBusinessLogic; + + @Before + public void setup() { + + initCategoriesList(); + initServicesList(); + initResourceslist(); + + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void initCategoriesList() { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setUniqueId(CATEGORY_UNIQUE_ID); + categories.add(categoryData); + } + + private void initServicesList() { + ServiceMetadataData serviceNotDeleted = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition1 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition1.setIsDeleted(false); + componentMetadataDataDefinition1.setHighestVersion(true); + componentMetadataDataDefinition1.setUniqueId(SERVICE_NOT_DELETED_ID); + serviceNotDeleted.setMetadataDataDefinition(componentMetadataDataDefinition1); + services.add(new ImmutablePair<>(serviceNotDeleted, null)); + + ServiceMetadataData deletedService = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition2 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition2.setIsDeleted(true); + componentMetadataDataDefinition2.setHighestVersion(true); + componentMetadataDataDefinition2.setUniqueId(DELETED_SERVICE_ID); + deletedService.setMetadataDataDefinition(componentMetadataDataDefinition2); + services.add(new ImmutablePair<>(deletedService, null)); + } + + private void initResourceslist() { + ResourceMetadataData notDeletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition3 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition3.setIsDeleted(false); + componentMetadataDataDefinition3.setHighestVersion(true); + componentMetadataDataDefinition3.setUniqueId(SERVICE_NOT_DELETED_ID); + notDeletedResource.setMetadataDataDefinition(componentMetadataDataDefinition3); + resources.add(new ImmutablePair<>(notDeletedResource, null)); + + ResourceMetadataData deletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition4 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition4.setIsDeleted(true); + componentMetadataDataDefinition4.setHighestVersion(true); + componentMetadataDataDefinition4.setUniqueId(DELETED_SERVICE_ID); + deletedResource.setMetadataDataDefinition(componentMetadataDataDefinition4); + resources.add(new ImmutablePair<>(deletedResource, null)); + } + + @Test + public void testFetchElementsByCategoryName_filterDeleted() { + ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class); + + when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) + .thenReturn(Either.left(categories)); + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class)) + .thenReturn(Either.left(services)); + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedService)); + + Either<List<Object>, StorageOperationStatus> elementsByCategoryEither = + elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), + NodeTypeEnum.Service, false, ServiceMetadataData.class, null); + + List<Object> elementsByCategory = elementsByCategoryEither.left().value(); + assertThat(elementsByCategory.get(0)).isSameAs(notDeletedService); + assertThat(elementsByCategory.size()).isEqualTo(1); + verifyCriteriaProperties(criteriaCapture); + } + + private void verifyCriteriaProperties(ArgumentCaptor<Map> propsCapture) { + Map<String, Object> props = propsCapture.getValue(); + assertThat(props.size()).isEqualTo(1); + assertThat(props.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty())).isEqualTo(ValidationUtils.normalizeCategoryName4Uniqueness(CATAGORY_NAME)); + } + + @Test + public void testFetchResourcesBySubcategoryUid_filterDeleted() { + + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)) + .thenReturn(Either.left(resources)); + + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedResource)); + + Either<List<Object>, StorageOperationStatus> resourcesBySubCategoryUidEither = elementBusinessLogic.fetchByCategoryOrSubCategoryUid(CATEGORY_UNIQUE_ID, NodeTypeEnum.ResourceSubcategory, + GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, false, ResourceMetadataData.class, null); + List<Object> resourcesBySubCategoryUid = resourcesBySubCategoryUidEither.left().value(); + assertThat(resourcesBySubCategoryUid.size()).isEqualTo(1); + assertThat(resourcesBySubCategoryUid.get(0)).isSameAs(notDeletedResource); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 5edf448cc2..b65e77c57f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -20,21 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; @@ -46,462 +32,475 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ImportUtilsTest { - @Test - public void testStringTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 4); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof String); - String value = (String) element; - assertTrue(value.equals("stringVal" + count)); - count++; - } - } - - @Test - public void testBooleanTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Boolean); - Boolean value = (Boolean) element; - if (count == 1 || count == 3) { - assertFalse(value); - } else if (count == 2) { - assertTrue(value); - } - - count++; - } - } - - @Test - public void testListTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof List); - - if (count == 1) { - verifyListElement1(element); - } else if (count == 2) { - verifyListElement2(element); - } - - else if (count == 3) { - verifyListElement3(element); - } - count++; - } - } - - @Test - public void testAllTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 5); - int count = 1; - for (Object element : list) { - if (count == 1) { - assertTrue(element instanceof String); - assertTrue(element.equals("tosca.nodes.Root")); - } else if (count == 2) { - assertTrue(element instanceof Map); - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); - Entry<String, Object> elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("mapTestTag")); - assertTrue(elementEntry.getValue().equals("string")); - - elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("required")); - assertTrue(elementEntry.getValue() instanceof Boolean); - assertTrue((Boolean) elementEntry.getValue()); - } - - else if (count == 3) { - assertTrue(element instanceof String); - assertTrue(element.equals("1 MB")); - } - - else if (count == 4) { - assertTrue(element instanceof List); - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - assertTrue(listElement.get(0) instanceof Map); - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("greater_or_equal")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal3")); - } else if (count == 5) { - assertTrue(element instanceof Boolean); - assertFalse((Boolean) element); - } - count++; - } - } - - @Test - public void testMapTypeFindToscaElements() throws IOException { - Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List<Object> list = toscaElements.left().value(); - assertTrue(list.size() == 2); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Map); - - if (count == 1) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("stringTestTag")); - assertTrue(inerElementEntry.getValue().equals("stringVal1")); - - inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("listTestTag")); - assertTrue(inerElementEntry.getValue() instanceof List); - List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); - - assertTrue(innerValue.size() == 3); - - } else if (count == 2) { - Map<String, Object> mapElement = (Map<String, Object>) element; - assertTrue(mapElement.size() == 2); - Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); - Entry<String, Object> inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("type")); - assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); - inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("allTestTag")); - assertTrue(inerElementEntry.getValue() instanceof Boolean); - } - - count++; - } - } - - @Test - public void testCreateFullHeatParameterModuleWithString() { - - testCreateFullHeatParameterModule("string", "default value"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithNumber() { - - testCreateFullHeatParameterModule("number", "777"); - testCreateFullHeatParameterModule("number", "777.23"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithBoolean() { - - testCreateFullHeatParameterModule("boolean", "true"); - testCreateFullHeatParameterModule("boolean", "on"); - testCreateFullHeatParameterModule("boolean", "n"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithList() { - - testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); - - } - - // @Test - // public void testCreateFullHeatParameterModuleWithInvalidType(){ - // - // String name = "fullParameter"; - // String description = "description_text"; - // - // Map<String, Object> parametersMap = new HashMap<String, Object>(); - // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", - // name, description); - // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), - // firstParam); - // - // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = - // ImportUtils.getHeatParameters(parametersMap); - // assertTrue(heatParameters.isRight()); - // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, - // heatParameters.right().value()); - // - // } - - @Test - public void testCreateFullHeatParameterModuleWithMissingType() { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isRight()); - assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); + @Test + public void testStringTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 4); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof String); + String value = (String) element; + assertTrue(value.equals("stringVal" + count)); + count++; + } + } + + @Test + public void testBooleanTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Boolean); + Boolean value = (Boolean) element; + if (count == 1 || count == 3) { + assertFalse(value); + } else if (count == 2) { + assertTrue(value); + } + + count++; + } + } + + @Test + public void testListTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof List); + + if (count == 1) { + verifyListElement1(element); + } else if (count == 2) { + verifyListElement2(element); + } + + else if (count == 3) { + verifyListElement3(element); + } + count++; + } + } + + @Test + public void testAllTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 5); + int count = 1; + for (Object element : list) { + if (count == 1) { + assertTrue(element instanceof String); + assertTrue(element.equals("tosca.nodes.Root")); + } else if (count == 2) { + assertTrue(element instanceof Map); + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator(); + Entry<String, Object> elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("mapTestTag")); + assertTrue(elementEntry.getValue().equals("string")); + + elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("required")); + assertTrue(elementEntry.getValue() instanceof Boolean); + assertTrue((Boolean) elementEntry.getValue()); + } + + else if (count == 3) { + assertTrue(element instanceof String); + assertTrue(element.equals("1 MB")); + } + + else if (count == 4) { + assertTrue(element instanceof List); + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + assertTrue(listElement.get(0) instanceof Map); + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("greater_or_equal")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal3")); + } else if (count == 5) { + assertTrue(element instanceof Boolean); + assertFalse((Boolean) element); + } + count++; + } + } + + @Test + public void testMapTypeFindToscaElements() throws IOException { + Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List<Object> list = toscaElements.left().value(); + assertTrue(list.size() == 2); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Map); + + if (count == 1) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("stringTestTag")); + assertTrue(inerElementEntry.getValue().equals("stringVal1")); + + inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("listTestTag")); + assertTrue(inerElementEntry.getValue() instanceof List); + List<Object> innerValue = (List<Object>) inerElementEntry.getValue(); + + assertTrue(innerValue.size() == 3); + + } else if (count == 2) { + Map<String, Object> mapElement = (Map<String, Object>) element; + assertTrue(mapElement.size() == 2); + Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator(); + Entry<String, Object> inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("type")); + assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); + inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("allTestTag")); + assertTrue(inerElementEntry.getValue() instanceof Boolean); + } + + count++; + } + } + + @Test + public void testCreateFullHeatParameterModuleWithString() { + + testCreateFullHeatParameterModule("string", "default value"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithNumber() { + + testCreateFullHeatParameterModule("number", "777"); + testCreateFullHeatParameterModule("number", "777.23"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithBoolean() { + + testCreateFullHeatParameterModule("boolean", "true"); + testCreateFullHeatParameterModule("boolean", "on"); + testCreateFullHeatParameterModule("boolean", "n"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithList() { + + testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); + + } + + // @Test + // public void testCreateFullHeatParameterModuleWithInvalidType(){ + // + // String name = "fullParameter"; + // String description = "description_text"; + // + // Map<String, Object> parametersMap = new HashMap<String, Object>(); + // Map<String, Object> firstParam = createParameterMap("aaa", "aaa", + // name, description); + // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), + // firstParam); + // + // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters = + // ImportUtils.getHeatParameters(parametersMap); + // assertTrue(heatParameters.isRight()); + // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, + // heatParameters.right().value()); + // + // } + + @Test + public void testCreateFullHeatParameterModuleWithMissingType() { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isRight()); + assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); - } + } - @Test - public void testCreateFullHeatParameterModuleWithMissingFields() { + @Test + public void testCreateFullHeatParameterModuleWithMissingFields() { - String name = "fullParameter"; + String name = "fullParameter"; - Map<String, Object> parametersMap = new HashMap<String, Object>(); - String type = "number"; - String defValue = "defvalue"; - // default value cannot be empty in heat in case tag exists - Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + Map<String, Object> parametersMap = new HashMap<String, Object>(); + String type = "number"; + String defValue = "defvalue"; + // default value cannot be empty in heat in case tag exists + Map<String, Object> firstParam = createParameterMap(type, defValue, name, null); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - assertParameter(parameterDefinition, name, type, null, defValue); + assertParameter(parameterDefinition, name, type, null, defValue); - } + } - @Test - public void testGetAttributesFromYml() throws IOException { + @Test + public void testGetAttributesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); - assertTrue(actualAttributes.isLeft()); - Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); - compareAttributes(expectedAttributes, actualAttributes.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + assertTrue(actualAttributes.isLeft()); + Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); + compareAttributes(expectedAttributes, actualAttributes.left().value()); - } + } - @Test - public void testGetPropertiesFromYml() throws IOException { + @Test + public void testGetPropertiesFromYml() throws IOException { - Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); - assertTrue(actualProperties.isLeft()); - Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); - compareProperties(expectedProperties, actualProperties.left().value()); + Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml"); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); + assertTrue(actualProperties.isLeft()); + Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); + compareProperties(expectedProperties, actualProperties.left().value()); - } + } - private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedAttribute; - PropertyDefinition actualAttribute, expectedAttributeModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { + Map<String, Object> singleExpectedAttribute; + PropertyDefinition actualAttribute, expectedAttributeModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) { - singleExpectedAttribute = expectedAttribute.getValue(); - assertNotNull(singleExpectedAttribute); - actualAttribute = actual.get(expectedAttribute.getKey()); - assertNotNull(actualAttribute); - actualAttribute.setName(expectedAttribute.getKey().toString()); - expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); - expectedAttributeModel.setName(expectedAttribute.getKey().toString()); + singleExpectedAttribute = expectedAttribute.getValue(); + assertNotNull(singleExpectedAttribute); + actualAttribute = actual.get(expectedAttribute.getKey()); + assertNotNull(actualAttribute); + actualAttribute.setName(expectedAttribute.getKey().toString()); + expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); + expectedAttributeModel.setName(expectedAttribute.getKey().toString()); - assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); - assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); - assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); - assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); - assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); + assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); + assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); + assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); + assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); - compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); + compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); - } + } - } + } - private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { + private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) { - Map<String, Object> singleExpectedProperty; - PropertyDefinition actualProperty, expectedPropertyModel; - // attributes of resource - for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { + Map<String, Object> singleExpectedProperty; + PropertyDefinition actualProperty, expectedPropertyModel; + // attributes of resource + for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) { - singleExpectedProperty = expectedProperty.getValue(); - assertNotNull(singleExpectedProperty); - actualProperty = actual.get(expectedProperty.getKey()); - assertNotNull(actualProperty); - actualProperty.setName(expectedProperty.getKey().toString()); - expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); - expectedPropertyModel.setName(expectedProperty.getKey().toString()); + singleExpectedProperty = expectedProperty.getValue(); + assertNotNull(singleExpectedProperty); + actualProperty = actual.get(expectedProperty.getKey()); + assertNotNull(actualProperty); + actualProperty.setName(expectedProperty.getKey().toString()); + expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); + expectedPropertyModel.setName(expectedProperty.getKey().toString()); - assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); - assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); - assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); - assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); - assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); + assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); + assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); + assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); + assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); + assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); - compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); - } + } - } + } - private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { + private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { - if (expected == null && actual == null) { - return; - } - PropertyDataDefinition actualPropertySchema = actual.getProperty(); - PropertyDataDefinition expectedPropertySchema = expected.getProperty(); - assertNotNull(actualPropertySchema); - assertNotNull(expectedPropertySchema); - assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); - assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); - - } + if (expected == null && actual == null) { + return; + } + PropertyDataDefinition actualPropertySchema = actual.getProperty(); + PropertyDataDefinition expectedPropertySchema = expected.getProperty(); + assertNotNull(actualPropertySchema); + assertNotNull(expectedPropertySchema); + assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); + assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); + + } - private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { - - Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); - assertTrue(toscaExpectedElements.isLeft()); - - return toscaExpectedElements.left().value(); - - } - - private void testCreateFullHeatParameterModule(String type, Object defaultVal) { - - String name = "fullParameter"; - String description = "description_text"; - - Map<String, Object> parametersMap = new HashMap<String, Object>(); - Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - - assertParameter(parameterDefinition, name, type, description, defaultVal); - - } - - private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { - Map<String, Object> firstParam = new HashMap<String, Object>(); - Map<String, Object> valuesMap = new HashMap<String, Object>(); - - valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); - valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); - valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); - - firstParam.put(name, valuesMap); - return firstParam; - } - - private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { - assertEquals(name, parameterDefinition.getName()); - assertEquals(description, parameterDefinition.getDescription()); - assertEquals(type, parameterDefinition.getType()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); - } - - private void verifyListElement3(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("type")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - private void verifyListElement2(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 2); - - Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map<String, Object>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue() instanceof List); - } - - private void verifyListElement1(Object element) { - List<Object> listElement = (List<Object>) element; - assertTrue(listElement.size() == 3); - - Map<String, String> innerElement = (Map<String, String>) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map<String, String>) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("2 MB")); - - innerElement = (Map<String, String>) listElement.get(2); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - public static String loadFileNameToJsonString(String fileName) throws IOException { - String sourceDir = "src/test/resources/normativeTypes"; - java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); - byte[] fileContent = Files.readAllBytes(filePath); - String content = new String(fileContent); - return content; - } - - private static Object loadJsonFromFile(String fileName) throws IOException { - String content = loadFileNameToJsonString(fileName); - Object load = new Yaml().load(content); - return load; - } + private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) { + + Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); + assertTrue(toscaExpectedElements.isLeft()); + + return toscaExpectedElements.left().value(); + + } + + private void testCreateFullHeatParameterModule(String type, Object defaultVal) { + + String name = "fullParameter"; + String description = "description_text"; + + Map<String, Object> parametersMap = new HashMap<String, Object>(); + Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List<HeatParameterDefinition> parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, description, defaultVal); + + } + + private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) { + Map<String, Object> firstParam = new HashMap<String, Object>(); + Map<String, Object> valuesMap = new HashMap<String, Object>(); + + valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); + valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); + valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); + + firstParam.put(name, valuesMap); + return firstParam; + } + + private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { + assertEquals(name, parameterDefinition.getName()); + assertEquals(description, parameterDefinition.getDescription()); + assertEquals(type, parameterDefinition.getType()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); + } + + private void verifyListElement3(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("type")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + private void verifyListElement2(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 2); + + Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map<String, Object>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue() instanceof List); + } + + private void verifyListElement1(Object element) { + List<Object> listElement = (List<Object>) element; + assertTrue(listElement.size() == 3); + + Map<String, String> innerElement = (Map<String, String>) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry<String, String> innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map<String, String>) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("2 MB")); + + innerElement = (Map<String, String>) listElement.get(2); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + public static String loadFileNameToJsonString(String fileName) throws IOException { + String sourceDir = "src/test/resources/normativeTypes"; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static Object loadJsonFromFile(String fileName) throws IOException { + String content = loadFileNameToJsonString(fileName); + Object load = new Yaml().load(content); + return load; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index ac4d37ef76..068f04aae2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; @@ -46,7 +39,17 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class InputsBusinessLogicTest { @@ -63,6 +66,9 @@ public class InputsBusinessLogicTest { @Mock private ToscaOperationFacade toscaOperationFacadeMock; + @Mock + private UserValidations userValidations; + @InjectMocks private InputsBusinessLogic testInstance; @@ -83,13 +89,13 @@ public class InputsBusinessLogicTest { instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput)); instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput())); service.setComponentInstancesInputs(instanceInputMap); - - Mockito.when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); } @Test public void getComponentInstanceInputs_ComponentInstanceNotExist() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, "nonExisting"); assertTrue(componentInstanceInputs.isRight()); Mockito.verify(componentsUtilsMock).getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); @@ -115,13 +121,13 @@ public class InputsBusinessLogicTest { @Test public void getComponentInstanceInputs() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals("inputId", componentInstanceInputs.left().value().get(0).getInputId()); } private void getComponents_emptyInputs(Service service) { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals(Collections.emptyList(), componentInstanceInputs.left().value()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java index 8109e36be1..e726f608f5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -42,51 +34,54 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; -public class InterfaceLifecycleTypeImportManagerTest { +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - @InjectMocks - private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); +public class InterfaceLifecycleTypeImportManagerTest { - static Logger log = Mockito.spy(Logger.class); + @InjectMocks + private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { - public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() throws IOException { + when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() { + public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void importLiecycleTest() throws IOException { - String ymlContent = getYmlContent(); - Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void importLiecycleTest() throws IOException { + String ymlContent = getYmlContent(); + Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - } + } - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java new file mode 100644 index 0000000000..9aca92010e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java @@ -0,0 +1,493 @@ +package org.openecomp.sdc.be.components.impl; + + +import fj.data.Either; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyBusinessLogicTest { + + @InjectMocks + private PolicyBusinessLogic businessLogic; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private UserValidations userValidations; + @Mock + private TitanDao titanDao; + @Mock + private ApplicationDataTypeCache dataTypeCache; + @Mock + private PropertyOperation propertyOperation; + + private final static String COMPONENT_ID = "componentId"; + private final static String COMPONENT_NAME = "componentName"; + private final static String POLICY_TYPE_NAME = "policyTypeName"; + private final static String POLICY_ID = "policyId"; + private final static String INVALID_POLICY_ID = "invalidPolicyId"; + private final static String POLICY_NAME = "policyName"; + private final static String OTHER_POLICY_NAME = "otherPolicyName"; + private final static String USER_ID = "jh0003"; + private final static String UNIQUE_ID_EXSISTS = "uniqueIdExists"; + private final static String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists"; + private final static String FAKE_TYPE = "fakeType"; + private final static String COMPONENT_INSTANCE_TYPE = "component_Instances"; + private final static String GROUP_TYPE = "GROUPS"; + + + + + private final String CREATE_POLICY = "create Policy"; + + private final static User user = buildUser(); + private final static PolicyDefinition policy = buildPolicy(POLICY_NAME); + private final static PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME); + private final static Resource resource = buildResource(); + private final static PolicyTypeDefinition policyType = buildPolicyType(); + + private static Either<User, ResponseFormat> userSuccessEither; + private static Either<Component, StorageOperationStatus> componentSuccessEither; + private static Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeSuccessEither; + private static Either<PolicyDefinition, StorageOperationStatus> policySuccessEither; + private static ResponseFormat notFoundResponse; + private static ResponseFormat invalidContentResponse; + private static ResponseFormat nameExistsResponse; + + @BeforeClass + public static void setup() { + String appConfigDir = "src/test/resources/config/catalog-be"; + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + createResponses(); + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + } + + private static void createResponses() { + userSuccessEither = Either.left(user); + componentSuccessEither = Either.left(resource); + getPolicyTypeSuccessEither = Either.left(policyType); + policySuccessEither = Either.left(policy); + notFoundResponse = new ResponseFormat(); + notFoundResponse.setStatus(404); + invalidContentResponse = new ResponseFormat(); + invalidContentResponse.setStatus(400); + nameExistsResponse = new ResponseFormat(); + nameExistsResponse.setStatus(409); + } + + @Test + public void createPolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void createPolicyUserFailureTest(){ + Either<User, ResponseFormat> userNotFoundResponse = Either.right(new ResponseFormat(404)); + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userNotFoundResponse); + stubRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + private void assertNotFound(Either<PolicyDefinition, ResponseFormat> response) { + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void createPolicyComponentFailureTest(){ + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither); + Either<Component, StorageOperationStatus> componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND); + when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(ComponentTypeEnum.RESOURCE))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyPolicyTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeFailed); + when(componentsUtils.convertFromStorageResponse(eq(getPolicyTypeFailed.right().value()))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyComponentTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + Either<PolicyDefinition, StorageOperationStatus> addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes); + when(componentsUtils.convertFromStorageResponse(eq(addPolicyRes.right().value()))).thenReturn(ActionStatus.INVALID_CONTENT); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_CONTENT))).thenReturn(invalidContentResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(400)); + } + + @Test + public void updatePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyNameFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NAME_ALREADY_EXIST), eq(POLICY_NAME))).thenReturn(nameExistsResponse); + stubUnlockAndRollback(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(409)); + } + + @Test + public void getPolicySuccessTest(){ + stubValidationSuccess(CREATE_POLICY); + stubCommit(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID); + assertTrue(response.isLeft()); + } + + @Test + public void getPolicyFailureTest(){ + stubValidationSuccess(CREATE_POLICY); + stubRollback(); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), eq(INVALID_POLICY_ID), eq(COMPONENT_ID))).thenReturn(notFoundResponse); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void deletePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + when(toscaOperationFacade.removePolicyFromComponent(eq(COMPONENT_ID),eq(POLICY_ID))).thenReturn(StorageOperationStatus.OK); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void deletePolicyFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER(); + Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true); + assertNotFound(response); + } + + private void stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), anyString(), anyString())).thenReturn(new ResponseFormat(404)); + } + + @Test + public void updatePolicyPropertiesSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + String prop1 = "Name"; + String prop2 = "Type"; + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1)); + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2)); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + PropertyDataDefinition[] properties = getProperties(prop1, prop2); + policy.setProperties(Arrays.asList(properties)); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties , USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyTargetsSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubGetToscaElementSuccess(); + stubGetTargetType(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID); + + Assert.assertTrue(result.isLeft()); + PolicyDefinition policyResult = result.left().value(); + Map<PolicyTargetType, List<String>> targets = getTargets(); + assertThat(policyResult.getTargets().values()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES)); + + } + + private void stubGetTargetType() { + } + + @Test + public void updatePolicyTargetsTargetIDFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeId(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertEquals(responseResult.getStatus().longValue(), 400L); + + } + + private void stubComponentUtilsGetResponseTargetNotFound() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST), (anyString()))).thenReturn(new ResponseFormat(400)); + } + + @Test + public void updatePolicyTargetsTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeType(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertTrue(responseResult.getStatus().equals(400)); + + } + + private void stubUpdatePolicyOfComponentSuccess() { + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy))).thenReturn(policySuccessEither); + } + + + @Test + public void updatePolicyPropertiesFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.PROPERTY_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + policy.setProperties(null); + Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getProperties("Name", "Type") , USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + private PropertyDataDefinition[] getProperties(String prop1, String prop2) { + PropertyDataDefinition property1 = new PropertyDataDefinition(); + property1.setName(prop1); + property1.setValue(prop1); + PropertyDataDefinition property2 = new PropertyDataDefinition(); + property2.setName(prop2); + property2.setValue(prop2); + PropertyDataDefinition[] properties = {property1, property2}; + return properties; + } + + + private void stubUnlockAndRollback() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubRollback(); + } + + private void stubCommit() { + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void stubRollback() { + when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + } + + private void stubUnlockAndCommit() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubCommit(); + } + + private void stubValidateAndLockSuccess(String methodName) { + stubValidationSuccess(methodName); + when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + } + + private void stubValidationSuccess(String methodName) { + when(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(userSuccessEither); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither); + } + + private void stubGetToscaFullElementSuccess() { + when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(buildElementEither()); + } + + private void stubGetToscaElementSuccess() { + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID))).thenReturn(componentSuccessEither); + } + + private Either<Component, StorageOperationStatus> buildElementEither() { + ResourceBuilder builder = new ResourceBuilder(); + GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build(); + ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder(); + ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build(); + return Either.left(builder.addGroups(groupDefinition).addComponentInstance(componentInstance).build()); + } + + private Map<PolicyTargetType, List<String>> getTargets() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + + + private static PolicyTypeDefinition buildPolicyType() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + policyType.setType(POLICY_TYPE_NAME); + return policyType; + } + + private static PolicyDefinition buildPolicy(String policyName) { + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + policy.setPolicyTypeName(POLICY_TYPE_NAME); + policy.setComponentName(COMPONENT_NAME); + policy.setName(policyName); + return policy; + } + + private static Resource buildResource() { + Resource resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setName(COMPONENT_NAME); + resource.setCreatorUserId(USER_ID); + resource.setLastUpdaterUserId(USER_ID); + resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setResourceType(ResourceTypeEnum.VF); + resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); + Map<String, PolicyDefinition> policies = new HashMap<>(); + policies.put(POLICY_ID, policy); + resource.setPolicies(policies); + return resource; + } + + private static User buildUser() { + User user = new User(); + user.setUserId(USER_ID); + return user; + } + private List<PolicyTargetDTO> getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType("componentInstances"); + + return Arrays.asList(target1, target2); + } + + private List<PolicyTargetDTO> getFakeIDTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target1.setType(GROUP_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target2.setType(COMPONENT_INSTANCE_TYPE); + + return Arrays.asList(target1, target2); + } + private List<PolicyTargetDTO> getFakeTypeTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType(FAKE_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType(FAKE_TYPE); + + return Arrays.asList(target1, target2); + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeType() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + private Map<PolicyTargetType, List<String>> getTargetListFakeId() { + Map<PolicyTargetType, List<String>> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + return targets; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java new file mode 100644 index 0000000000..ad3e6e8974 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java @@ -0,0 +1,148 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.core.Response; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyPropertiesBusinessLogicTest { + + private static final String POLICY_ID = "policy1"; + private static final String RESOURCE_ID = "resourceId"; + private static final String USER_ID = "userId"; + public static final String NO_PROPS_POLICY = "policy2"; + @InjectMocks + private PolicyBusinessLogic testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private TitanDao titanDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private ComponentsUtils componentsUtils; + + private ComponentParametersView componentFilter; + private Resource resource; + private PropertyDefinition prop1, prop2; + + @Before + public void setUp() throws Exception { + componentFilter = new ComponentParametersView(true); + componentFilter.setIgnorePolicies(false); + componentFilter.setIgnoreUsers(false); + + prop1 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + prop2 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + + PolicyDefinition policy1 = PolicyDefinitionBuilder.create() + .setUniqueId(POLICY_ID) + .setProperties(prop1, prop2) + .build(); + + PolicyDefinition policy2 = PolicyDefinitionBuilder.create() + .setUniqueId(NO_PROPS_POLICY) + .build(); + resource = new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) + .setLastUpdaterUserId(USER_ID) + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + @After + public void tearDown() { + verify(titanDao).commit(); + } + + @Test + public void getPolicyProperties_userIdIsNull() { + String userId = null; + ResponseFormat forbiddenResponse = new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()); + when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenReturn(Either.right(forbiddenResponse)); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null); + assertThat(policyProperties.right().value()).isSameAs(forbiddenResponse); + } + + @Test + public void getPolicyProperties_componentNotFound() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.right().value()).isSameAs(notFoundResponse); + } + + @Test + public void getPolicyProperties_policyNotExist() { + doPolicyValidations(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, "nonExistingPolicy", RESOURCE_ID)).thenReturn(notFoundResponse); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, "nonExistingPolicy", USER_ID); + assertThat(policyProperties.right().value()).isEqualTo(notFoundResponse); + } + + @Test + public void getPolicyProperties_noPropertiesOnPolicy() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, NO_PROPS_POLICY, USER_ID); + assertThat(policyProperties.left().value()).isNull(); + } + + @Test + public void getPolicyProperties() { + doPolicyValidations(); + Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.left().value()) + .usingElementComparatorOnFields("uniqueId") + .containsExactly(prop1, prop2); + } + + private void doPolicyValidations() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.left(resource)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java new file mode 100644 index 0000000000..7dc12d96e6 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.impl; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTypeBusinessLogicTest { + + private static final String USER_ID = "userId"; + private static final Set<String> EXCLUDED_POLICY_TYPES = newHashSet("type1", "type2"); + private static final String COMPONENT_TYPE = "VF"; + + @InjectMocks + private PolicyTypeBusinessLogic testInstance; + @Mock + private TitanDao titanDao; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private UserValidations userValidations; + + @Before + public void setUp() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.left(new User())); + when(componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(any(StorageOperationStatus.class))).thenCallRealMethod(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES)); + } + + @BeforeClass + public static void beforeClass() { + new DummyConfigurationManager(); + } + + @Test + public void getAllPolicyTypes_userNotExist() { + ResponseFormat userNotExistResponse = new ResponseFormat(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.right(userNotExistResponse)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(userNotExistResponse); + } + + @Test + public void getAllPolicyTypes_whenExcludePolicyTypesSetIsNull_passNullExcludedTypesSet() { + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenCallRealMethod(); + when(policyTypeOperation.getAllPolicyTypes(null)).thenReturn(Either.left(emptyList())); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + } + + @Test + public void getAllPolicyTypes() { + List<PolicyTypeDefinition> policyTypes = Arrays.asList(new PolicyTypeBuilder().setUniqueId("id1").build(), + new PolicyTypeBuilder().setUniqueId("id2").build(), + new PolicyTypeBuilder().setUniqueId("id3").build()); + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.left(policyTypes)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isSameAs(policyTypes); + } + + @Test + public void getAllPolicyTypes_noPolicyTypes() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + verify(titanDao).commit(); + } + + @Test + public void getAllPolicyTypes_err() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + ResponseFormat errResponse = new ResponseFormat(); + when(componentsUtils.getResponseFormat(StorageOperationStatus.GENERAL_ERROR)).thenReturn(errResponse); + Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(errResponse); + verify(titanDao).commit(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index f7724aaeff..8054baf15f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -20,22 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; @@ -44,13 +29,13 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -98,1635 +83,1738 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class ResourceBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName()); - public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; - public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; - public static final String RESOURCE_SUBCATEGORY = "Router"; + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class); + public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; + public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; + public static final String RESOURCE_SUBCATEGORY = "Router"; - public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; - public static final String UPDATED_SUBCATEGORY = "Gateway"; + public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; + public static final String UPDATED_SUBCATEGORY = "Gateway"; - public static final String RESOURCE_NAME = "My-Resource_Name with space"; + public static final String RESOURCE_NAME = "My-Resource_Name with space"; private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF"; + private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR"; private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC"; private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF"; - - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - IElementOperation mockElementDao; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); - NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); - TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); - final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); - final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); - final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); - final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - ResponseFormatManager responseManager = null; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - User user = null; - Resource resourceResponse = null; - Resource genericVF = null; - Resource genericVFC = null; - Resource genericPNF = null; - ComponentsUtils componentsUtils = new ComponentsUtils(); - ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); - CsarOperation csarOperation = Mockito.mock(CsarOperation.class); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - - - public ResourceBusinessLogicTest() { - - } - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - Mockito.reset(propertyOperation); - - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - - Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); - Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); - - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); - - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - - // createResource - resourceResponse = createResourceObject(true); - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); - Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); - when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - - // BL object - artifactManager.nodeTemplateOperation = nodeTemplateOperation; - bl = new ResourceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setCapabilityTypeOperation(capabilityTypeOperation); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setLifecycleManager(lifecycleBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setArtifactsManager(artifactManager); - bl.setPropertyOperation(propertyOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setApplicationDataTypeCache(applicationDataTypeCache); - bl.setCsarOperation(csarOperation); - bl.setCacheManagerOperation(cacheManager); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); - toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); - bl.setToscaOperationFacade(toscaOperationFacade); - Resource resourceCsar = createResourceObjectCsar(true); - setCanWorkOnResource(resourceCsar); - Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); - when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); - responseManager = ResponseFormatManager.getInstance(); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource createResourceObjectCsar(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<String>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setResourceVendorModelNumber(""); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - resource.setCsarUUID("valid_vf.csar"); - resource.setCsarVersion("1"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource setCanWorkOnResource(Resource resource) { - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setLastUpdaterUserId(user.getUserId()); - return resource; - } - - @Test - public void testHappyScenario() { - Resource resource = createResourceObject(false); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEquals(createResourceObject(true), createResponse.left().value()); - } - - @Test - public void testUpdateHappyScenario() { - Resource resource = createResourceObjectCsar(true); - setCanWorkOnResource(resource); - - Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); - when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); - if (updateResponse.isRight()) { - assertEquals(new Integer(200), updateResponse.right().value().getStatus()); - } - assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); - } - - /* CREATE validations - start ***********************/ - // Resource name - start - - @Test - public void testFailedResourceValidations() { - testResourceNameExist(); - testResourceNameEmpty(); - // testResourceNameExceedsLimit(); - testResourceNameWrongFormat(); - testResourceDescExceedsLimitCreate(); - testResourceDescNotEnglish(); - testResourceDescriptionEmpty(); - testResourceDescriptionMissing(); - testResourceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - testResourceTagNotExist(); - testResourceTagEmpty(); - testTagsExceedsLimitCreate(); - testTagsNoServiceName(); - testInvalidTag(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testResourceContactIdEmpty(); - testResourceContactIdMissing(); - testVendorNameExceedsLimit(); - testVendorNameWrongFormatCreate(); - testVendorReleaseWrongFormat(); - testVendorReleaseExceedsLimitCreate(); - testResourceVendorModelNumberExceedsLimit(); - testResourceVendorNameMissing(); - testResourceVendorReleaseMissing(); - testResourceCategoryExist(); - testResourceBadCategoryCreate(); - testHappyScenarioCostLicenseType(); - testCostWrongFormatCreate(); - testLicenseTypeWrongFormatCreate(); - testResourceTemplateNotExist(); - testResourceTemplateEmpty(); - testResourceTemplateInvalid(); - } - - private void testResourceNameExist() { - String resourceName = "alreadyExists"; - Resource resourceExist = createResourceObject(false); - resourceExist.setName(resourceName); - resourceExist.getTags().add(resourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - private void testResourceNameEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceNameExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - resourceExccedsNameLimit.setName(tooLongResourceName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testResourceNameWrongFormat() { - Resource resource = createResourceObject(false); - // contains : - String nameWrongFormat = "ljg?fd"; - resource.setName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Resource name - end - // Resource description - start - private void testResourceDescExceedsLimitCreate() { - Resource resourceExccedsDescLimit = createResourceObject(false); - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - resourceExccedsDescLimit.setDescription(tooLongResourceDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testResourceDescNotEnglish() { - Resource notEnglish = createResourceObject(false); - // Not english - String notEnglishDesc = "\uC2B5"; - notEnglish.setDescription(notEnglishDesc); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - // Resource description - end - // Resource icon start - - private void testResourceIconMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconInvalid() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Resource icon end - // Resource tags - start - private void testResourceTagNotExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testResourceTagEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testTagsExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resourceExccedsNameLimit.getName()); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; - String tag2 = resourceExccedsNameLimit.getName(); - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - - resourceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb%#%"; - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); - - } - - // Resource tags - stop - // Resource contact start - - private void testContactIdTooLong() { - Resource resourceContactId = createResourceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - resourceContactId.setContactId(contactIdTooLong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Resource resourceContactId = createResourceObject(false); - // 3 letters and 3 digits and special characters - String contactIdFormatWrong = "yrt134!!!"; - resourceContactId.setContactId(contactIdFormatWrong); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(""); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testVendorNameExceedsLimit() { - Resource resourceExccedsVendorNameLimit = createResourceObject(false); - String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - } - - private void testResourceVendorModelNumberExceedsLimit() { - Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); - String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - } - - private void testVendorNameWrongFormatCreate() { - Resource resource = createResourceObject(false); - // contains * - String nameWrongFormat = "ljg*fd"; - resource.setVendorName(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - } - - private void testVendorReleaseWrongFormat() { - Resource resource = createResourceObject(false); - // contains > - String nameWrongFormat = "1>2"; - resource.setVendorRelease(nameWrongFormat); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); - - } - - private void testVendorReleaseExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - private void testResourceVendorNameMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorName(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); - } - - private void testResourceVendorReleaseMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorRelease(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); - } - - // Resource vendor name/release stop - // Category start - private void testResourceCategoryExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceBadCategoryCreate() { - - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - resourceExist.addCategory("koko", "koko"); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Category stop - // Cost start - private void testHappyScenarioCostLicenseType() { - Resource createResourceObject = createResourceObject(false); - Resource createResourceObjectAfterCreate = createResourceObject(true); - // Adding cost and licenseType to basic mock - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - - String cost = "123.456"; - String licenseType = "User"; - createResourceObject.setCost(cost); - createResourceObject.setLicenseType(licenseType); - Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - createResourceObjectAfterCreate.setCost(cost); - createResourceObjectAfterCreate.setLicenseType(licenseType); - assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); - } - - private void testCostWrongFormatCreate() { - Resource resourceCost = createResourceObject(false); - // Comma instead of fullstop - String cost = "12356,464"; - resourceCost.setCost(cost); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // Cost stop - // License type start - private void testLicenseTypeWrongFormatCreate() { - Resource resourceLicenseType = createResourceObject(false); - // lowcase - String licenseType = "cpu"; - resourceLicenseType.setLicenseType(licenseType); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // License type stop - // Derived from start - private void testResourceTemplateNotExist() { - Resource resourceExist = createResourceObject(false); - List<String> list = null; - resourceExist.setDerivedFrom(list); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDerivedFrom(new ArrayList<String>()); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateInvalid() { - Resource resourceExist = createResourceObject(false); - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - resourceExist.setDerivedFrom(derivedFrom); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - // Derived from stop - - private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - // UPDATE tests - start - // Resource name - @Test - public void testResourceNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setName(nameWrongFormat); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testResourceNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String name = "ljg"; - updatedResource.setName(name); - resource.setVersion("1.0"); - - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - - } - - @Ignore - public void testResourceNameExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - updatedResource.setName(tooLongResourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - @Test - public void testResourceNameAlreadyExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceName = "alreadyExists"; - updatedResource.setName(resourceName); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - // - - @Test - public void testResourceDescExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - updatedResource.setDescription(tooLongResourceDesc); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - - } - - @Test - public void testIconWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains . - String icon = "icon.jpg"; - updatedResource.setIcon(icon); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testIconAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains - String icon = "icon"; - updatedResource.setIcon(icon); - - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - - } - - @Test - public void testTagsExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List<String> tagsList = new ArrayList<String>(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resource.getName()); - - updatedResource.setTags(tagsList); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - } - - @Test - public void testVendorNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - - } - - @Test - public void testVendorNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - - } - - @Test - public void testVendorReleaseExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // 129 chars, the limit is 128 - String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; - updatedResource.setVendorRelease(tooLongVendorRelease); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - @Ignore - public void testContactIdWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - // 3 letters and 3 digits - String contactIdTooLong = "yrt134"; - updatedResource.setContactId(contactIdTooLong); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceBadCategory_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - String badCategory = "ddfds"; - updatedResource.setCategories(null); - updatedResource.addCategory(badCategory, "fikt"); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceCategoryAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - updatedResource.setCategories(null); - updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); - resource.setVersion("1.0"); - ; - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - } - - // Derived from start - @Test - public void testResourceTemplateNotExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - String resourceId = resource.getUniqueId(); - - List<String> list = null; - updatedResource.setDerivedFrom(list); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateEmpty_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - updatedResource.setDerivedFrom(new ArrayList<String>()); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateInvalid_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("kuku"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - - @Test - public void testResourceTemplateCertify_UPDATE_HAPPY() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); - - Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); - when(propertyOperation.deleteAllPropertiesAssociatedToNode(Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isLeft()); - } - - @Test - public void testResourceTemplateCertify_UPDATE_SAD() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) - .thenReturn(isToscaNameExtending); - - resource.setVersion("1.0"); - - ArrayList<String> derivedFrom = new ArrayList<String>(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, - false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - } - // Derived from stop - - @Test - public void createOrUpdateResourceAlreadyCheckout() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - createResponse.left().value().setLastUpdaterUserId(user.getUserId()); - assertTrue(createResponse.isLeft()); - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceCertified() { - Resource resourceExist = createResourceObject(false); - - Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - assertTrue(createResponse.isLeft()); - Resource certifiedResource = createResponse.left().value(); - certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - certifiedResource.setVersion("1.0"); - - - Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); - Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); - - Resource resourceToUpdtae = createResourceObject(false); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceNotExist() { - Resource resourceToUpdtae = createResourceObject(false); - - Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); - - Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { - Resource basic = createResourceObject(true); - - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); - when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - @Test - public void testValidatePropertiesDefaultValues_FailedWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1.5"); - List<PropertyDefinition> properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IElementOperation mockElementDao; + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); + NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); + TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); + final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); + final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + ResponseFormatManager responseManager = null; + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + User user = null; + Resource resourceResponse = null; + Resource genericVF = null; + Resource genericCR = null; + Resource genericVFC = null; + Resource genericPNF = null; + ComponentsUtils componentsUtils; + ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + + public ResourceBusinessLogicTest() { + + } + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); + + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either<User, ActionStatus> eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1); + Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); + + Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); + + Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount); + /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/ + + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + + // createResource + resourceResponse = createResourceObject(true); + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); + Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + artifactManager.setNodeTemplateOperation(nodeTemplateOperation); + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setCapabilityTypeOperation(capabilityTypeOperation); + bl.setComponentsUtils(componentsUtils); + bl.setLifecycleManager(lifecycleBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setArtifactsManager(artifactManager); + bl.setPropertyOperation(propertyOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setApplicationDataTypeCache(applicationDataTypeCache); + bl.setCsarOperation(csarOperation); + bl.setCacheManagerOperation(cacheManager); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); + toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setUserValidations(userValidations); + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); + when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + responseManager = ResponseFormatManager.getInstance(); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource createResourceObjectCsar(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List<String> template = new ArrayList<String>(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setResourceVendorModelNumber(""); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + resource.setCsarUUID("valid_vf.csar"); + resource.setCsarVersion("1"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); + return resource; + } + + @Test + public void testHappyScenario() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createResourceObject(false); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEquals(createResourceObject(true), createResponse.left().value()); + } + + @Test + public void testUpdateHappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); + Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + if (updateResponse.isRight()) { + assertEquals(new Integer(200), updateResponse.right().value().getStatus()); + } + assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); + } + + /* CREATE validations - start ***********************/ + // Resource name - start + + @Test + public void testFailedResourceValidations() { + testResourceNameExist(); + testResourceNameEmpty(); + // testResourceNameExceedsLimit(); + testResourceNameWrongFormat(); + testResourceDescExceedsLimitCreate(); + testResourceDescNotEnglish(); + testResourceDescriptionEmpty(); + testResourceDescriptionMissing(); + testResourceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + testResourceTagNotExist(); + testResourceTagEmpty(); + testTagsExceedsLimitCreate(); + testTagsNoServiceName(); + testInvalidTag(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + testResourceVendorModelNumberExceedsLimit(); + testResourceVendorNameMissing(); + testResourceVendorReleaseMissing(); + testResourceCategoryExist(); + testResourceBadCategoryCreate(); + testHappyScenarioCostLicenseType(); + testCostWrongFormatCreate(); + testLicenseTypeWrongFormatCreate(); + testResourceTemplateNotExist(); + testResourceTemplateEmpty(); + testResourceTemplateInvalid(); + } + + private void testResourceNameExist() { + String resourceName = "alreadyExists"; + Resource resourceExist = createResourceObject(false); + resourceExist.setName(resourceName); + resourceExist.getTags().add(resourceName); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + private void testResourceNameEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceNameExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + resourceExccedsNameLimit.setName(tooLongResourceName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testResourceNameWrongFormat() { + Resource resource = createResourceObject(false); + // contains : + String nameWrongFormat = "ljg?fd"; + resource.setName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Resource name - end + // Resource description - start + private void testResourceDescExceedsLimitCreate() { + Resource resourceExccedsDescLimit = createResourceObject(false); + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + resourceExccedsDescLimit.setDescription(tooLongResourceDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testResourceDescNotEnglish() { + Resource notEnglish = createResourceObject(false); + // Not english + String notEnglishDesc = "\uC2B5"; + notEnglish.setDescription(notEnglishDesc); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + // Resource description - end + // Resource icon start + + private void testResourceIconMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconInvalid() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Resource icon end + // Resource tags - start + private void testResourceTagNotExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testResourceTagEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testTagsExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resourceExccedsNameLimit.getName()); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; + String tag2 = resourceExccedsNameLimit.getName(); + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + + resourceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb%#%"; + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"}); + + } + + // Resource tags - stop + // Resource contact start + + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + resourceContactId.setContactId(contactIdTooLong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Resource resourceContactId = createResourceObject(false); + // 3 letters and 3 digits and special characters + String contactIdFormatWrong = "yrt134!!!"; + resourceContactId.setContactId(contactIdFormatWrong); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(""); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testResourceVendorModelNumberExceedsLimit() { + Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); + String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + } + + private void testVendorReleaseWrongFormat() { + Resource resource = createResourceObject(false); + // contains > + String nameWrongFormat = "1>2"; + resource.setVendorRelease(nameWrongFormat); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); + + } + + private void testVendorReleaseExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + private void testResourceVendorNameMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorName(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); + } + + private void testResourceVendorReleaseMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorRelease(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); + } + + // Resource vendor name/release stop + // Category start + private void testResourceCategoryExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceBadCategoryCreate() { + + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + resourceExist.addCategory("koko", "koko"); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Category stop + // Cost start + private void testHappyScenarioCostLicenseType() { + Resource createResourceObject = createResourceObject(false); + Resource createResourceObjectAfterCreate = createResourceObject(true); + // Adding cost and licenseType to basic mock + Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + createResourceObjectAfterCreate.setCost(cost); + createResourceObjectAfterCreate.setLicenseType(licenseType); + assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); + } + + private void testCostWrongFormatCreate() { + Resource resourceCost = createResourceObject(false); + // Comma instead of fullstop + String cost = "12356,464"; + resourceCost.setCost(cost); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // Cost stop + // License type start + private void testLicenseTypeWrongFormatCreate() { + Resource resourceLicenseType = createResourceObject(false); + // lowcase + String licenseType = "cpu"; + resourceLicenseType.setLicenseType(licenseType); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // License type stop + // Derived from start + private void testResourceTemplateNotExist() { + Resource resourceExist = createResourceObject(false); + List<String> list = null; + resourceExist.setDerivedFrom(list); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDerivedFrom(new ArrayList<String>()); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateInvalid() { + Resource resourceExist = createResourceObject(false); + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + resourceExist.setDerivedFrom(derivedFrom); + + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + // Derived from stop + + private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + // UPDATE tests - start + // Resource name + @Test + public void testResourceNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testResourceNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + @Test + public void testResourceNameAlreadyExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + // + + @Test + public void testResourceDescExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + + } + + @Test + public void testIconWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testIconAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + + } + + @Test + public void testTagsExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List<String> tagsList = new ArrayList<String>(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resource.getName()); + + updatedResource.setTags(tagsList); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + } + + @Test + public void testVendorNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorNameWrongFormat() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorReleaseExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + @Ignore + public void testContactIdWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + updatedResource.setContactId(contactIdTooLong); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceBadCategory_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceCategoryAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + } + + // Derived from start + @Test + public void testResourceTemplateNotExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List<String> list = null; + updatedResource.setDerivedFrom(list); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateEmpty_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList<String>()); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateInvalid_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + + @Test + public void testResourceTemplateCertify_UPDATE_HAPPY() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); + + Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); + when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isLeft()); + } + + @Test + public void testResourceTemplateCertify_UPDATE_SAD() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) + .thenReturn(isToscaNameExtending); + + resource.setVersion("1.0"); + + ArrayList<String> derivedFrom = new ArrayList<String>(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, + false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value()); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceCertified() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + assertTrue(createResponse.isLeft()); + Resource certifiedResource = createResponse.left().value(); + certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + certifiedResource.setVersion("1.0"); + + + Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource); + Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); + + Resource resourceToUpdtae = createResourceObject(false); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceNotExist() { + Resource resourceToUpdtae = createResourceObject(false); + + Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); + + Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { + Resource basic = createResourceObject(true); + + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_FailedWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1.5"); + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); - Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isRight()); - } - -// @Test -// public void testDeleteMarkedResourcesNoResources() { -// List<GraphVertex> ids = new ArrayList<>(); -// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + +// @Test +// public void testDeleteMarkedResourcesNoResources() { +// List<GraphVertex> ids = new ArrayList<>(); +// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); +// +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// } // -// } +// @Test +// public void testDeleteMarkedResources() { +// List<String> ids = new ArrayList<String>(); +// String resourceInUse = "123"; +// ids.add(resourceInUse); +// String resourceFree = "456"; +// ids.add(resourceFree); +// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// @Test -// public void testDeleteMarkedResources() { -// List<String> ids = new ArrayList<String>(); -// String resourceInUse = "123"; -// ids.add(resourceInUse); -// String resourceFree = "456"; -// ids.add(resourceFree); -// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); +// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); // -// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true); -// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false); +// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); +// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); // -// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); -// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); +// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); +// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); // -// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); -// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); +// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); +// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); // -// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource()); -// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); +// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); +// List<String> deletedComponents = new ArrayList<>(); +// deletedComponents.add(resourceFree); +// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); // -// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); -// List<String> deletedComponents = new ArrayList<>(); -// deletedComponents.add(resourceFree); -// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); -// -// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// List<String> resourceIdList = deleteMarkedResources.left().value(); -// assertFalse(resourceIdList.isEmpty()); -// assertTrue(resourceIdList.contains(resourceFree)); -// assertFalse(resourceIdList.contains(resourceInUse)); +// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// List<String> resourceIdList = deleteMarkedResources.left().value(); +// assertFalse(resourceIdList.isEmpty()); +// assertTrue(resourceIdList.contains(resourceFree)); +// assertFalse(resourceIdList.contains(resourceInUse)); // -// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); -// } - - @SuppressWarnings("unchecked") - @Test - public void testFindVfCsarArtifactsToHandle() { - - Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; - String methodName = "findVfCsarArtifactsToHandle"; - Resource resource = new Resource(); - String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; - String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; - String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; - - String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; - String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; - String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; - - byte[] oldPayloadData = "oldPayloadData".getBytes(); - byte[] newPayloadData = "newPayloadData".getBytes(); - Map<String, ArtifactDefinition> deploymentArtifacts =new HashMap<>(); - - ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); - deploymentArtifactToUpdate.setMandatory(false); - deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); - deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); - deploymentArtifactToUpdate.setPayload(oldPayloadData); - deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); - deploymentArtifactToDelete.setMandatory(false); - deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); - deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); - deploymentArtifactToDelete.setPayload(oldPayloadData); - deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); - - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); - deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); - - Map<String, ArtifactDefinition> artifacts = new HashMap<>(); - - ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); - artifactToUpdate.setMandatory(false); - artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); - artifactToUpdate.setArtifactType("SNMP_POLL"); - artifactToUpdate.setPayload(oldPayloadData); - artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToDelete = new ArtifactDefinition(); - artifactToDelete.setMandatory(false); - artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); - artifactToDelete.setArtifactType("SNMP_TRAP"); - artifactToDelete.setPayload(oldPayloadData); - artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); - - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()),artifactToUpdate); - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()),artifactToDelete); - artifacts.put("ignore",artifactToIgnore); - - resource.setDeploymentArtifacts(deploymentArtifacts); - resource.setArtifacts(artifacts); - - List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); - NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, deploymentArtifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName); - - NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactInfoToCreateFileName); - - artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); - artifactPathAndNameList.add(informationalArtifactInfoToUpdate); - artifactPathAndNameList.add(deploymentArtifactInfoToCreate); - artifactPathAndNameList.add(informationalArtifactInfoToCreate); - - Object[] argObjects = {resource, artifactPathAndNameList, user}; - Class[] argClasses = {Resource.class, List.class, User.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = - (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Update).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - - } - catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testVFGeneratedInputs() { - - Resource resource = createVF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); - } - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckout() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - // create a new generic version without properties - genericVF.setVersion("2.0"); - genericVF.setProperties(null); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - List<InputDefinition> currentInputs = resource.getInputs(); - //verify previous inputs ownerId fields exist - user may not delete generated inputs - assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update required and valid - assertTrue(upgradeToLatestGeneric.left().value()); - //verify version was upgraded - assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not deleted - assertTrue(8 == resource.getInputs().size()); - //verify inputs ownerId fields were removed - user may delete/edit inputs - assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - } - - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - - //add an input to the VF - PropertyDefinition newProp = new PropertyDefinition(); - newProp.setType("integer"); - newProp.setName("newProp"); - resource.getInputs().add(new InputDefinition(newProp)); - - //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type - genericVF.setVersion("2.0"); - newProp.setType("string"); - genericVF.setProperties(new ArrayList<PropertyDefinition>()); - genericVF.getProperties().add(newProp); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update is invalid an void - assertFalse(upgradeToLatestGeneric.left().value()); - //verify version was not upgraded - assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not removed - assertTrue(9 == resource.getInputs().size()); - //verify user defined input exists - assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); - } - - @Test - public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { - - Resource resource = createPNF(); - List<InputDefinition> inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); - assertTrue(0 == resource.getArtifacts().size()); - } - - - private Resource createVF() { - - genericVF = setupGenericTypeMock(GENERIC_VF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.VF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - private Resource createPNF() { - - genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.PNF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - - +// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); +// } + + @SuppressWarnings("unchecked") + @Test + public void testFindVfCsarArtifactsToHandle() { + + Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class; + String methodName = "findVfCsarArtifactsToHandle"; + Resource resource = new Resource(); + String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; + String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; + String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; + + String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; + String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; + String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml"; + String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; + + byte[] oldPayloadData = "oldPayloadData".getBytes(); + byte[] newPayloadData = "newPayloadData".getBytes(); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + + ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); + deploymentArtifactToUpdate.setMandatory(false); + deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); + deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); + deploymentArtifactToUpdate.setPayload(oldPayloadData); + deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); + deploymentArtifactToDelete.setMandatory(false); + deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); + deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); + deploymentArtifactToDelete.setPayload(oldPayloadData); + deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); + + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); + deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); + + Map<String, ArtifactDefinition> artifacts = new HashMap<>(); + + ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); + artifactToUpdate.setMandatory(false); + artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); + artifactToUpdate.setArtifactType("SNMP_POLL"); + artifactToUpdate.setPayload(oldPayloadData); + artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition artifactToDelete = new ArtifactDefinition(); + artifactToDelete.setMandatory(false); + artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); + artifactToDelete.setArtifactType("SNMP_TRAP"); + artifactToDelete.setPayload(oldPayloadData); + artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToDelete.setIsFromCsar(true); + + ArtifactDefinition artifactToNotDelete = new ArtifactDefinition(); + artifactToNotDelete.setMandatory(false); + artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName); + artifactToNotDelete.setArtifactType("SNMP_TRAP"); + artifactToNotDelete.setPayload(oldPayloadData); + artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToNotDelete.setIsFromCsar(false); + + ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); + + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete); + artifacts.put("ignore", artifactToIgnore); + + resource.setDeploymentArtifacts(deploymentArtifacts); + resource.setArtifacts(artifacts); + + List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>(); + NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false); + + NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactInfoToCreateFileName, false); + + artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdate); + artifactPathAndNameList.add(deploymentArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar); + artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar); + + Object[] argObjects = {resource, artifactPathAndNameList, user}; + Class[] argClasses = {Resource.class, List.class, User.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = + (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size() == 1); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testVFGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(8 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); + } + + @Test + public void testCRGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createCR(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(5 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericCR.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericCR.getVersion())); + } + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckout() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + //create a VF that is derived from generic version 1.0 + Resource resource = createVF(); + // create a new generic version without properties + genericVF.setVersion("2.0"); + genericVF.setProperties(null); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + List<InputDefinition> currentInputs = resource.getInputs(); + //verify previous inputs ownerId fields exist - user may not delete generated inputs + assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update required and valid + assertTrue(upgradeToLatestGeneric.left().value()); + //verify version was upgraded + assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not deleted + assertTrue(8 == resource.getInputs().size()); + //verify inputs ownerId fields were removed - user may delete/edit inputs + assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + } + + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { + + //create a VF that is derived from generic version 1.0 + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + + //add an input to the VF + PropertyDefinition newProp = new PropertyDefinition(); + newProp.setType("integer"); + newProp.setName("newProp"); + resource.getInputs().add(new InputDefinition(newProp)); + + //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type + genericVF.setVersion("2.0"); + newProp.setType("string"); + genericVF.setProperties(new ArrayList<PropertyDefinition>()); + genericVF.getProperties().add(newProp); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update is invalid an void + assertFalse(upgradeToLatestGeneric.left().value()); + //verify version was not upgraded + assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not removed + assertTrue(9 == resource.getInputs().size()); + //verify user defined input exists + assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); + } + + @Test + public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createPNF(); + List<InputDefinition> inputs = resource.getInputs(); + assertTrue(3 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); + assertTrue(0 == resource.getArtifacts().size()); + } + + + private Resource createVF() { + + genericVF = setupGenericTypeMock(GENERIC_VF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.VF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Resource createCR() { + + genericCR = setupGenericTypeMock(GENERIC_CR_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.CR); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + private Resource createPNF() { + + genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.PNF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Map<String, String> getGenericPropertiesByToscaName(String toscaName) { + HashMap<String, String> PNFProps = new HashMap<String, String>() {{ + put("nf_function", "string"); + put("nf_role", "string"); + put("nf_type", "string"); + }}; + + HashMap<String, String> CRProps = new HashMap<String, String>() {{ + putAll(PNFProps); + put("nf_naming_code", "string"); + put("nf_naming", "org.openecomp.datatypes.Naming"); + }}; + + HashMap<String, String> VFProps = new HashMap<String, String>() {{ + putAll(CRProps); + put("availability_zone_max_count", "integer"); + put("min_instances", "integer"); + put("max_instances", "integer"); + }}; + + if (toscaName.contains("PNF")) return PNFProps; + if (toscaName.contains("CR")) return CRProps; + if (toscaName.contains("VF")) return VFProps; + + return new HashMap<>(); + } + + private Resource setupGenericTypeMock(String toscaName) { - - Resource genericType = createResourceObject(true); - genericType.setVersion("1.0"); - genericType.setToscaResourceName(toscaName); - String[] propNames = {"nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count", "min_instances", "max_instances"}; - String[] propTypes = {"string", "string", "string", "string", "org.openecomp.datatypes.Naming", "integer", "integer", "integer"}; - List<PropertyDefinition> genericProps = new ArrayList<>(); - for(int i = 0; i < 8; ++i){ - PropertyDefinition prop = new PropertyDefinition(); - prop.setName(propNames[i]); - prop.setType(propTypes[i]); - genericProps.add(prop); - } - genericType.setProperties(genericProps); - return genericType; - } - - - + + Resource genericType = createResourceObject(true); + genericType.setVersion("1.0"); + genericType.setToscaResourceName(toscaName); + List<PropertyDefinition> genericProps = new ArrayList<>(); + Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName); + genericPropsMap.forEach((name, type) -> { + PropertyDefinition prop = new PropertyDefinition(); + prop.setName(name); + prop.setType(type); + genericProps.add(prop); + }); + + genericType.setProperties(genericProps); + return genericType; + } + + private void validateUserRoles(Role... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java index 581adb28df..3abf711b91 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -53,6 +44,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ConfigurationSource; @@ -61,252 +53,259 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class ResourceInstanceBusinessLogicTest { - private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; - private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; - private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; - private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; - private static final String SERVICE_ID = "MyServiceId"; - private static final String HEAT_LABEL = "myHeat"; - private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; - private static final String USER_ID = "jh0003"; - private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); - - static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); - - @InjectMocks - static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic(); - - public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); - public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); -// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); - public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // @BeforeClass - public static void setup() { - - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); - - ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); - Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); - artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); - - ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); - Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); - artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); - - ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); - Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); - artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); - - Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); - Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); - - Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); - - Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); - - Either<User, ActionStatus> eitherUser = Either.left(adminUser); - Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); - - Object lightService = new Service(); - Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); -// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); - - Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), - Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); - - Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - - Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), - Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); - - Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); - Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); - - bl.setToscaOperationFacade(toscaOperationFacade); - - StorageOperationStatus status = StorageOperationStatus.OK; - Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); - Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); - Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); - - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); -// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); - setup(); - } - - @Test - public void testAddResourceInstanceArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); + private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; + private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; + private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; + private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; + private static final String SERVICE_ID = "MyServiceId"; + private static final String HEAT_LABEL = "myHeat"; + private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; + private static final String USER_ID = "jh0003"; + private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); + + static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); + + @InjectMocks + static ComponentInstanceBusinessLogic bl = new ComponentInstanceBusinessLogic(); + + public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); + public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); +// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); + public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // @BeforeClass + public static void setup() { + + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); + + ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); + Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>(); + artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); + + ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); + Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>(); + artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); + + ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); + Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>(); + artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); + + Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); + Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); + + Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class)); + + Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); + + Either<User, ActionStatus> eitherUser = Either.left(adminUser); + Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); + + Object lightService = new Service(); + Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService); + + Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.any(AuditingActionEnum.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ResourceAuditData.class)); + + Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + + Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), + Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); + + Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>()); + Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); + + bl.setToscaOperationFacade(toscaOperationFacade); + + StorageOperationStatus status = StorageOperationStatus.OK; + Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); + Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); + Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); + + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); +// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); + setup(); + } + + @Test + public void testAddResourceInstanceArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); // -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); // -// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); -// assertNotNull(heatParameters); +// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); +// assertNotNull(heatParameters); // -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNotNull(heatEnvParameters); +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNotNull(heatEnvParameters); // -// assertEquals(heatParameters.size(), heatEnvParameters.size()); +// assertEquals(heatParameters.size(), heatEnvParameters.size()); // -// int index = 0; -// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { -// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); -// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); -// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); -// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); -// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); -// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); -// // current of heat parameter should be the default for heat env -// // parameter -// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); +// int index = 0; +// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { +// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); +// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); +// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); +// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); +// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); +// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); +// // current of heat parameter should be the default for heat env +// // parameter +// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); // -// index++; -// } - } - - @Test - public void testAddResourceInstanceArtifactsNoParams() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); - -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); - - List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); - assertNull(heatParameters); - -// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNull(heatEnvParameters); - - } - - @SuppressWarnings("unchecked") - @Test - public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map<String, String> existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - - Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); - assertTrue(deploymentArtifacts.size() == 0); - - Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); - } - - private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".yml"); - artifactInfo.setArtifactType("HEAT"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - // long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); - - if (!placeholderOnly) { - artifactInfo.setEsId(artifactInfo.getUniqueId()); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - - if (withHeatParams) { - List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactInfo.setListHeatParameters(heatParams); - } - } - - return artifactInfo; - } - - private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } +// index++; +// } + } + + @Test + public void testAddResourceInstanceArtifactsNoParams() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); + +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); + + List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters(); + assertNull(heatParameters); + +// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNull(heatEnvParameters); + + } + + @SuppressWarnings("unchecked") + @Test + public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map<String, String> existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + + Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 0); + + Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); + } + + private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + artifactInfo.setUserIdCreator(userId); + String fullName = "Jim H"; + artifactInfo.setUpdaterFullName(fullName); + // long time = System.currentTimeMillis(); + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(userId); + artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + + if (!placeholderOnly) { + artifactInfo.setEsId(artifactInfo.getUniqueId()); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + if (withHeatParams) { + List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactInfo.setListHeatParameters(heatParams); + } + } + + return artifactInfo; + } + + private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java index 309689af45..5f4dfdc6f7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java @@ -1,12 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +14,12 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class GenericTypeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java new file mode 100644 index 0000000000..6b1b37e5bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java @@ -0,0 +1,258 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class PolicyTypeImportUtilsTest { + + private static final String UNIQUE_ID_EXSISTS = "uniqueId"; + + @Test + public void isPolicyTypesEquals_whenBothTypesAreNull_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, null)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenOneTypeIsNull_returnFalse() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(new PolicyTypeDefinition(), null)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, new PolicyTypeDefinition())).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTypesIsSameObject_returnTrue() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(policyType, policyType)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_allFieldsEquals_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(createPolicyTypeWithAllFields(), createPolicyTypeWithAllFields())).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenTypesAreDifferentInANonCompareFields_returnTrue() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setOwnerId("ownerIdNew"); + type2.setModificationTime(System.currentTimeMillis()); + type2.setCreationTime(System.currentTimeMillis()); + type2.setUniqueId("uniqueIdNew"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenTypeIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setType("newType"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDescription("newDescription"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTargetsAreDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setTargets(new ArrayList<>()); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDerivedFromIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDerivedFrom("newDerivedFrom"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenVersionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setVersion("2.0"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenMetadataIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setMetadata(ImmutableMap.of("newKey", "newVal")); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() { + PolicyTypeDefinition noProperties = new PolicyTypeDefinition(); + PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build(); + PolicyTypeDefinition oneProp = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition twoProps = new PolicyTypeBuilder().setProperties(Arrays.asList(createPropertyDefinitionWithAllFields("prop1"), + createPropertyDefinitionWithAllFields("prop2"))) + .build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(twoProps, oneProp)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesSamePropertiesList_returnTrue() { + List<PropertyDefinition> propList = Collections.singletonList(createPropertyDefinitionWithAllFields("prop1")); + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(propList).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(propList).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListFieldsEquals_returnTrue() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListDifferentInANonComparedFields_returnTrue() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffNonComparedFields = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffNonComparedFields.setOwnerId("newOwner"); + prop1DiffNonComparedFields.setValue("newVal"); + prop1DiffNonComparedFields.setConstraints(null); + prop1DiffNonComparedFields.setUniqueId("newId"); + prop1DiffNonComparedFields.setHidden(true); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffNonComparedFields)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameName_returnFalse() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop2"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOFSameType_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1TypeInteger = createPropertyDefinitionWithAllFields("prop1"); + prop1TypeInteger.setType("integer"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1TypeInteger)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameDefaultVal_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDefault = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDefault.setDefaultValue("newDefVal"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDefault)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameSchema_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffSchema = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffSchema.setSchema(null); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffSchema)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsPasswordFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsPassword = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsPassword.setPassword(!prop1.isPassword()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsPassword)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsRequiredFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsRequired = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsRequired.setRequired(!prop1.isRequired()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsRequired)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotSameDescription_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDescription = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDescription.setDescription("newDescription"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDescription)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + private PolicyTypeDefinition createPolicyTypeWithAllFields() { + return new PolicyTypeBuilder() + .setType("type1") + .setDerivedFrom("derivedFrom") + .setVersion("1.0") + .setDescription("description") + .setUniqueId("id1") + .setHighestVersion(true) + .setModificationTime(System.currentTimeMillis()) + .setCreationTime(System.currentTimeMillis()) + .setTargets(getTargets()) + .setOwner("owner") + .setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2")) + .build(); + } + + private PropertyDefinition createPropertyDefinitionWithAllFields(String name) { + return new PropertyDataDefinitionBuilder() + .setConstraints(Arrays.asList(new GreaterThanConstraint("abc"), new MinLengthConstraint(5))) + .setUniqueId("uid") + .setDefaultValue("val1") + .setType("string") + .setValue("val1") + .setName(name) + .setSchemaType("string") + .setOwnerId("owner") + .setStatus("status") + .setDescription("description") + .setIsPassword(false) + .setIsRequired(false) + .build(); + } + + private List<String> getTargets() { + + return Collections.singletonList(UNIQUE_ID_EXSISTS); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java new file mode 100644 index 0000000000..0dac6ecb2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestGenerationUtils { + + public static ComponentsUtils getComponentsUtils() { + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + return new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java new file mode 100644 index 0000000000..fe6071239e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java @@ -0,0 +1,152 @@ +package org.openecomp.sdc.be.components.impl.version; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GroupMembersUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + private static final String INSTANCE_ID_PRE_CHANGE = "inst2"; + private static final String INSTANCE_ID_POST_CHANGE = "newInst2"; + @InjectMocks + private GroupMembersUpdateOperation testInstance; + @Mock + private GroupsOperation groupsOperation; + @Mock + private ComponentsUtils componentsUtils; + + @Captor + private ArgumentCaptor<List<GroupDataDefinition>> updatedGroupsCaptor; + private GroupDefinition group1, group2, group3; + private Resource container; + private ComponentInstance prevInst2Version, currInst2Version; + private static final ComponentInstance DONT_CARE = new ComponentInstance(); + + @Before + public void setUp() throws Exception { + group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE); + group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3"); + group3 = createGroupWithMembers("group3", "inst1", "inst3"); + container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .setUniqueId(CONTAINER_ID) + .setComponentType(ComponentTypeEnum.RESOURCE) + .build(); + prevInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_PRE_CHANGE) + .build(); + currInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_POST_CHANGE) + .build(); + } + + @Test + public void whenNoGroupsOnContainer_returnOk() { + ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenEmptyListOfGroups_returnOk() { + Resource resource = new Resource(); + resource.setGroups(new ArrayList<>()); + ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupsHasNoMembers_returnOk() { + GroupDefinition group1 = new GroupDefinition(); + group1.setMembers(emptyMap()); + GroupDefinition group2 = new GroupDefinition(); + group2.setMembers(emptyMap()); + Resource container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .build(); + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() { + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() { + verifyAllGroupsHasPrevInstancesAsMembers(); + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null)); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyGroupWithPrevInstanceMemberWereReplaced(); + assertThat(updatedGroupsCaptor.getValue()) + .containsExactlyInAnyOrder(group1, group2); + } + + @Test + public void whenFailingToUpdateGroups_propagateError() { + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void verifyGroupWithPrevInstanceMemberWereReplaced() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void verifyAllGroupsHasPrevInstancesAsMembers() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_PRE_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_PRE_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void assertGroupMembersIds(GroupDefinition group, String ... expectedMembersIds) { + assertThat(group.getMembers()) + .containsValues(expectedMembersIds); + } + + private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) { + GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create(); + Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId)); + groupDefinitionBuilder.setUniqueId(groupId); + return groupDefinitionBuilder.build(); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java new file mode 100644 index 0000000000..0da59d1157 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.utils.TestGenerationUtils.getComponentsUtils; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTargetsUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + + private PolicyTargetsUpdateOperation policyTargetsUpdateOperation; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Captor + private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor; + private PolicyDefinition policy1, policy2, policy3; + private Resource container; + + @Before + public void setUp() throws Exception { + policy1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2"); + policy2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3"); + policy3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3"); + container = new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .addPolicy(policy3) + .setUniqueId(CONTAINER_ID) + .build(); + policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils()); + } + + @Test + public void whenNoPolicies_returnActionOk() { + Component container = new Resource(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoCmptInstancePolicies_returnOk() { + PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build(); + Component container = new ResourceBuilder().addPolicy(policy).build(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.OK); + List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue(); + verifyUpdatedPolicies(updatedPolicies, policy1, policy2);//policy3 does not have "inst2" as target, no update needed + verifyUpdatedPolicyTargets(policy1, "inst1", "inst2New"); + verifyUpdatedPolicyTargets(policy2, "inst1", "inst2New", "inst3"); + } + + @Test + public void whenUpdateOfPoliciesFails_propagateTheFailure() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) { + assertThat(updatedPolicy.resolveComponentInstanceTargets()) + .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds); + } + + private void verifyUpdatedPolicies(List<PolicyDefinition> updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) { + assertThat(updatedPolicies) + .usingElementComparatorOnFields("targets") + .containsExactlyInAnyOrder(expectedUpdatedPolicies); + } + + private PolicyDefinition createPolicyWithCmptInstAsTargets(String uniqueId, String ... instId) { + PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create(); + Stream.of(instId).forEach(policyDefinitionBuilder::addComponentInstanceTarget); + return policyDefinitionBuilder.setUniqueId(uniqueId).build(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java new file mode 100644 index 0000000000..ef239f9a2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PostChangeVersionOperationOrchestratorTest { + + private PostChangeVersionOperationOrchestrator testInstance; + @Mock + private PostChangeVersionOperation postChangeVersionOperation1; + @Mock + private PostChangeVersionOperation postChangeVersionOperation2; + @Mock + private PostChangeVersionOperation postChangeVersionOperation3; + + @Before + public void setUp() throws Exception { + testInstance = new PostChangeVersionOperationOrchestrator(asList(postChangeVersionOperation1, postChangeVersionOperation2, postChangeVersionOperation3)); + } + + @Test + public void whenFirstPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation2, postChangeVersionOperation3); + } + + @Test + public void whenAnyPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation3); + } + + @Test + public void whenLastPostOperationFails_returnTheFailureResult() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void whenAllOperationsSucceeds_returnOk() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + +}
\ No newline at end of file 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 index 31c795478a..cfb5bb59e0 100644 --- 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 @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; 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; @@ -35,139 +32,138 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CertificationChangeTransitionTest extends LifecycleTestBase { - private CertificationChangeTransition certifyTransitionObj = null; - private CertificationChangeTransition certificationCancelObj = null; - private CertificationChangeTransition certificationFailObj = null; - - private ComponentsUtils componentsUtils = new ComponentsUtils(); - private User owner = null; - - Resource resource; - - @SuppressWarnings("unchecked") - @Before - public void setup() { - - super.setup(); - componentsUtils.Init(); - // checkout transition object - certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certifyTransitionObj.setConfigurationManager(configurationManager); - certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationCancelObj.setConfigurationManager(configurationManager); - certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationFailObj.setConfigurationManager(configurationManager); - certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - resource = createResourceObject(); - } - - @Test - public void testVFCMTStateValidation(){ - Resource resource = createResourceVFCMTObject(); - - User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isLeft(), true); - } - - @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()); - } + private CertificationChangeTransition certifyTransitionObj = null; + private CertificationChangeTransition certificationCancelObj = null; + private CertificationChangeTransition certificationFailObj = null; + + private User owner = null; + + Resource resource; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + + super.setup(); + // checkout transition object + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certifyTransitionObj.setConfigurationManager(configurationManager); + certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationCancelObj.setConfigurationManager(configurationManager); + certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationFailObj.setConfigurationManager(configurationManager); + certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + resource = createResourceObject(); + } + + @Test + public void testVFCMTStateValidation(){ + Resource resource = createResourceVFCMTObject(); + + User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isLeft(), true); + } + + @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 index 5530d4c0f5..f9fb9c83c1 100644 --- 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 @@ -20,13 +20,7 @@ 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 fj.data.Either; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -38,7 +32,6 @@ import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionAr import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; 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.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -55,215 +48,219 @@ import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.Silent.class) public class CertificationRequestTest extends LifecycleTestBase { - private ComponentsUtils componentsUtils = new ComponentsUtils(); - @Mock - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Mock - private ServiceBusinessLogic serviceBusinessLogic; - @Mock - private CapabilityOperation capabilityOperation; - @Mock - private ToscaExportHandler toscaExportUtils; - - private CertificationRequestTransition rfcObj; - - - @Before - public void setup() { - super.setup(); - rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); - // checkout transition object -// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); - // checkoutObj.setAuditingManager(iAuditingManager); - rfcObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - -// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation); -// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); - } - - @Test - public void testVFCMTStateValidation(){ - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceVFCMTObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - User user = new User(); - user.setUserId("cs0008"); - user.setFirstName("Carlos"); - user.setLastName("Santana"); - user.setRole(Role.TESTER.name()); - - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - @Test - public void testCheckoutStateValidation() { - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - 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(); - - 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(); - - 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(); - - 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")); - - } - - @Test - public void testDeploymentArtifactRestriction() { - Either<? extends Component, ResponseFormat> changeStateResult; - Service service = createServiceObject(false); - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either<Service, ResponseFormat> result = Either.left(service); - Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); - when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - private void simulateCertifiedVersionExistForRI() { - Component dummyResource = new Resource(); - Either<Component, StorageOperationStatus> result = Either.left(dummyResource); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); - Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.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; - } + @Mock + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + @Mock + private CapabilityOperation capabilityOperation; + @Mock + private ToscaExportHandler toscaExportUtils; + + private CertificationRequestTransition rfcObj; + + + @Before + public void setup() { + super.setup(); + rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); + // checkout transition object +// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); + // checkoutObj.setAuditingManager(iAuditingManager); + rfcObj.setConfigurationManager(configurationManager); + +// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation); +// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); + + } + + @Test + public void testVFCMTStateValidation(){ + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceVFCMTObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + User user = new User(); + user.setUserId("cs0008"); + user.setFirstName("Carlos"); + user.setLastName("Santana"); + user.setRole(Role.TESTER.name()); + + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + 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(); + + 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(); + + 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(); + + 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")); + + } + + @Test + public void testDeploymentArtifactRestriction() { + Either<? extends Component, ResponseFormat> changeStateResult; + Service service = createServiceObject(); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either<Service, ResponseFormat> result = Either.left(service); + Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); + when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, true); + assertEquals(changeStateResult.isLeft(), true); + } + + private void simulateCertifiedVersionExistForRI() { + Component dummyResource = new Resource(); + Either<Component, StorageOperationStatus> result = Either.left(dummyResource); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); + Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.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 index 21111ef59e..e60998b177 100644 --- 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 @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; 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; @@ -35,135 +32,133 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; 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, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkinObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - } - - @Test - public void testSimpleCheckin() { - Either<Boolean, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - 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(); - - 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(); - - 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()); - - } + private CheckinTransition checkinObj = null; + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkinObj.setConfigurationManager(configurationManager); + } + + @Test + public void testSimpleCheckin() { + Either<Boolean, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + 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(); + + 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(); + + 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(); + + 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(); + + 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(); + + 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 index 1e3f6f6ce8..0826e5d40c 100644 --- 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 @@ -20,16 +20,13 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; 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.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; @@ -37,153 +34,151 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; 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, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setComponentsUtils(componentsUtils); - - } - - @Test - public void testCheckoutStateValidation() { - Either<? extends Component, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); - - 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(); - - 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(); - - 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(); - - 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(); - - 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); - - } + private CheckoutTransition checkoutObj = null; + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkoutObj.setConfigurationManager(configurationManager); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setComponentsUtils(componentsUtils); + + } + + @Test + public void testCheckoutStateValidation() { + Either<? extends Component, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); + + 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(); + + 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(); + + 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(); + + 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(); + + 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 index bc131ff39a..941af0d728 100644 --- 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 @@ -20,20 +20,13 @@ 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 fj.data.Either; import org.junit.BeforeClass; 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.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -41,6 +34,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; 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; @@ -67,173 +61,185 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.when; 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 ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); - protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; - protected User user = null; - protected Resource resourceResponse; - protected Service serviceResponse; - protected static ConfigurationManager configurationManager = null; - protected ResponseFormatManager responseManager = null; - protected TitanDao titanDao = Mockito.mock(TitanDao.class); - protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - @BeforeClass - public static void setupClass() { - 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); - } - - public void setup() { - - // 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.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); - when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); - - // Resource Operation mock methods - // getCount - - // createResource - resourceResponse = createResourceObject(); - Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); - when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - Either<User, StorageOperationStatus> getOwnerResult = Either.left(user); - when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); - - Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK); - when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); - - 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() { - Resource resource = new Resource(); - resource.setName("MyResourceName"); - resource.setUniqueId("uid"); - 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"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Resource createResourceVFCMTObject() { - ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); - rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); - ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; - - Resource resource = new Resource(cMetadataDataDefinition); - resource.setUniqueId("rid"); - resource.setName("MyResourceVFCMTName"); - resource.addCategory("VoIP", "INfra"); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<String>(); - tgs.add("test1"); - 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"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Service createServiceObject(boolean b) { - Service service = new Service(); - service.setName("MyServiceName"); - service.setUniqueId("sid"); - 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"); - - return service; - } - - protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - 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; - } + private static final Logger log = LoggerFactory.getLogger(LifecycleTestBase.class); + @InjectMocks + protected final ServletContext servletContext = Mockito.mock(ServletContext.class); + protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; + protected User user = null; + protected Resource resourceResponse; + protected Service serviceResponse; + protected static ConfigurationManager configurationManager = null; + protected ResponseFormatManager responseManager = null; + protected TitanDao titanDao = Mockito.mock(TitanDao.class); + protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + protected static ComponentsUtils componentsUtils; + + @BeforeClass + public static void setupClass() { + 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); + + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } + + 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); + + + // 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.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); + when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); + + // Resource Operation mock methods + // getCount + + // createResource + resourceResponse = createResourceObject(); + Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); + when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + Either<User, StorageOperationStatus> getOwnerResult = Either.left(user); + when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); + + Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK); + when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); + + 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() { + Resource resource = new Resource(); + resource.setUniqueId("uid"); + resource.setName("MyResourceName"); + resource.setUniqueId("uid"); + 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"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Resource createResourceVFCMTObject() { + ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); + rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); + ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; + + Resource resource = new Resource(cMetadataDataDefinition); + resource.setUniqueId("rid"); + resource.setName("MyResourceVFCMTName"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List<String> tgs = new ArrayList<String>(); + tgs.add("test1"); + 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"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Service createServiceObject() { + Service service = new Service(); + service.setName("MyServiceName"); + service.setUniqueId("sid"); + 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"); + + return service; + } + + protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + 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 index 11913ad31a..d5d665809d 100644 --- 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 @@ -20,105 +20,100 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; 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; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class UndoCheckoutTest extends LifecycleTestBase { - private UndoCheckoutTransition undoCheckoutObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - - @Before - public void setup() { + private UndoCheckoutTransition undoCheckoutObj = null; - super.setup(); + @Before + public void setup() { - // checkout transition object - undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - undoCheckoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); + super.setup(); + // checkout transition object + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + undoCheckoutObj.setConfigurationManager(configurationManager); - } + } - @Test - public void testResourceNotCheckedOutValidation() { - Either<Resource, ResponseFormat> changeStateResult; - Resource resource = createResourceObject(); + @Test + public void testResourceNotCheckedOutValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); + 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()); + 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); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + 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); + 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()); + 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); + 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()); + 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); + 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()); + 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(); + @Test + public void testDifferentResourceOwnerValidation() { + Either<Resource, ResponseFormat> changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); + 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); + 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()); - } + 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/components/merge/GlobalInputsFilteringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java index ab2e865ae0..89b82b91d2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java @@ -1,14 +1,7 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - +import com.google.common.collect.Sets; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -24,9 +17,14 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class GlobalInputsFilteringBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java index a00b0b8e8a..ec741b4953 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -18,7 +11,13 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; public class GlobalTypesMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java index 773b068cd7..d50f4859db 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; @@ -14,14 +9,23 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class RelationsComparatorTest { public static final String INSTANCE1 = "instance1"; public static final String INSTANCE2 = "instance2"; RelationsComparator testInstance; - private RequirementCapabilityRelDef relation1, relation2, relation3, relation4; - private ComponentInstance componentInstance1, componentInstance2; + private RequirementCapabilityRelDef relation1; + private RequirementCapabilityRelDef relation2; + private RequirementCapabilityRelDef relation3; + private RequirementCapabilityRelDef relation4; + private ComponentInstance componentInstance1; + private ComponentInstance componentInstance2; @Before public void setUp() { @@ -59,21 +63,21 @@ public class RelationsComparatorTest { @Test public void isRelationsChanged_notSameType() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().getRelationship().setType("someDiffType"); + relation2DifType.resolveSingleRelationship().getRelation().getRelationship().setType("someDiffType"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameCapability() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); + relation2DifType.resolveSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameReqName() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setRequirement("someDiffReq"); + relation2DifType.resolveSingleRelationship().getRelation().setRequirement("someDiffReq"); isRelationsChangedTest(relation2DifType); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java index 3b1ed52550..298a4454b3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java @@ -1,10 +1,6 @@ package org.openecomp.sdc.be.components.merge; -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 fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +16,10 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class TopologyComparatorTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java new file mode 100644 index 0000000000..be9f426c2c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java @@ -0,0 +1,113 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import java.util.Map; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleCapabilityResolverTest { + + public static final String NEW_OWNER_ID1 = "owner1"; + public static final String NEW_OWNER_ID2 = "owner2"; + public static final String OLD_OWNER_ID1 = "oldOwner1"; + private static final String OLD_OWNER_ID2 = "oldOwner2"; + public static final String OLD_OWNER_ID3 = "oldOwner3"; + @InjectMocks + private SimpleCapabilityResolver testInstance; + @Mock + private MergeInstanceUtils MergeInstanceUtils; + + private CapabilityDefinition capName1Owner1Type1; + private CapabilityDefinition capName1Owner1Type2; + private CapabilityDefinition capName1Owner2Type1; + private CapabilityDefinition capName2Owner1Type2; + + private CapabilityDefinition prevCapName1Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type2; + private CapabilityDefinition prevCapName1Owner2Type1; + private CapabilityDefinition prevCapName2Owner1Type2; + private CapabilityDefinition prevCapName1Owner3Type1; + private CapabilityDefinition prevCapName3Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type3; + CapabilityDefinition[] prevCapabilities; + private ComponentInstance oldInstance; + private ComponentInstance currInstance; + + + @Before + public void setUp() { + capName1Owner1Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type1 = new CapabilityDefinition(capName1Owner1Type1); + prevCapName1Owner1Type1.setOwnerId(OLD_OWNER_ID1); + + capName1Owner1Type2 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName1Owner1Type2 = new CapabilityDefinition(capName1Owner1Type2); + prevCapName1Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + capName1Owner2Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID2).setType("type1").build(); + prevCapName1Owner2Type1 = new CapabilityDefinition(capName1Owner2Type1); + prevCapName1Owner2Type1.setOwnerId(OLD_OWNER_ID2); + + capName2Owner1Type2 = new CapabilityDefinitionBuilder().setName("name2").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName2Owner1Type2 = new CapabilityDefinition(capName2Owner1Type2); + prevCapName2Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + //prev capabilities that are not mapped to any new capability + prevCapName1Owner3Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID3).setType("type1").build(); + prevCapName3Owner1Type1 = new CapabilityDefinitionBuilder().setName("name3").setOwnerId(OLD_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type3 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID1).setType("type3").build(); + + currInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(capName1Owner1Type1, capName1Owner1Type2, capName1Owner2Type1, capName2Owner1Type2).build(); + prevCapabilities = new CapabilityDefinition[]{prevCapName1Owner1Type1, prevCapName1Owner1Type2, prevCapName1Owner2Type1, prevCapName2Owner1Type2, prevCapName1Owner3Type1, prevCapName3Owner1Type1, prevCapName1Owner1Type3}; + oldInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(prevCapabilities).build(); + } + + @Test + public void resolvePrevCapIdToNewCapability_resolveByTypeNameAndNewOwnerId() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } + + @Test + public void resolvePrevCapIdToNewCapability_noMatchingNewOwnerIds() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(emptyMap()); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).isEmpty(); + } + + @Test + public void mapOldToNewInstanceCapabilitiesOwnerIds() { + Resource container = new ResourceBuilder().addComponentInstance(currInstance).build(); + Resource prevInstanceOrigNode = new Resource(); + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, "inst1", asList(OLD_OWNER_ID1, OLD_OWNER_ID2, OLD_OWNER_ID3))).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapToNewCapability(container, prevInstanceOrigNode, "inst1", asList(prevCapabilities)); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java index bcdd08e95b..c75a6ccd5d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java @@ -1,12 +1,5 @@ package org.openecomp.sdc.be.components.merge.heat; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ArtifactBuilder; @@ -15,6 +8,13 @@ import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + public class HeatEnvArtifactsMergeBusinessLogicTest { private HeatEnvArtifactsMergeBusinessLogic testInstance; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java index 26b6782918..30801b0a4a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java @@ -1,14 +1,6 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.ListUtils; import org.junit.Before; import org.junit.Test; @@ -22,7 +14,14 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class ComponentInputsMergeBLTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java index b0124e4e44..98fceab7a8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java @@ -1,26 +1,24 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class InputsValuesMergingBusinessLogicTest { public static final String INPUT_DEFUALT_TYPE = "string"; @@ -133,54 +131,4 @@ public class InputsValuesMergingBusinessLogicTest { inputDef.setOwnerId("owner"); return inputDef; } - - private void addInstanceProperty(Resource resource, ComponentInstanceProperty prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesProperties(), prop, instanceId); - } - - private void addInstanceInput(Resource resource, ComponentInstanceInput prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesInputs(), prop, instanceId); - } - - private <T extends PropertyDataDefinition> void addInstancePropDefinition(Map<String, List<T>> propsDefinitions, T propDef, String instanceId) { - propsDefinitions.computeIfAbsent(instanceId, id -> new ArrayList<>()).add(propDef); - } - - private Resource createResourceWithInputs(String ... inputsIds) { - Resource resource = new Resource(); - List<InputDefinition> inputs = new ArrayList<>(); - for (String inputId : inputsIds) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setOwnerId("cs0008"); - inputDefinition.setUniqueId(inputId); - inputs.add(inputDefinition); - } - resource.setInputs(inputs); - return resource; - } - - - private ComponentInstanceProperty createGetInputComponentProperty(String ... declaredToInputId) { - ComponentInstanceProperty prevDeclaredProperty = new ComponentInstanceProperty(); - for (String inputId : declaredToInputId) { - addGetInputValueOnProp(inputId, prevDeclaredProperty); - } - - return prevDeclaredProperty; - } - - private void addGetInputValueOnProp(String declaredToInputId, PropertyDataDefinition declaredProperty) { - GetInputValueDataDefinition getInputDef = new GetInputValueDataDefinition(); - getInputDef.setInputId(declaredToInputId); - if (declaredProperty.getGetInputValues() == null) { - declaredProperty.setGetInputValues(new ArrayList<>()); - } - declaredProperty.getGetInputValues().add(getInputDef); - } - - private ComponentInstanceInput createGetInputComponentInstanceInput(String declaredToInputId) { - ComponentInstanceInput prevDeclaredProp = new ComponentInstanceInput(); - addGetInputValueOnProp(declaredToInputId, prevDeclaredProp); - return prevDeclaredProp; - } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java index be16bc3621..df3e0ddb68 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge.instance; -import static junit.framework.TestCase.assertEquals; - -import java.util.HashMap; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -14,6 +9,11 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; +import java.util.HashMap; +import java.util.Map; + +import static groovy.util.GroovyTestCase.assertEquals; + public class ComponentInstanceArtifactsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java new file mode 100644 index 0000000000..4fbb1ab5d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +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.exception.ResponseFormat; + +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabiliteisPropertiesMergeTest { + + @InjectMocks + private ComponentInstanceCapabiliteisPropertiesMerge testInstance; + + @Mock + private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; + + @Mock + private ComponentsUtils componentsUtils; + + private DataForMergeHolder mergeHolder; + + private Resource origInstanceNode; + private List<CapabilityDefinition> origInstanceCapabilities; + + @Before + public void setUp() throws Exception { + origInstanceNode = new Resource(); + origInstanceCapabilities = Collections.emptyList(); + mergeHolder = new DataForMergeHolder(); + mergeHolder.setOrigInstanceNode(origInstanceNode); + mergeHolder.setOrigInstanceCapabilities(origInstanceCapabilities); + } + + @Test + public void mergeDataAfterCreate() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.OK); + Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isLeft()); + } + + @Test + public void mergeDataAfterCreate_error() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat()); + Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isRight()); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java new file mode 100644 index 0000000000..d73459c1b1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java @@ -0,0 +1,275 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.merge.capability.SimpleCapabilityResolver; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstancePropertyBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +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.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabilitiesMergeBLTest { + + private static final String INSTANCE1 = "inst1"; + private static final String INSTANCE2 = "inst2"; + + private ComponentCapabilitiesPropertiesMergeBL testInstance; + private ComponentsUtils componentsUtils; + @Mock + private SimpleCapabilityResolver capabilityResolver; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; + @Captor + private ArgumentCaptor<List<ComponentInstanceProperty>> prevCapPropertiesCaptor; + @Captor + private ArgumentCaptor<List<ComponentInstanceProperty>> currCapPropertiesCaptor; + @Captor + private ArgumentCaptor<ComponentParametersView> getCurrResourceFilterCapture; + + private CapabilityDefinition oldCap; + private CapabilityDefinition oldCap2; + private CapabilityDefinition newCap; + private CapabilityDefinition newCap2; + + private ComponentParametersView getCapabilitiesPropsFilter; + + protected static ConfigurationManager configurationManager = null; + + @Before + public void setUp() throws Exception { + oldCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .build(); + + oldCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop3").build()) + .build(); + + getCapabilitiesPropsFilter = new ComponentParametersView(); + getCapabilitiesPropsFilter.disableAll(); + getCapabilitiesPropsFilter.setIgnoreComponentInstances(false); + getCapabilitiesPropsFilter.setIgnoreCapabilities(false); + getCapabilitiesPropsFilter.setIgnoreCapabiltyProperties(false); + + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + testInstance = new ComponentCapabilitiesPropertiesMergeBL(dataDefinitionsValuesMergingBusinessLogic, toscaOperationFacade, componentsUtils, capabilityResolver); + } + + @Test + public void mergeCapabilityProperties_singleCapability() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), getCurrResourceFilterCapture.capture())).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + assertThat(getCurrResourceFilterCapture.getValue()).isEqualToComparingFieldByField(getCapabilitiesPropsFilter); + } + + @Test + public void mergeCapabilityProperties_failToGetResourceWithPropsCapabilities() { + Resource currResource = new ResourceBuilder().setUniqueId("rid").build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + ActionStatus actionStatus = testInstance.mergeComponents(new Resource(), currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + @Test + public void mergeCapabilityProperties_multipleCapabilitiesToMerge() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance prevInst2 = new ComponentInstanceBuilder().addCapability(oldCap2).setName(oldCap2.getOwnerName()).build(); + + ComponentInstance currInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + ComponentInstance currInst2 = new ComponentInstanceBuilder().addCapability(newCap2).setName(newCap2.getOwnerName()).build(); + + Resource currResource = new ResourceBuilder().addComponentInstance(currInst1).addComponentInstance(currInst2).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).addComponentInstance(prevInst2).build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(currResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, currInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst2, currInst2)).thenReturn(ImmutableMap.of(oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeCapabilityProperties_noNewCapabilitiesResolved() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().setName(oldCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_noPrevCapabilitiesToMerge() { + Resource newResource = new Resource(); + Resource prevResource = new Resource(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + verifyNoMoreInteractions(toscaOperationFacade); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_failedToUpdateComponent() { + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + Resource newResource = new Resource(); + Resource prevResource = new ResourceBuilder().addComponentInstance(inst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + //////////////////////////// + @Test + public void mergeInstanceCapabilityProperties_singleCap() { + List<CapabilityDefinition> previousInstanceCapabilities = Collections.singletonList(oldCap); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, newCap.getOwnerId())).thenReturn(StorageOperationStatus.OK); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap)); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + } + + @Test + public void mergeInstanceCapabilityProperties() { + List<CapabilityDefinition> previousInstanceCapabilities = Arrays.asList(oldCap, oldCap2); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).addCapability(newCap2).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap, oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeInstanceCapabilityProperties_emptyCapabilitiesList() { + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(new Resource(), new Resource(), "instanceId", Collections.emptyList()); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade, dataDefinitionsValuesMergingBusinessLogic, capabilityResolver); + } + + @Test + public void mergeInstanceCapabilityProperties_failedToUpdateComponent() { + Resource container = new Resource(); + Resource resource = new Resource(); + List<CapabilityDefinition> capList = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, capList)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, capList); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void mergeInstanceCapabilityProperties_noNewCapabilitiesFound() { + Resource container = new Resource(); + Resource resource = new Resource(); + List<CapabilityDefinition> prevCapabilities = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, prevCapabilities)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, prevCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java index 2101ea49ab..115825733e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -26,7 +19,13 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Mockito.when; public class ComponentInstanceHeatEnvMergeTest { @@ -67,7 +66,7 @@ public class ComponentInstanceHeatEnvMergeTest { for (ArtifactDefinition mergedArtifact : mergedArtifacts) { Map<String, Object> json = new HashMap<>(); when(artifactsBusinessLogicMock.buildJsonForUpdateArtifact(mergedArtifact, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(json); - ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update); + ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE); when(artifactsBusinessLogicMock.updateResourceInstanceArtifactNoContent(Mockito.eq(instanceId), Mockito.eq(resource), Mockito.eq(USER), Mockito.eq(json), Mockito.refEq(artifactUpdateOperation), diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java index bc3efe423d..630a43ef2d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -29,7 +22,13 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceMergeDataBusinessLogicTest { @@ -112,4 +111,6 @@ public class ComponentInstanceMergeDataBusinessLogicTest { assertFalse(value.isIgnoreArtifacts()); } + + }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java index cb3d506bfc..d946206f23 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java @@ -1,16 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyListOf; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -19,8 +9,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -37,7 +25,16 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropsAndInputsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java new file mode 100644 index 0000000000..08c8456064 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java @@ -0,0 +1,378 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceRelationMergeTest { + private ComponentInstanceRelationMerge compInstanceRelationMerge; + @Mock + private DataForMergeHolder dataHolder; + private Component containerComponent; + private Component updatedContainerComponent; + private ComponentInstance currentResourceInstance; + + private RequirementCapabilityRelDef requirementDef1; + private RequirementCapabilityRelDef requirementDef2; + private RequirementCapabilityRelDef capabilityDef1; + private RequirementCapabilityRelDef capabilityDef2; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private User user; + + @Captor + ArgumentCaptor<VfRelationsMergeInfo> argumentCaptor; + + + @Before + public void startUp() { + compInstanceRelationMerge = new ComponentInstanceRelationMerge(); + compInstanceRelationMerge.setToscaOperationFacade(toscaOperationFacade); + + MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + compInstanceRelationMerge.setMergeInstanceUtils(mergeInstanceUtils); + + containerComponent = new Service(); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + + requirementDef1 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF2.VFI_1", "SRV1.VF1.VFC_1.VFCI_1", "Requirement1"); + resourceInstancesRelations.add(requirementDef1); + requirementDef2 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF3.VFI_1", "SRV1.VF1.VFC_2.VFCI_2", "Requirement2"); + resourceInstancesRelations.add(requirementDef2); + + + capabilityDef1 = createCapabilityDef("SRV1.VF4.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_3.VFCI_3", "Capability3"); + resourceInstancesRelations.add(capabilityDef1); + capabilityDef2 = createCapabilityDef("SRV1.VF5.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_4.VFCI_1", "Capability4"); + resourceInstancesRelations.add(capabilityDef2); + + containerComponent.setComponentInstancesRelations(resourceInstancesRelations ); + + currentResourceInstance = new ComponentInstance(); + currentResourceInstance.setUniqueId("SRV1.VF1.VFI_1"); + currentResourceInstance.setComponentUid("SRV1.VF1"); + currentResourceInstance.setIsProxy(false); + + updatedContainerComponent = new Service(); + updatedContainerComponent.setUniqueId("123123123123123123"); + } + + @Test + public void testSaveDataBeforeMerge() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + compInstanceRelationMerge.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, vf); + + verify(dataHolder).setVfRelationsInfo(argumentCaptor.capture()); + VfRelationsMergeInfo relationsMergeInfo = argumentCaptor.getValue(); + List<RelationMergeInfo> fromRelationsMergeInfo = relationsMergeInfo.getFromRelationsInfo(); + List<RelationMergeInfo> toRelationsMergeInfo = relationsMergeInfo.getToRelationsInfo(); + + assertNotNull("Expected not null list of relations merge info", fromRelationsMergeInfo); + assertNotNull("Expected not null list of relations merge info", toRelationsMergeInfo); + + assertEquals("Expected 2 elements", 2, fromRelationsMergeInfo.size()); + assertEquals("Expected 1 elements", 1, toRelationsMergeInfo.size()); + } + + @Test + public void testMergeDataAfterCreate_NoSavedData() { + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertNull("Expected no relations", relations); + } + + @Test + public void testMergeDataAfterCreate() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either<Component, StorageOperationStatus> eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>(); + List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_1", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_1", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + + @Test + public void testMergeDataAfterCreate_OwnerChanged() { + Resource vf = new Resource(); + + List<ComponentInstance> vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_2", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_2", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either<Component, StorageOperationStatus> eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>(); + List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_2", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_2", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + /** + * @param vfId + * @param vfiUniqueId + * @return + */ + private ComponentInstance createVfi(String vfId, String vfiUniqueId) { + ComponentInstance vfi = new ComponentInstance(); + vfi.setUniqueId(vfiUniqueId); + vfi.setComponentUid(vfId); + + Resource vf = new Resource(); + vf.setUniqueId(vfId); + return vfi; + } + + private ComponentInstance createVfci(String name, String uniqueId, String componentUid, boolean foundVfc) { + ComponentInstance compInst = new ComponentInstance(); + compInst.setName(name); + compInst.setUniqueId(uniqueId); + compInst.setComponentUid(componentUid); + + if(foundVfc) { + createVfc(componentUid); + } + else { + failLoadVfc(componentUid); + } + return compInst; + } + + private void failLoadVfc(String uid) { + Either<Component, StorageOperationStatus> eitherVFC = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + } + + private Component createVfc(String uid) { + Resource vfc = new Resource(); + vfc.setUniqueId(uid); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>();; + IntStream.range(0, 5).forEach(i -> { + + List<CapabilityDefinition> capList = new LinkedList<>(); + capList.add(null); + CapabilityDefinition capDef = new CapabilityDefinition(); + capDef.setName("CapabilityName" + i); + capDef.setUniqueId("Capability" + i); + capDef.setType("CapabilityType" + i); + capList.add(capDef); + capabilities.put("Key" + i, capList); + + List<RequirementDefinition> reqList = new LinkedList<>(); + reqList.add(null); + RequirementDefinition reqDef = new RequirementDefinition(); + reqDef.setName("RequirementName" + i); + reqDef.setUniqueId("Requirement" + i); + reqDef.setCapability("CapabilityType" + i); + reqList.add(reqDef); + requirements.put("Key" + i, reqList); + + }); + vfc.setCapabilities(capabilities ); + vfc.setRequirements(requirements); + + Either<Component, StorageOperationStatus> eitherVFC = Either.left(vfc); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + + return vfc; + } + + private RequirementCapabilityRelDef createRequirementCapabilityDef(String fromNode, String toNode) { + RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef(); + + reqCapDef.setFromNode(fromNode); + reqCapDef.setToNode(toNode); + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + relationships.add(capabilityRequirementRelationship); + reqCapDef.setRelationships(relationships); + + return reqCapDef; + } + + private RequirementCapabilityRelDef createRequirementDef(String fromNode, String toNode, String ownerId, String requirementUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setRequirementOwnerId(ownerId); + relationshipInfo.setRequirementUid(requirementUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + + + return reqCapDef; + } + + private RequirementCapabilityRelDef createCapabilityDef(String fromNode, String toNode, String ownerId, String capabilityUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setCapabilityOwnerId(ownerId); + relationshipInfo.setCapabilityUid(capabilityUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + return reqCapDef; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java new file mode 100644 index 0000000000..65ab3ec121 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.components.merge.path; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceForwardingPathMerge; +import org.openecomp.sdc.be.components.path.BaseForwardingPathVersionChangeTest; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Set; + +import static groovy.util.GroovyTestCase.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.when; + +public class ComponentInstanceForwardingPathMergeTest extends BaseForwardingPathVersionChangeTest { + + @InjectMocks + private ComponentInstanceForwardingPathMerge testInstance; + + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + private User user; + + @Before + public void setUpData() { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId("44"); + user.setRole(UserRoleEnum.ADMIN.getName()); + } + + @Test + public void testIgnoreMergeSinceItIsNotService() { + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, newNodeAC, "3344"); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(newNodeAC, componentResponseFormatEither.left().value()); + } + + @Test + public void mergeShouldDelete() { + Set<String> forwardingPathNamesToDeleteOnComponentInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeACI.getUniqueId()); + nodeACI.getCapabilities().clear(); + newNodeAC.getCapabilities().clear(); + when(serviceBusinessLogic.deleteForwardingPaths(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(forwardingPathNamesToDeleteOnComponentInstanceDeletion)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(0, ((Service) componentResponseFormatEither.left().value()).getForwardingPaths().size()); + } + + @Test + public void mergeShouldUpdate() { + when(serviceBusinessLogic.updateForwardingPath(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(service)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + Either<Component, ResponseFormat> componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java index 0a858c9a29..bbb2dd6895 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceInputsMergeBL; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -23,7 +17,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceInputsMergeBLTest { @@ -41,7 +41,8 @@ public class ComponentInstanceInputsMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -71,22 +72,22 @@ public class ComponentInstanceInputsMergeBLTest { @Test public void mergeInstancesInputs() throws Exception { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @Test - public void mergeInstancesInputs_failure() throws Exception { + public void mergeInstancesInputs_failure() { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } @Test - public void mergeInstanceProps() throws Exception { + public void mergeInstanceProps() { List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) @@ -97,7 +98,7 @@ public class ComponentInstanceInputsMergeBLTest { } @Test - public void mergeInstanceProps_failure() throws Exception { + public void mergeInstanceProps_failure() { List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java index 7948ab8a3d..6013009106 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -21,7 +15,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropertiesMergeBLTest { @@ -40,7 +40,8 @@ public class ComponentInstancePropertiesMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -64,7 +65,7 @@ public class ComponentInstancePropertiesMergeBLTest { public void mergeInstancesPropsAndInputs_mergeInstanceProps() throws Exception { when(toscaOperationFacade.updateComponentInstancePropsToComponent(newResource.getComponentInstancesProperties(), newResource.getUniqueId())) .thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @@ -75,7 +76,7 @@ public class ComponentInstancePropertiesMergeBLTest { .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java index 8669a781b4..3b079d30d5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java @@ -1,21 +1,22 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionAbstractBuilder; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.verify; + public class DataDefinitionsValuesMergingBusinessLogicTest { private static final String DEFAULT_PROP_TYPE = "string"; @@ -110,9 +111,10 @@ public class DataDefinitionsValuesMergingBusinessLogicTest { } private PropertyDataDefinition createGetInputPropertyDataDefinition(String name, String ... inputsNames) { - PropertyDataDefinitionBuilder propertyBuilder = new PropertyDataDefinitionBuilder() + PropertyDataDefinitionAbstractBuilder propertyBuilder = new PropertyDataDefinitionBuilder() .setName(name) .setType(DEFAULT_PROP_TYPE); + for (String inputName : inputsNames) { propertyBuilder.addGetInputValue(inputName); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java index 6faee487f4..5c23ec0e8c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java @@ -1,17 +1,6 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -25,7 +14,17 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import fj.data.Either; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class PropertyDataValueMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java index 8e7949f108..0590c7e500 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java @@ -1,82 +1,63 @@ package org.openecomp.sdc.be.components.merge.resource; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; - import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) public class ResourceDataMergeBusinessLogicTest { @InjectMocks private ResourceDataMergeBusinessLogic testInstance; @Mock - private ComponentInstanceInputsMergeBL instanceInputsValueMergeBLMock; + private ComponentsMergeCommand commandA; @Mock - private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBLMock; + private ComponentsMergeCommand commandB; @Mock - private ComponentInputsMergeBL inputsValueMergeBLMock; + private ComponentsMergeCommand commandC; @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + testInstance = new ResourceDataMergeBusinessLogic(Arrays.asList(commandA, commandB, commandC)); } @Test - public void mergeResourceInputs_allMergeClassesAreCalled() throws Exception { + public void mergeResources_allMergeClassesAreCalled() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.OK); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandB.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandC.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.OK, actionStatus); } @Test - public void mergeResourceInputs_failToMergeProperties_dontCallOtherMergeMethods() throws Exception { + public void mergeResources_mergeCommandFailed_dontCallOtherMergeMethods() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(instanceInputsValueMergeBLMock, inputsValueMergeBLMock); + verify(commandA).description(); + verifyZeroInteractions(commandB, commandC); } - @Test - public void mergeResourceInputs_failToMergeInstanceInputs_dontCallOtherMergeMethods() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(inputsValueMergeBLMock); - } - - @Test - public void mergeResourceInputs_failedToMergeInputs() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java new file mode 100644 index 0000000000..3131c4987c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java @@ -0,0 +1,328 @@ +package org.openecomp.sdc.be.components.merge.utils; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class MergeInstanceUtilsTest { + private MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Before + public void startUp() { + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent() { + Component container = new Service(); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci1 = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci1); + List<ComponentInstance> vfciList = Arrays.asList(vfci1); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfi1 = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + container.setComponentInstances(Arrays.asList(vfi1)); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + List<ComponentInstance> vfciList2 = Arrays.asList(vfci1); + vfNew.setComponentInstances(vfciList2); + + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfi1.getComponentUid())).thenReturn(eitherComponent); + + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, vfOld, "SRV1.VF2.VFI_1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + assertEquals("SRV1.VF1.VFI_1.VFC1.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent_Proxy() { + Resource container = new Resource(); + container.setComponentType(ComponentTypeEnum.RESOURCE); + container.setResourceType(ResourceTypeEnum.VF); + + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List<ComponentInstance> vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + container.setComponentInstances(Arrays.asList(proxyVfciNew)); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, serviceOld, "SRV1.PROXY_VFC_NEW.VFCI1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstanceComponentInstance() { + ComponentInstance oldInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(oldInstance); + + ComponentInstance newInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC2.VFCI_1" ,"SRV1.VF1.VFI_1.VFC2", false); + createVfc(newInstance); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, newInstance); + assertEquals("SRV1.VF1.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstComponentInst_Proxy() { + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List<ComponentInstance> vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + ComponentInstance proxyVfciOld = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + proxyVfciOld.setSourceModelUid("SRV_PROXY"); + Resource proxyVfcOld = new Resource(); + proxyVfcOld.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcOld.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent2 = Either.left(serviceOld); + when(toscaOperationFacade.getToscaElement(proxyVfciOld.getSourceModelUid())).thenReturn(eitherComponent2); + + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(proxyVfciOld, proxyVfciNew); + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + + @Test + public void testConvertToVfciNameMap() { + ComponentInstance componentInstance1 = new ComponentInstance(); + componentInstance1.setName("ComponentInstance1"); + + ComponentInstance componentInstance2 = new ComponentInstance(); + componentInstance2.setName("ComponentInstance2"); + + List<ComponentInstance> componentInstances = Arrays.asList(componentInstance1, componentInstance2); + Map<String, ComponentInstance> mapResult = mergeInstanceUtils.convertToVfciNameMap(componentInstances); + + assertEquals(2, mapResult.size()); + assertEquals(componentInstance1, mapResult.get("ComponentInstance1")); + assertEquals(componentInstance2, mapResult.get("ComponentInstance2")); + } + + @Test + public void testGetVfcInstances_NullComponentInstance() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadActualComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + componentInstance.setSourceModelUid("SRV_PROXY"); + + Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getSourceModelUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + + @Test + public void testGetVfcInstancesAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + + createVfc(componentInstance); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(1, vfcInstances.size()); + assertEquals(componentInstance, vfcInstances.get(0)); + } + + + @Test + public void testGetVfcInstancesNonAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Resource vf = new Resource(); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vf); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci); + List<ComponentInstance> vfciList = Arrays.asList(vfci); + + vf.setComponentInstances(vfciList); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(vfciList, vfcInstances); + } + + @Test + public void testGetVfcInstances_ComponentNullI_nstanceComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, new Resource()); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstance_NullComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(new ComponentInstance(), null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_NullComponentInstance_NullComponent() { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, null); + + assertTrue(vfcInstances.isEmpty()); + } + + + /** + * @param uniqueId + * @param componentUid + * @param isProxy + * @return + */ + private ComponentInstance createComponentInstance(String uniqueId, String componentUid, boolean isProxy) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setUniqueId(uniqueId); + componentInstance.setComponentUid(componentUid); + componentInstance.setIsProxy(isProxy); + return componentInstance; + } + + /** + * @param componentInstance + */ + private void createVfc(ComponentInstance componentInstance) { + Resource vfc = new Resource(); + Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfc); + vfc.setComponentType(ComponentTypeEnum.RESOURCE); + vfc.setResourceType(ResourceTypeEnum.VFC); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java new file mode 100644 index 0000000000..44f87bb352 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java @@ -0,0 +1,208 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import fj.data.Either; +import org.junit.Before; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.path.beans.TitanGraphTestSetup; +import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +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.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class BaseForwardingPathTest extends BeConfDependentTest implements ForwardingPathTestUtils { + + protected User user; + protected ForwardingPathDataDefinition forwardingPathDataDefinition; + + @Autowired + protected TitanGraphClient titanGraphClient; + + @Autowired + protected CapabiltyRequirementConvertor capabiltyRequirementConvertor; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @Autowired + protected ServiceBusinessLogic bl; + + @Autowired + protected IElementOperation elementDao; + + @Autowired + protected ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @javax.annotation.Resource + protected TitanDao titanDao; + + @Before + public void initTitan() { + TitanGraphTestSetup.createGraph(titanGraphClient.getGraph().left().value()); + categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(CATEGORY_NAME); + } + + @Before + public void initUser() { + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + } + + + protected CategoryDefinition categoryDefinition; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static final String CATEGORY_NAME = "cat_name"; + protected static final String FORWARDING_PATH_ID = "forwarding_pathId"; + protected static final String HTTP_PROTOCOL = "http"; + + + protected Resource setupGenericServiceMock() { + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected void initGraph() { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.abstract.nodes.service"); + + GraphTestUtils.createServiceVertex(titanDao, props); + + GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.PNF); + resourceVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "0.1"); + Either<GraphVertex, TitanOperationStatus> vertexTitanOperationStatusEither = titanDao.updateVertex(resourceVertex); + assertTrue(vertexTitanOperationStatusEither.isLeft()); + } + + protected Service createTestService() { + createCategory(); + createServiceCategory(CATEGORY_NAME); + initGraph(); + Service service = new Service(); + service.setName("ForwardingPathTestingService"); + service.setDescription("Just a comment."); + service.setTags(Lists.newArrayList(service.getName(), service.getComponentType().getValue() + service.getName() + "2")); + service.setContactId("as123y"); + service.setIcon("MyIcon"); + service.setProjectCode("414155"); + ArrayList<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition cd = new CategoryDefinition(); + cd.setName(CATEGORY_NAME); + cd.setNormalizedName("abcde"); + categories.add(cd); + service.setCategories(categories); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_APPROVED); + return service; + } + + protected void createCategory() { + Either<CategoryDefinition, ActionStatus> category = elementDao.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory); + assertTrue("Failed to create category", category.isLeft()); + } + + protected void createServiceCategory(String categoryName) { + GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); + + assertTrue(catRes.isLeft()); + } + + protected Service initForwardPath() { + ForwardingPathDataDefinition forwardingPathDataDefinition = createMockPath(); + Service service = new Service(); + service.setUniqueId(FORWARDING_PATH_ID); + assertEquals(null, service.addForwardingPath(forwardingPathDataDefinition)); + return service; + } + + protected ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null) { + return forwardingPathDataDefinition; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol(HTTP_PROTOCOL); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode", "toNode", "333", "444", "2222", "5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode", "toNode2", "4444", "44444", "4", "44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } + + protected Service createService() { + Either<Service, ResponseFormat> serviceCreateResult = bl.createService(createTestService(), user); + assertTrue("Failed to create service", serviceCreateResult.isLeft()); + Service service = serviceCreateResult.left().value(); +// ComponentInstance componentInstance = new ComponentInstance(); +// componentInstance.setName("Test1"); +// componentInstance.setNormalizedName("Test1"); +// componentInstance.setUniqueId("Test1"); +// componentInstance.setInputValueCounter(1); +// componentInstance.setAttributeValueCounter(1); +// componentInstance.setIcon("network"); +// componentInstance.setComponentVersion("1.0"); +// componentInstance.setIsProxy(true); +// componentInstance.setComponentUid(service.getUniqueId()); +// componentInstance.setPropertyValueCounter(1); +// componentInstance.setPosX("333"); +// componentInstance.setPosY("333"); +// componentInstance.setOriginType(OriginTypeEnum.VF); +// +// Either<ComponentInstance, ResponseFormat> instanceResult = serviceComponentInstanceBusinessLogic.createComponentInstance("services", service.getUniqueId(), user.getUserId(), componentInstance); +// assertTrue("Failed to create instance", instanceResult.isLeft()); + return service; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java new file mode 100644 index 0000000000..0e56680728 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import org.junit.Before; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class BaseForwardingPathVersionChangeTest { + protected Service service; + protected ComponentInstance nodeACI; + protected ComponentInstance newNodeACI; + protected Component newNodeAC; + protected Component newNodeWithoutCapability; + protected DataForMergeHolder dataHolder; + protected static final String nodeA = "nodeA"; + protected static final String NODE_A_FORWARDER_CAPABILITY = "nodeA_FORWARDER_CAPABILITY"; + protected static final String nodeB = "nodeB"; + protected static final String newNodeA = "newNodeA"; + protected static final String fpName = "fpName"; + protected static final String FPId = "1122"; + + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, NODE_A_FORWARDER_CAPABILITY, "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put(FPId, forwardingPath); + service.setForwardingPaths(forwardingPaths); + nodeACI = new ComponentInstance(); + initComponentInstance(nodeACI, nodeA); + newNodeACI = new ComponentInstance(); + initComponentInstance(newNodeACI, newNodeA); + newNodeAC = new Resource(); + newNodeWithoutCapability=new Resource(); + initComponent(newNodeAC, newNodeA); + service.setComponentInstances(Lists.newArrayList(newNodeACI)); + initComponentWithoutForwarder(newNodeWithoutCapability,"newNodeC"); + service.setComponentInstances(Lists.newArrayList(nodeACI)); + + dataHolder = new DataForMergeHolder(); + dataHolder.setOrigComponentInstId(nodeA); + } + + private void initComponent(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + + private void initComponentWithoutForwarder(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilitesWithoutForwarder(); + component.setCapabilities(capabilities); + } + + private HashMap<String, List<CapabilityDefinition>> initCapabilites() { + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition forwarder = new CapabilityDefinition(); + forwarder.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + forwarder.setUniqueId(NODE_A_FORWARDER_CAPABILITY); + capabilities.put("bla bla", Arrays.asList(forwarder)); + return capabilities; + } + + private HashMap<String, List<CapabilityDefinition>> initCapabilitesWithoutForwarder() { + HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setType("tosca.capabilities.Node"); + capabilityDefinition.setUniqueId("tosca capability"); + capabilities.put("bla bla", Arrays.asList(capabilityDefinition)); + return capabilities; + } + + private void initComponentInstance(ComponentInstance component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java new file mode 100644 index 0000000000..03bbc31aef --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java @@ -0,0 +1,107 @@ + +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathBussinessLogicTest extends BaseForwardingPathTest { + + + @Test + public void shouldFailToUpdateForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either<Service, ResponseFormat> serviceResponseFormatEither = bl.updateForwardingPath(FORWARDING_PATH_ID, service, user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldFailToDeleteForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either<Set<String>, ResponseFormat> serviceResponseFormatEither = bl.deleteForwardingPaths("delete_forward_test", Sets.newHashSet(FORWARDING_PATH_ID), user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldSucceedCreateAndDeleteForwardingPath() { + Service createdService = createService(); + Service service = initForwardPath(); + assertNotNull(service); + Either<Service, ResponseFormat> serviceResponseFormatEither = bl.createForwardingPath(createdService.getUniqueId(), service, user, true); + assertEquals(true, serviceResponseFormatEither.isLeft()); + Map<String, ForwardingPathDataDefinition> forwardingPathsMap = serviceResponseFormatEither.left().value().getForwardingPaths(); + Set<String> pathIds = forwardingPathsMap.keySet(); + assertEquals(1, pathIds.size()); + String toscaResourceName = forwardingPathsMap.values().iterator().next().getToscaResourceName(); + + // should return the created path + Either<UiComponentDataTransfer, ResponseFormat> uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map<String, ForwardingPathDataDefinition> forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths.keySet().equals(pathIds)); + Map<String, ForwardingPathDataDefinition> updatedForwardingPaths = new HashMap<>(forwardingPaths); + String newProtocol = "https"; + ForwardingPathDataDefinition forwardingPathDataDefinition = updatedForwardingPaths.values().stream().findAny().get(); + assertEquals(forwardingPathDataDefinition.getProtocol(), HTTP_PROTOCOL); + assertEquals(toscaResourceName, forwardingPathDataDefinition.getToscaResourceName()); + ForwardingPathDataDefinition forwardingPathDataDefinitionUpdate = updatedForwardingPaths.values().iterator().next(); + // updated values + forwardingPathDataDefinitionUpdate.setProtocol(newProtocol); + forwardingPathDataDefinitionUpdate.setPathElements(new ListDataDefinition<>()); + + // should update value + service.getForwardingPaths().clear(); + service.getForwardingPaths().put(forwardingPathDataDefinitionUpdate.getUniqueId(), forwardingPathDataDefinitionUpdate); + serviceResponseFormatEither = bl.updateForwardingPath(createdService.getUniqueId(), service, user, true); + assertTrue(serviceResponseFormatEither.isLeft()); + + // make sure changes were applied + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map<String, ForwardingPathDataDefinition> forwardingPathsUpdated = uiServiceDataTransfer.getForwardingPaths(); + ForwardingPathDataDefinition updatedData = forwardingPathsUpdated.values().iterator().next(); + assertEquals(newProtocol, updatedData.getProtocol()); + assertTrue(updatedData.getPathElements().isEmpty()); + + Service createdData = serviceResponseFormatEither.left().value(); + Set<String> paths = createdData.getForwardingPaths().keySet(); + Either<Set<String>, ResponseFormat> setResponseFormatEither = bl.deleteForwardingPaths(createdService.getUniqueId(), paths, user, true); + assertEquals(true, setResponseFormatEither.isLeft()); + + // nothing to return now + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.COMPONENT_INSTANCES.getValue(),ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths == null || forwardingPaths.isEmpty()); + + } + + + + +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java new file mode 100644 index 0000000000..5af94d7938 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.components.path; + +import org.javatuples.Pair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +public class ForwardingPathChangeVersionTest extends BaseForwardingPathVersionChangeTest { + + + @Test + public void updateForwardingPath() { + Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map<String, ForwardingPathDataDefinition> updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(1, updated.size()); + assertEquals(newNodeA, updated.values().iterator().next().getPathElements().getListToscaDataDefinition().get(0).getFromNode()); + Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(0, deleted.size()); + } + + @Test + public void deleteForwardingPath(){ + newNodeAC.setCapabilities(new HashMap<>()); + Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map<String, ForwardingPathDataDefinition> updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(0, updated.size()); + + Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(1, deleted.size()); + assertEquals(FPId, deleted.keySet().stream().findAny().get()); + } + + @Test + public void fetchPathsToBeDeletedZeroPaths(){ + Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeAC); + assertEquals(0,data.size()); + } + + @Test + public void fetchPathsToBeDeleted(){ + Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeWithoutCapability); + assertEquals(1,data.size()); + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java new file mode 100644 index 0000000000..e5de493cb1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ForwardingPathDeleteCITest { + + private Service service; + private static final String nodeA = "nodeA"; + private static final String nodeB = "nodeB"; + private static final String fpName = "fpName"; + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, "nodeAcpType", "nodeBcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeB, "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + } + + + @Test + public void getListToDelete() { + + Set<String> forwardingPathNamesToDeleteOnComponenetInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeA); + assertEquals(1, forwardingPathNamesToDeleteOnComponenetInstanceDeletion.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + Set<String> forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeB); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(1, forwardingPathNamesToDeleteOnCIDelete.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, "Does not exist"); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(0, forwardingPathNamesToDeleteOnCIDelete.size()); + assertFalse(forwardingPathNamesToDeleteOnCIDelete.contains(fpName)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java new file mode 100644 index 0000000000..9ab9ffd788 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.components.path; + +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; + +public interface ForwardingPathTestUtils { + + default ForwardingPathDataDefinition createPath(String pathName, String protocol, String ports, String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber(ports); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java new file mode 100644 index 0000000000..e7100a4a7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java @@ -0,0 +1,186 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDER; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PORTS_RANGE; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PROTOCOL; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.addForwardingPaths; + +/** + * @author KATYR, ORENK + * @since November 19, 2017 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathToscaUtilTest extends BaseForwardingPathTest { + + private static final String NODE_NAME_1 = "nodeA-name"; + private static final String NODE_NAME_2 = "nodeB-name"; + private static final String PATH_1_PROTOCOL = "protocol-path1"; + private static final String PATH_1_DESC = "path1-desc"; + private static final String PATH_1_PORTS = "8585"; + private static final String PATH_1_NAME = "pathName1"; + private Service service; + private Map<String, Component> originComponents = new HashMap<>(); + private static final String NODE_ID_1 = "nodeA-id"; + private static final String NODE_ID_2 = "nodeB-id"; + private static final String FORWARDING_PATH_TOSCA_TYPE = "org.openecomp.nodes.ForwardingPath"; + + + @Before + public void setUpForwardingPath() { + service = initForwardPath(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.add(generateComponentInstance(NODE_NAME_1, NODE_ID_1)); + componentInstances.add(generateComponentInstance(NODE_NAME_2, NODE_ID_2)); + service.setComponentInstances(componentInstances); + } + + private ComponentInstance generateComponentInstance(String name, String uuid) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setName(name); + componentInstance.setUniqueId(uuid); + componentInstance.setComponentUid(uuid); + Map<String, List<CapabilityDefinition>> capabiltiesMap = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setMinOccurrences(Integer.toString(1)); + capabilityDefinition.setMaxOccurrences(Integer.toString(100)); + capabilityDefinition.setType(ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME); + capabilityDefinition.setName(name); + capabilityDefinition.setUniqueId(name); + capabilityDefinition.setPath(Arrays.asList("Just", "something", "to", "read")); + capabiltiesMap.put(capabilityDefinition.getName(), + Collections.singletonList(capabilityDefinition)); + componentInstance.setCapabilities(capabiltiesMap); + Resource resource = new Resource(); + resource.setToscaResourceName("test"); + originComponents.put(uuid, resource); + return componentInstance; + } + + + @Test + public void singleElementPath() { + createPathSingleElement(); + Map<String, ToscaNodeTemplate> nodeTemplatesRes = new HashMap<>(); + + Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes = new HashMap<>(); + ToscaNodeTemplate pathEntry = new ToscaNodeTemplate(); + pathEntry.setType(FORWARDING_PATH_TOSCA_TYPE); + Map<String, Object> expectedProps = new HashMap<>(); + expectedProps.put(PORTS_RANGE, Collections.singletonList(PATH_1_PORTS)); + expectedProps.put(PROTOCOL, PATH_1_PROTOCOL); + pathEntry.setProperties(expectedProps); + List<Map<String, ToscaTemplateRequirement>> requirements = new ArrayList<>(); + ToscaTemplateRequirement firstEntryReq = new ToscaTemplateRequirement(); + ToscaTemplateRequirement secondEntryReq = new ToscaTemplateRequirement(); + + firstEntryReq.setCapability("null." + NODE_NAME_1); + secondEntryReq.setCapability("null." + NODE_NAME_2); + + firstEntryReq.setNode(NODE_NAME_1); + secondEntryReq.setNode(NODE_NAME_2); + + firstEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + secondEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + + Map<String, ToscaTemplateRequirement> entryMap1 = new HashMap<>(); + Map<String, ToscaTemplateRequirement> entryMap2 = new HashMap<>(); + + entryMap1.put(FORWARDER, firstEntryReq); + entryMap2.put(FORWARDER, secondEntryReq); + + requirements.add(entryMap1); + requirements.add(entryMap2); + + pathEntry.setRequirements(requirements); + expectedNodeTemplatesRes.put(PATH_1_NAME, pathEntry); + addForwardingPaths(service, nodeTemplatesRes, capabiltyRequirementConvertor, originComponents, + toscaOperationFacade); + + assertEquals(2, nodeTemplatesRes.get(PATH_1_NAME).getRequirements().size()); + compareToscaPathEntry(expectedNodeTemplatesRes, nodeTemplatesRes); + } + + private void compareToscaPathEntry(Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes, + Map<String, ToscaNodeTemplate> nodeTemplatesRes) { + final ToscaNodeTemplate expectedTemplate = expectedNodeTemplatesRes.get(PATH_1_NAME); + final ToscaNodeTemplate actualTemplate = nodeTemplatesRes.get(PATH_1_NAME); + assertEquals(expectedTemplate.getProperties(), actualTemplate.getProperties()); + final int size = expectedTemplate.getRequirements().size(); + assertEquals(size, + actualTemplate.getRequirements().size()); + for (int i = 0; i < size; i++) { + compareToscaRequirement(expectedTemplate, actualTemplate, i); + } + } + + private void compareToscaRequirement(ToscaNodeTemplate expectedTemplate, + ToscaNodeTemplate actualTemplate, + int i) { + final ToscaTemplateRequirement actualRequirement = + actualTemplate.getRequirements().get(i).get(FORWARDER); + final ToscaTemplateRequirement expectedToscaRequirement = expectedTemplate + .getRequirements() + .get(i).get(FORWARDER); + assertEquals(actualRequirement.getCapability(), expectedToscaRequirement.getCapability()); + assertEquals(actualRequirement.getNode(), expectedToscaRequirement.getNode()); + } + + private void createPathSingleElement() { + ForwardingPathElementDataDefinition element1 = initElement(NODE_ID_1, NODE_ID_2, NODE_NAME_1, + NODE_NAME_2); + + ListDataDefinition<ForwardingPathElementDataDefinition> list = new ListDataDefinition<>(); + list.add(element1); + + + ForwardingPathDataDefinition path = new ForwardingPathDataDefinition(); + path.setDescription(PATH_1_DESC); + path.setProtocol(PATH_1_PROTOCOL); + path.setDestinationPortNumber(PATH_1_PORTS); + path.setToscaResourceName(FORWARDING_PATH_TOSCA_TYPE); + path.setPathElements(list); + path.setName(PATH_1_NAME); + + Map<String, ForwardingPathDataDefinition> paths = new HashMap<>(); + paths.put(PATH_1_NAME, path); + + service.setForwardingPaths(paths); + } + + private ForwardingPathElementDataDefinition initElement(String fromId, String toId, String + fromCP, String toCP) { + ForwardingPathElementDataDefinition element = new ForwardingPathElementDataDefinition(); + element.setFromCP(fromCP); + element.setFromNode(fromId); + element.setToCP(toCP); + element.setToNode(toId); + return element; + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java new file mode 100644 index 0000000000..fd9e25f475 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java @@ -0,0 +1,151 @@ +package org.openecomp.sdc.be.components.path; + + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; +import java.util.Set; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +public class ForwardingPathValidatorTest implements ForwardingPathTestUtils { + + ResponseFormatManager mock; + + private Service service = (Service) getToscaFullElement().left().value(); + + + @Mock + ToscaOperationFacade toscaOperationFacade; + @InjectMocks + ForwardingPathValidationUtilTest test = new ForwardingPathValidationUtilTest(); + + private static final String SERVICE_ID = "serviceid1"; + + + + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + mock = Mockito.mock(ResponseFormatManager.class); + when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(mock.getResponseFormat(any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any(), any())).thenReturn(new ResponseFormat()); + + } + + @Test + public void testValidForwardingPathName(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName", "http", "8285", "pathName"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isLeft()); + } + + @Test + public void testEmptyForwardingPathName(){ + Collection<ForwardingPathDataDefinition> paths = createData("", "protocol", "8285", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + } + + @Test + public void testLongForwardingPathName(){ + String pathName = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData(pathName, + "http", "port", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testUniqueForwardingPathNameUpdateName(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName4", "httpfd", "82df85", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testUniqueForwardingPathNameUpdatePort(){ + + Collection<ForwardingPathDataDefinition> paths = createData("pathName3", "httpfd", "82df85", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testLongForwardingPathPortNumber(){ + String port = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData("pathName", + "http", port, "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testLongForwardingPathProtocol(){ + String protocol = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection<ForwardingPathDataDefinition> paths = createData("pathName", + protocol, "port", "name1"); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + private Set<ForwardingPathDataDefinition> createData(String pathName, String protocol, String ports, String uniqueId) { + + return Sets.newHashSet(createPath(pathName, protocol, ports, uniqueId)); + } + + + private <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement() { + + return Either.left((T) setUpServiceMcok()); + } + + private Service setUpServiceMcok(){ + Service service = new Service(); + service.addForwardingPath(createPath("pathName3", "http", "8285", "name1")); + return service; + } + + private class ForwardingPathValidationUtilTest extends ForwardingPathValidator { + + protected ResponseFormatManager getResponseFormatManager() { + return mock; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java new file mode 100644 index 0000000000..290ba07883 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("artifact-cassandra-dao") +public class ArtifactCassandraDaoMock extends ArtifactCassandraDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java new file mode 100644 index 0000000000..c4885e1f07 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("audit-cassandra-dao") +public class AuditCassandraDaoMock extends AuditCassandraDao{ + + @PostConstruct + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java new file mode 100644 index 0000000000..0d4b2f1e7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.cassandra.CassandraClient; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.springframework.stereotype.Component; + +@Component("cassandra-client") +public class CassandraClientMock extends CassandraClient{ + public CassandraClientMock() { + + } + + @Override + public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) { + return null; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java new file mode 100644 index 0000000000..6a9731e86d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.ComponentCacheAccessor; +import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao; +import org.openecomp.sdc.be.resources.data.ComponentCacheData; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component("component-cassandra-dao") +public class ComponentCassandraDaoMock extends ComponentCassandraDao { + + public static Integer DEFAULT_FETCH_SIZE = 500; + private ComponentCacheAccessor componentCacheAccessor; + + public ComponentCassandraDaoMock() { + super(); + } + + @PostConstruct + public void init() { + + } + + public Either<List<ComponentCacheData>, ActionStatus> getComponents(List<String> ids) { + + return null; + } + + public Either<List<ComponentCacheData>, ActionStatus> getAllComponentIdTimeAndType() { + return null; + } + + + public Either<ComponentCacheData, ActionStatus> getComponent(String id) { + + return null; + } + + public CassandraOperationStatus saveComponent(ComponentCacheData componentCacheData) { + return null; + } + + + public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) { + return null; + } + + + public Either<ImmutablePair<List<ComponentCacheData>, Set<String>>, ActionStatus> getComponents( + Map<String, Long> idToTimestampMap) { + + return null; + } + + public CassandraOperationStatus deleteComponent(String id) { + return null; + } + + } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java new file mode 100644 index 0000000000..748ae56bd7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java @@ -0,0 +1,61 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +public class DistributionEngineMock implements IDistributionEngine { + @Override + public boolean isActive() { + return false; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + return null; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable(String envName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable() { + return null; + } + + @Override + public void disableEnvironment(String envName) { + + } + + @Override + public StorageOperationStatus isReadyForDistribution(Service service, String envName) { + return null; + } + + @Override + public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) { + return null; + } + + @Override + public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) { + return null; + } + + @Override + public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) { + return null; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java new file mode 100644 index 0000000000..2d7b1ad287 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("operational-environment-dao") +public class EnvironmentCassandraDaoMock extends OperationalEnvironmentDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java new file mode 100644 index 0000000000..09e1a72b44 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +@org.springframework.stereotype.Component("tosca-operation-facade") +public class ForwardingPathToscaOperationFacade extends ToscaOperationFacade { + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + @Override + public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return Either.left(setupGenericServiceMock()); + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + @Override + public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { + if(resourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || resourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByName(resourceName); + } + + @Override + public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { + if(toscaResourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || toscaResourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByToscaResourceName(toscaResourceName); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java new file mode 100644 index 0000000000..1aa3ab8102 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; + +public class ForwardingPathValidatorMock extends ForwardingPathValidator { + @Override + public Either<Boolean, ResponseFormat> validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths, String serviceId, + boolean isUpdate) { + return Either.left(Boolean.TRUE); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java new file mode 100644 index 0000000000..4e3923d2ea --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java @@ -0,0 +1,218 @@ +package org.openecomp.sdc.be.components.path.beans; + + +import com.thinkaurelius.titan.core.InvalidElementException; +import com.thinkaurelius.titan.core.InvalidIDException; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.QueryException; +import com.thinkaurelius.titan.core.SchemaViolationException; +import com.thinkaurelius.titan.core.TitanConfigurationException; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import com.thinkaurelius.titan.core.util.TitanCleanup; +import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; +import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; +import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; + +@Component("titan-client") +public class InMemoryTitanGraphClient extends TitanGraphClient { + + + private static final Logger logger = LoggerFactory.getLogger(InMemoryTitanGraphClient.class); + + private static final String OK = "GOOD"; + + public InMemoryTitanGraphClient() { + } + + + private TitanGraph graph; + TitanClientStrategy titanClientStrategy; + + public InMemoryTitanGraphClient(TitanClientStrategy titanClientStrategy) { + super(); + this.titanClientStrategy = titanClientStrategy; + logger.info("** TitanGraphClient created"); + } + + @PostConstruct + public TitanOperationStatus createGraph() { + + logger.info("** createGraph started **"); + graph = TitanFactory.build().set("storage.backend", "inmemory").open(); + createTitanSchema(); + + logger.info("** in memory graph created"); + return TitanOperationStatus.OK; + + } + + + public void cleanupGraph() { + if (graph != null) { + // graph.shutdown(); + graph.close(); + TitanCleanup.clear(graph); + } + } + + public TitanOperationStatus createGraph(String titanCfgFile) { + logger.info("** open graph with {} started", titanCfgFile); + try { + logger.info("openGraph : try to load file {}", titanCfgFile); + graph = TitanFactory.open(titanCfgFile); + if (graph.isClosed()) { + logger.error("titan graph was not initialized"); + return TitanOperationStatus.NOT_CREATED; + } + + } catch (Exception e) { + this.graph = null; + logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); + return TitanOperationStatus.NOT_CONNECTED; + } + + logger.info("** Titan graph created "); + + return TitanOperationStatus.OK; + } + + + public Either<TitanGraph, TitanOperationStatus> getGraph() { + if (graph != null) { + return Either.left(graph); + } else { + return Either.right(TitanOperationStatus.NOT_CREATED); + } + } + + public TitanOperationStatus commit() { + if (graph != null) { + try { + graph.tx().commit(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public TitanOperationStatus rollback() { + if (graph != null) { + try { + // graph.rollback(); + graph.tx().rollback(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public static TitanOperationStatus handleTitanException(Exception e) { + if (e instanceof TitanConfigurationException) { + return TitanOperationStatus.TITAN_CONFIGURATION; + } + if (e instanceof SchemaViolationException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof PermanentLockingException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof IDPoolExhaustedException) { + return TitanOperationStatus.GENERAL_ERROR; + } + if (e instanceof InvalidElementException) { + return TitanOperationStatus.INVALID_ELEMENT; + } + if (e instanceof InvalidIDException) { + return TitanOperationStatus.INVALID_ID; + } + if (e instanceof QueryException) { + return TitanOperationStatus.INVALID_QUERY; + } + if (e instanceof ResourceUnavailableException) { + return TitanOperationStatus.RESOURCE_UNAVAILABLE; + } + if (e instanceof IllegalArgumentException) { + // TODO check the error message?? + return TitanOperationStatus.ILLEGAL_ARGUMENT; + } + + return TitanOperationStatus.GENERAL_ERROR; + } + + public boolean getHealth() { + return true; + } + + private boolean isGraphOpen() { + return true; + } + + + private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; + + + private void createTitanSchema() { + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class<?> clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java new file mode 100644 index 0000000000..4e0105f067 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("sdc-schema-files-cassandra-dao") +public class SdcSchemaFilesCassandraDaoMock extends SdcSchemaFilesCassandraDao { + + @PostConstruct + @Override + public void init() { + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java new file mode 100644 index 0000000000..7a7eff879a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java @@ -0,0 +1,166 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanGraphQuery; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class TitanGraphTestSetup { + + + private static final Logger logger = LoggerFactory.getLogger(TitanGraphTestSetup.class); + + private static TitanGraph graph; + + public static boolean createGraph( TitanGraph graph) { + TitanGraphTestSetup.graph = graph; + createIndexesAndDefaults(); + + logger.info("** Titan graph created "); + + return true; + } + + private static boolean isVertexExist(Map<String, Object> properties) { + TitanGraphQuery query = graph.query(); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry<String, Object> entry : properties.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable<Vertex> vertecies = query.vertices(); + java.util.Iterator<Vertex> iterator = vertecies.iterator(); + if (iterator.hasNext()) { + return true; + } + return false; + } + + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); + graph.tx().commit(); + + } + + private static void createUser(UserData user) { + Map<String, Object> checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map<String, Object> properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry<String, Object> entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private static UserData getDefaultUserAdmin() { + UserData userData = new UserData(); + userData.setAction(ActionEnum.Create); + userData.setElementType(GraphElementTypeEnum.Node); + userData.setUserId("jh0003"); + userData.setEmail("admin@sdc.com"); + userData.setFirstName("Jimmy"); + userData.setLastName("Hendrix"); + userData.setRole("ADMIN"); + userData.setStatus(UserStatusEnum.ACTIVE.name()); + userData.setLastLoginTime(0L); + return userData; + } + + + private static void createVertexIndixes() { + logger.info("** createVertexIndixes started"); + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class<?> clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + logger.info("** createVertexIndixes ended"); + + } + + private static void createEdgeIndixes() { + logger.info("** createEdgeIndixes started"); + TitanManagement graphMgt = graph.openManagement(); + for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); + + } + } + graphMgt.commit(); + logger.info("** createEdgeIndixes ended"); + } + + private static void createIndexesAndDefaults() { + createVertexIndixes(); + createEdgeIndixes(); + createDefaultAdminUser(); + createRootCatalogVertex(); + } + private static void createRootCatalogVertex(){ + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); + vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()); + graph.tx().commit(); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java new file mode 100644 index 0000000000..79a1dab517 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java @@ -0,0 +1,115 @@ +/*- + * ============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.path.utils; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +public final class GraphTestUtils { + + public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) { + GraphVertex vertex = new GraphVertex(); + if (type == ResourceTypeEnum.VF) { + vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + } else { + vertex.setLabel(VertexTypeEnum.NODE_TYPE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); + } + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); + vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); + for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static GraphVertex createServiceVertex(TitanDao titanDao, Map<GraphPropertyEnum, Object> metadataProps){ + GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + String uuid = UUID.randomUUID().toString(); + + vertex.setUniqueId(uuid); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static void clearGraph(TitanDao titanDao) { + Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } + + public static String exportGraphMl(TitanGraph graph, String outputDirectory) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + graph.tx().commit(); + } catch (Exception e) { + graph.tx().rollback(); + e.printStackTrace(); + } + return result; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java new file mode 100644 index 0000000000..9bd04d6da3 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java @@ -0,0 +1,238 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstancePropertyDeceleratorTest extends PropertyDeceleratorTestBase { + + private static final String INSTANCE_ID = "inst1"; + private static final String RESOURCE_ID = "resource1"; + + @InjectMocks + private ComponentInstancePropertyDecelerator testInstance; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Captor + private ArgumentCaptor<Map<String, List<ComponentInstanceProperty>>> instancePropertiesCaptor; + private Resource resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithInstance(); + } + + @Test + public void declarePropertiesAsInputs_componentInstanceNotExist() { + Component cmpt = new Resource(); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(cmpt, "someCmptInstId", Collections.emptyList()); + assertThat(createdInputs.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void declarePropertiesAsInputs_singleNonComplexProperty() { + List<PropertyDataDefinition> properties = Collections.singletonList(prop1); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_multipleNonComplexProperty() { + List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_singleComplexProperty() { + PropertyDefinition innerProp1 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP1) + .setValue("true") + .setType("boolean") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + PropertyDefinition innerProp2 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP2) + .setValue("abc") + .setType("string") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + List<ComponentInstancePropInput> propsToDeclare = createComplexPropInputList(innerProp1, innerProp2); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List<InputDefinition> inputs = createdInputs.left().value(); + List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + + verifyCreatedInputsFromComplexProperty(propsToDeclare, capturedInstanceProperties, inputs); + verifyUpdatedComplexProperty(capturedInstanceProperties, inputs); + } + + private void verifyUpdatedProperties(List<PropertyDataDefinition> properties, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(capturedInstanceProperties).hasSize(properties.size()); + Map<String, ComponentInstanceProperty> updatedPropertiesByName = MapUtil.toMap(capturedInstanceProperties, ComponentInstanceProperty::getName); + properties.forEach(prop -> verifyUpdatedInstanceProperty(prop, updatedPropertiesByName.get(prop.getName()), inputs)); + } + + private void verifyUpdatedComplexProperty(List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(capturedInstanceProperties).hasSize(1); + verifyUpdatedInstanceComplexProperty(capturedInstanceProperties.get(0), inputs); + } + + private void verifyCreatedInputs(List<PropertyDataDefinition> originalPropsToDeclare, List<ComponentInstanceProperty> capturedUpdatedProperties, List<InputDefinition> inputs) { + assertThat(inputs).hasSize(originalPropsToDeclare.size()); + Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(inputs, InputDefinition::getPropertyId); + originalPropsToDeclare.forEach(propToDeclare -> verifyCreatedInput(propToDeclare, propertyIdToCreatedInput.get(propToDeclare.getUniqueId()))); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyCreatedInputsFromComplexProperty(List<ComponentInstancePropInput> propsToDeclare, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) { + assertThat(inputs).hasSize(propsToDeclare.size()); + Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + propsToDeclare.forEach(propToDeclare -> verifyCreatedInputFromComplexProperty(propToDeclare, inputsByName)); + Map<String, List<InputDefinition>> propertyIdToCreatedInput = MapUtil.groupListBy(inputs, InputDefinition::getPropertyId); + capturedInstanceProperties.forEach(updatedProperty -> verifyInputPropertiesListFromComplexProperty(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyInputPropertiesListFromComplexProperty(ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) { + inputs.forEach(input -> verifyInputPropertiesList(updatedProperty, input)); + } + + private void verifyCreatedInputFromComplexProperty(ComponentInstancePropInput parentProperty, Map<String, InputDefinition> inputsByName) { + PropertyDefinition innerProperty = parentProperty.getInput(); + String expectedInputName = generateExpectedInputName(parentProperty, innerProperty); + InputDefinition input = inputsByName.get(expectedInputName); + assertThat(input.getType()).isEqualTo(innerProperty.getType()); + assertThat(input.getValue()).isEqualTo(innerProperty.getValue()); +// assertThat(input.getDefaultValue()).isEqualTo(innerProperty.getValue());//bug + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(parentProperty.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + + } + + private void verifyInputPropertiesList(ComponentInstanceProperty updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(updatedProperty).isEqualTo(input.getProperties().get(0)); + } + + + private List<ComponentInstancePropInput> createComplexPropInputList(PropertyDefinition ... innerProperties) { + return Stream.of(innerProperties).map(this::createComplexPropInput).collect(Collectors.toList()); + } + + private ComponentInstancePropInput createComplexPropInput(PropertyDefinition innerProp) { + ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput(new ComponentInstanceProperty(complexProperty)); + componentInstancePropInput.setInput(innerProp); + componentInstancePropInput.setPropertiesName(complexProperty.getName() + "#" + innerProp.getName()); + return componentInstancePropInput; + } + + private void verifyUpdatedInstanceProperty(PropertyDataDefinition originalProperty, ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) { + assertThat(updatedProperty.getValue()).isEqualTo(generateGetInputValue(generateExpectedInputName(originalProperty))); + assertThat(updatedProperty.isGetInputProperty()).isTrue(); + assertThat(updatedProperty.getName()).isEqualTo(originalProperty.getName()); + List<GetInputValueDataDefinition> getInputValues = updatedProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyUpdatedInstanceComplexProperty(ComponentInstanceProperty updatedComplexProperty, List<InputDefinition> inputs) { + assertThat(updatedComplexProperty.getValue()).isEqualTo(generateComplexGetInputValue(inputs)); + assertThat(updatedComplexProperty.isGetInputProperty()).isTrue(); + assertThat(updatedComplexProperty.getName()).isEqualTo(complexProperty.getName()); + List<GetInputValueDataDefinition> getInputValues = updatedComplexProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyGetInputValues(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs) { + Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + getInputValues.forEach(getInputVal -> { + InputDefinition input = inputsByName.get(getInputVal.getInputName()); + assertThat(input.getUniqueId()).isEqualTo(getInputVal.getInputId()); + }); + } + + private String generateComplexGetInputValue(List<InputDefinition> createdInputs) { + return String.format("{\"%s\":%s,\"%s\":%s}", INNER_PROP1, generateGetInputValue(createdInputs.get(0).getName()), INNER_PROP2, generateGetInputValue(createdInputs.get(1).getName())); + } + + private String generateExpectedInputName(PropertyDataDefinition prop) { + return INSTANCE_ID + "_" + prop.getName(); + } + + private String generateExpectedInputName(PropertyDefinition parentProp, PropertyDefinition innerProperty) { + return INSTANCE_ID + "_" + parentProp.getName()+ "_" + innerProperty.getName(); + } + + private void verifyCreatedInput(PropertyDataDefinition property, InputDefinition input) { + assertThat(input.getType()).isEqualTo(property.getType()); + assertThat(input.getName()).isEqualTo(generateExpectedInputName(property)); + assertThat(input.getValue()).isEqualTo(property.getValue()); + assertThat(input.getDefaultValue()).isEqualTo(property.getValue()); + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(property.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + } + + private Resource createResourceWithInstance() { + ComponentInstance inst1 = new ComponentInstanceBuilder() + .setId(INSTANCE_ID) + .setNormalizedName(INSTANCE_ID) + .build(); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .addComponentInstance(inst1) + .build(); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java new file mode 100644 index 0000000000..cd454d5a84 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java @@ -0,0 +1,172 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +//note that testing for most of the common logic is under the ComponentInstancePropertyDeceleratorTest +public class PolicyPropertyDeceleratorTest extends PropertyDeceleratorTestBase{ + + private static final String POLICY_ID = "policyId"; + private static final String RESOURCE_ID = "resourceId"; + private static final String INPUT_ID = "inputId"; + @InjectMocks + private PolicyPropertyDecelerator policyPropertyDecelerator; + @Mock + private PolicyOperation policyOperation; + @Mock + private PropertyOperation propertyOperation; + @Captor + private ArgumentCaptor<List<PropertyDataDefinition>> updatedPropsCapture; + private Resource resource; + private InputDefinition input; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithPolicy(); + input = new InputDefinition(); + input.setUniqueId(INPUT_ID); + input.setName(INPUT_ID); + input.setValue("value"); + } + + @Test + public void testDeclarePropertiesAsInputs_policyNotExist() { + Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, "nonExistingPolicy", Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testDeclarePropertiesAsInputs_failedToUpdateProperties() { + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testDeclarePropertiesAsInputs() { + List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2); + List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + Either<List<InputDefinition>, StorageOperationStatus> createdInputs = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, propsToDeclare); + List<InputDefinition> inputs = createdInputs.left().value(); + assertThat(inputs).hasSize(2); + verifyInputPropertiesList(inputs, updatedPropsCapture.getValue()); + //creation of inputs values is part of the DefaultPropertyDecelerator and is tested in the ComponentInstancePropertyDeceleratorTest class + } + + @Test + public void testUnDeclareProperties_whenComponentHasNoPolicies_returnOk() { + Resource resource = new Resource(); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testUnDeclareProperties_whenNoPropertiesFromPolicyMatchInputId_returnOk() { + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(createResourceWithPolicy(), input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void whenFailingToUpdateDeclaredProperties_returnErrorStatus() { + Resource resource = createResourceWithPolicies(POLICY_ID); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + policyDefinition.setProperties(Collections.singletonList(getInputPropForInput)); + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testUnDeclareProperties_propertiesUpdatedCorrectly() { + Resource resource = createResourceWithPolicies(POLICY_ID, "policyId2"); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + PropertyDataDefinition someOtherProperty = new PropertyDataDefinitionBuilder().build(); + policyDefinition.setProperties(Arrays.asList(getInputPropForInput, someOtherProperty)); + + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + List<PropertyDataDefinition> updatedProperties = updatedPropsCapture.getValue(); + assertThat(updatedProperties).hasSize(1); + PropertyDataDefinition updatedProperty = updatedProperties.get(0); + assertThat(updatedProperty.isGetInputProperty()).isFalse(); + assertThat(updatedProperty.getValue()).isEmpty(); + assertThat(updatedProperty.getDefaultValue()).isEqualTo(getInputPropForInput.getDefaultValue()); + assertThat(updatedProperty.getUniqueId()).isEqualTo(getInputPropForInput.getUniqueId()); + } + + private Resource createResourceWithPolicy() { + return createResourceWithPolicies(POLICY_ID); + } + + private Resource createResourceWithPolicies(String ... policies) { + List<PolicyDefinition> policiesDef = Stream.of(policies) + .map(this::buildPolicy) + .collect(Collectors.toList()); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setPolicies(policiesDef) + .build(); + } + + private PolicyDefinition buildPolicy(String policyId) { + return PolicyDefinitionBuilder.create() + .setUniqueId(policyId) + .setName(policyId) + .build(); + } + + private PropertyDataDefinition buildGetInputProperty(String inputId) { + return new PropertyDataDefinitionBuilder() + .addGetInputValue(inputId) + .setUniqueId(POLICY_ID + "_" + inputId) + .setDefaultValue("defaultValue") + .setValue(generateGetInputValue(inputId)) + .build(); + } + + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java new file mode 100644 index 0000000000..0c761a948d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java @@ -0,0 +1,69 @@ +package org.openecomp.sdc.be.components.property; + +import org.junit.Before; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; + +public class PropertyDeceleratorTestBase { + + static final String INNER_PROP1 = "ecomp_generated_naming"; + static final String INNER_PROP2 = "naming_policy"; + PropertyDataDefinition prop1, prop2, complexProperty; + + @Before + public void setUp() throws Exception { + prop1 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop1") + .setType("string") + .setName("prop1") + .setValue("value1") + .build(); + + prop2 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop2") + .setType("string") + .setSchemaType("string") + .setName("prop2") + .setValue("[\"a\", \"b\"]") + .build(); + + complexProperty = new PropertyDataDefinitionBuilder() + .setUniqueId("prop3") + .setType("org.openecomp.type1") + .setName("prop3") + .setValue("{\"ecomp_generated_naming\":true\",\"naming_policy\":\"abc\"}") + .build(); + + } + + List<ComponentInstancePropInput> createInstancePropInputList(List<PropertyDataDefinition> properties) { + return properties.stream().map(prop -> new ComponentInstancePropInput(new ComponentInstanceProperty(prop))) + .collect(Collectors.toList()); + } + + void verifyInputPropertiesList(List<InputDefinition> createdInputs, List<PropertyDataDefinition> capturedUpdatedProperties) { + Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(createdInputs, InputDefinition::getPropertyId); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + String generateGetInputValue(String value) { + return String.format("{\"%s\":\"%s\"}", GET_INPUT, value); + } + + private void verifyInputPropertiesList(PropertyDataDefinition updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(new ComponentInstanceProperty(updatedProperty)).isEqualTo(input.getProperties().get(0)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java new file mode 100644 index 0000000000..56aef5d923 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java @@ -0,0 +1,138 @@ +package org.openecomp.sdc.be.components.scheduledtasks; + +import fj.data.Either; +import org.apache.commons.lang.math.NumberUtils; +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.BeConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; +import org.openecomp.sdc.be.components.scheduledtasks.RecoveryThreadManager.FixEnvironmentTask; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.datastructure.Wrapper; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class RecoveryThreadManagerTest extends BeConfDependentTest { + + @InjectMocks + RecoveryThreadManager recoveryThreadManager = new RecoveryThreadManager(); + + private OperationalEnvironmentDao operationalEnvironmentDao = mock(OperationalEnvironmentDao.class); + private EnvironmentsEngine environmentsEngine = mock(EnvironmentsEngine.class); + private ScheduledExecutorService scheduledService = mock(ScheduledExecutorService.class); + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + reset(operationalEnvironmentDao, environmentsEngine, scheduledService); + recoveryThreadManager.init(); + } + + @Test + public void testInit() { + verify(scheduledService, Mockito.times(1)).scheduleAtFixedRate(recoveryThreadManager.task, + NumberUtils.LONG_ZERO, 180L, TimeUnit.SECONDS); + + } + @SuppressWarnings("unchecked") + @Test + public void testTaskNoRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskCassandraCrash() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherResult = Either.right(CassandraOperationStatus.GENERAL_ERROR); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(eitherResult); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskMultipleFailedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockEntry = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> nonEmptyList = Either.left(Arrays.asList(mockEntry, mockEntry, mockEntry)); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(nonEmptyList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskStaleRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockFailedEntryFirst = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockFailedEntrySecond = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> failedRecordsList = Either.left(Arrays.asList(mockFailedEntryFirst, mockFailedEntrySecond)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(failedRecordsList); + + OperationalEnvironmentEntry mockInProgressNonStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockInProgressStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 /2)).when(mockInProgressNonStaleEntry).getLastModified(); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 * 2)).when(mockInProgressStaleEntry).getLastModified(); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> inProgressList = Either.left(Arrays.asList(mockInProgressNonStaleEntry, mockInProgressStaleEntry)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(inProgressList); + fixEnvironmentTask.run(); + + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntryFirst)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntrySecond)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressStaleEntry)); + verify(environmentsEngine, times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressNonStaleEntry)); + + verify(environmentsEngine, times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + + + @Test + public void testUnconnectedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockCompleteConnected = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockCompleteUnconnected = Mockito.mock(OperationalEnvironmentEntry.class); + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> completeRecordsList = Either.left(Arrays.asList(mockCompleteConnected, mockCompleteUnconnected)); + when(environmentsEngine.isInMap(mockCompleteConnected)).thenReturn(true); + when(environmentsEngine.isInMap(mockCompleteUnconnected)).thenReturn(false); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(completeRecordsList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(Either.left(Arrays.asList())); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(Either.left(Arrays.asList())); + fixEnvironmentTask.run(); + + verify(environmentsEngine).createUebTopicsForEnvironment(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).createUebTopicsForEnvironment(mockCompleteConnected); + verify(environmentsEngine).addToMap(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).addToMap(mockCompleteConnected); + verify(environmentsEngine, times(1)).createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java index 55a119e078..32e3f9c10a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.ArrayList; + public class ArtifactBuilder { private ArtifactDefinition artifactDefinition; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java new file mode 100644 index 0000000000..4c137551dc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java @@ -0,0 +1,51 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +import java.util.ArrayList; + +public class CapabilityDefinitionBuilder { + + private CapabilityDefinition capabilityDefinition; + + public CapabilityDefinitionBuilder() { + capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setProperties(new ArrayList<>()); + } + + public CapabilityDefinitionBuilder addProperty(ComponentInstanceProperty property) { + capabilityDefinition.getProperties().add(property); + return this; + } + + public CapabilityDefinitionBuilder setOwnerId(String ownerId) { + capabilityDefinition.setOwnerId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setOwnerName(String ownerName) { + capabilityDefinition.setOwnerName(ownerName); + return this; + } + + public CapabilityDefinitionBuilder setType(String type) { + capabilityDefinition.setType(type); + return this; + } + + public CapabilityDefinitionBuilder setId(String ownerId) { + capabilityDefinition.setUniqueId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setName(String name) { + capabilityDefinition.setName(name); + return this; + } + + + public CapabilityDefinition build() { + return capabilityDefinition; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java new file mode 100644 index 0000000000..490140dac0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java @@ -0,0 +1,155 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public abstract class ComponentBuilder<T extends Component, B extends ComponentBuilder<T, B>> { + + private T component; + + protected abstract T component(); + + protected abstract ComponentBuilder<T, B> self(); + + public ComponentBuilder() { + this.component = component(); + } + + public ComponentBuilder(T component) { + this.component = component; + } + + public ComponentBuilder<T, B> setUniqueId(String id) { + component.setUniqueId(id); + return self(); + } + + public ComponentBuilder<T, B> setLifeCycleState(LifecycleStateEnum lifeCycleState) { + component.setLifecycleState(lifeCycleState); + return self(); + } + + public ComponentBuilder<T, B> setLastUpdaterUserId(String lastUpdater) { + component.setLastUpdaterUserId(lastUpdater); + return self(); + } + + public ComponentBuilder<T, B> setInvariantUUid(String invariantUUid) { + component.setInvariantUUID(invariantUUid); + return self(); + } + + public ComponentBuilder<T, B> setName(String name) { + component.setName(name); + return self(); + } + + public ComponentBuilder<T, B> setComponentType(ComponentTypeEnum type) { + component.setComponentType(type); + return self(); + } + + public ComponentBuilder<T, B> setSystemName(String systemName) { + component.setSystemName(systemName); + return self(); + } + + public ComponentBuilder<T, B> addComponentInstance(ComponentInstance componentInstance) { + if (component.getComponentInstances() == null) { + component.setComponentInstances(new ArrayList<>()); + } + component.getComponentInstances().add(componentInstance); + return self(); + } + + public ComponentBuilder<T, B> addInput(InputDefinition input) { + if (component.getInputs() == null) { + component.setInputs(new ArrayList<>()); + } + component.getInputs().add(input); + return self(); + } + + public ComponentBuilder<T, B> addInput(String inputName) { + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setName(inputName); + inputDefinition.setUniqueId(inputName); + this.addInput(inputDefinition); + return self(); + } + + public ComponentBuilder<T, B> addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { + if (component.getComponentInstancesProperties() == null) { + component.setComponentInstancesProperties(new HashMap<>()); + } + component.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder<T, B> addInstanceProperty(String instanceId, String propName) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); + componentInstanceProperty.setName(propName); + this.addInstanceProperty(instanceId, componentInstanceProperty); + return self(); + } + + public ComponentBuilder<T, B> addInstanceInput(String instanceId, ComponentInstanceInput prop) { + if (component.getComponentInstancesInputs() == null) { + component.setComponentInstancesInputs(new HashMap<>()); + } + component.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder<T, B> addInstanceInput(String instanceId, String propName) { + ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); + componentInstanceInput.setName(propName); + this.addInstanceInput(instanceId, componentInstanceInput); + return self(); + } + + public ComponentBuilder<T, B> addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { + if (component.getComponentInstancesRelations() == null) { + component.setComponentInstancesRelations(new ArrayList<>()); + } + component.getComponentInstancesRelations().add(requirementCapabilityRelDef); + return self(); + } + + public ComponentBuilder<T, B> addPolicy(PolicyDefinition policyDefinition) { + if (component.getPolicies() == null) { + component.setPolicies(new HashMap<>()); + } + component.getPolicies().put(policyDefinition.getUniqueId(), policyDefinition); + return self(); + } + public ComponentBuilder<T, B> addGroups(GroupDefinition groupDefinition){ + if(component.getGroups() == null){ + component.setGroups(new ArrayList<>()); + } + component.getGroups().add(groupDefinition); + return self(); + } + + public ComponentBuilder<T, B> setPolicies(List<PolicyDefinition> policies) { + component.setPolicies(MapUtil.toMap(policies, PolicyDefinition::getUniqueId)); + return self(); + } + + public T build() { + return component; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java index a99f08c20d..f461806010 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java @@ -1,17 +1,25 @@ package org.openecomp.sdc.be.components.utils; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.stream.Stream; + public class ComponentInstanceBuilder { private ComponentInstance componentInstance; public ComponentInstanceBuilder() { componentInstance = new ComponentInstance(); + componentInstance.setCapabilities(new HashMap<>()); + componentInstance.setDeploymentArtifacts(new HashMap<>()); + } + + public ComponentInstanceBuilder(ComponentInstance componentInstance) { + this.componentInstance = componentInstance; } public ComponentInstanceBuilder setName(String name) { @@ -19,6 +27,16 @@ public class ComponentInstanceBuilder { return this; } + public ComponentInstanceBuilder setNormalizedName(String name) { + componentInstance.setNormalizedName(name); + return this; + } + + public ComponentInstanceBuilder setUniqueId(String uniqueId) { + componentInstance.setUniqueId(uniqueId); + return this; + } + public ComponentInstanceBuilder setComponentUid(String componentUid) { componentInstance.setComponentUid(componentUid); return this; @@ -35,14 +53,20 @@ public class ComponentInstanceBuilder { } public ComponentInstanceBuilder addDeploymentArtifact(ArtifactDefinition artifactDefinition) { - Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (deploymentArtifacts == null) { - componentInstance.setDeploymentArtifacts(new HashMap<>()); - } componentInstance.getDeploymentArtifacts().put(artifactDefinition.getArtifactName(), artifactDefinition); return this; } + public ComponentInstanceBuilder addCapability(CapabilityDefinition capabilityDefinition) { + componentInstance.getCapabilities().computeIfAbsent(capabilityDefinition.getType(), key -> new ArrayList<>()).add(capabilityDefinition); + return this; + } + + public ComponentInstanceBuilder addCapabilities(CapabilityDefinition ... capabilities) { + Stream.of(capabilities).forEach(this::addCapability); + return this; + } + public ComponentInstance build() { return componentInstance; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java new file mode 100644 index 0000000000..d8cfa2cb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +public class ComponentInstancePropertyBuilder extends PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> { + + @Override + protected PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> self() { + return this; + } + + @Override + ComponentInstanceProperty propertyDefinition() { + return new ComponentInstanceProperty(); + } + + @Override + public ComponentInstanceProperty build() { + return propertyDefinition; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java new file mode 100644 index 0000000000..d7deaa423a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupDefinition; + +import java.util.HashMap; +import java.util.Map; + +public class GroupDefinitionBuilder { + private GroupDefinition groupDefinition; + + private GroupDefinitionBuilder() { + this.groupDefinition = new GroupDefinition(); + } + + public static GroupDefinitionBuilder create() { + return new GroupDefinitionBuilder(); + } + + public GroupDefinitionBuilder setUniqueId(String uid) { + groupDefinition.setUniqueId(uid); + return this; + } + + public GroupDefinition build() { + return groupDefinition; + } + + public GroupDefinitionBuilder addMember(String memberName, String memberId) { + Map<String, String> members = groupDefinition.getMembers(); + if (members == null) { + members = new HashMap<>(); + groupDefinition.setMembers(members); + } + members.put(memberId, memberId); + return this; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java new file mode 100644 index 0000000000..719967fd6b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupTypeDefinition; + +public class GroupTypeBuilder { + + private GroupTypeDefinition groupTypeDataDefinition; + + public static GroupTypeBuilder create() { + return new GroupTypeBuilder(); + } + + private GroupTypeBuilder() { + this.groupTypeDataDefinition = new GroupTypeDefinition(); + } + + public GroupTypeBuilder setType(String type) { + groupTypeDataDefinition.setType(type); + return this; + } + + public GroupTypeBuilder setUniqueId(String uid) { + groupTypeDataDefinition.setUniqueId(uid); + return this; + } + + public GroupTypeBuilder setVersion(String version) { + groupTypeDataDefinition.setVersion(version); + return this; + } + + public GroupTypeBuilder setDerivedFrom(String derivedFrom) { + groupTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public GroupTypeDefinition build() { + return groupTypeDataDefinition; + } + + + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java index 3a99d54ffa..249cf69112 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java @@ -1,11 +1,5 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -15,6 +9,12 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + public class ObjectGenerator { public static Resource buildResourceWithInputs(String ... inputNames) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java new file mode 100644 index 0000000000..b6aa96e7d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.Set; + +public class OperationalEnvironmentBuilder { + + private OperationalEnvironmentEntry operationalEnvironmentEntry; + + public OperationalEnvironmentBuilder() { + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + } + + public OperationalEnvironmentBuilder setEnvId(String envId) { + operationalEnvironmentEntry.setEnvironmentId(envId); + return this; + } + + public OperationalEnvironmentBuilder setDmaapUebAddress(Set<String> addresses) { + operationalEnvironmentEntry.setDmaapUebAddress(addresses); + return this; + } + + public OperationalEnvironmentBuilder setStatus(EnvironmentStatusEnum status) { + operationalEnvironmentEntry.setStatus(status); + return this; + } + + public OperationalEnvironmentEntry build() { + return operationalEnvironmentEntry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java new file mode 100644 index 0000000000..f818c04ccd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PolicyDefinitionBuilder { + + private PolicyDefinition policyDefinition; + + private PolicyDefinitionBuilder() { + this.policyDefinition = new PolicyDefinition(); + } + + public static PolicyDefinitionBuilder create() { + return new PolicyDefinitionBuilder(); + } + + public PolicyDefinitionBuilder setName(String name) { + policyDefinition.setName(name); + return this; + } + + public PolicyDefinitionBuilder setUniqueId(String uid) { + policyDefinition.setUniqueId(uid); + return this; + } + + public PolicyDefinitionBuilder setProperties(PropertyDataDefinition ... props) { + policyDefinition.setProperties(Arrays.asList(props)); + return this; + } + + public PolicyDefinitionBuilder setTargets(Map<PolicyTargetType, List<String>> targets ){ + policyDefinition.setTargets(targets); + return this; + } + + public PolicyDefinitionBuilder addComponentInstanceTarget(String instId) { + Map<PolicyTargetType, List<String>> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.COMPONENT_INSTANCES, k -> new ArrayList<>()) + .add(instId); + return this; + } + + public PolicyDefinitionBuilder addGroupTarget(String groupId) { + Map<PolicyTargetType, List<String>> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.GROUPS, k -> new ArrayList<>()).add(groupId); + return this; + } + + public PolicyDefinition build() { + return policyDefinition; + } + + private Map<PolicyTargetType, List<String>> getTargets() { + Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets(); + if (targets == null) { + targets = new HashMap<>(); + policyDefinition.setTargets(targets); + } + return targets; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java new file mode 100644 index 0000000000..8c2b54f27e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.components.utils; + + +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +import java.util.List; +import java.util.Map; + +public class PolicyTypeBuilder { + + private PolicyTypeDefinition policyTypeDataDefinition; + + public PolicyTypeBuilder() { + this.policyTypeDataDefinition = new PolicyTypeDefinition(); + } + + public PolicyTypeBuilder setType(String type) { + policyTypeDataDefinition.setType(type); + return this; + } + + public PolicyTypeBuilder setUniqueId(String uid) { + policyTypeDataDefinition.setUniqueId(uid); + return this; + } + + public PolicyTypeBuilder setDerivedFrom(String derivedFrom) { + policyTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public PolicyTypeBuilder setVersion(String version) { + policyTypeDataDefinition.setVersion(version); + return this; + } + + public PolicyTypeBuilder setDescription(String version) { + policyTypeDataDefinition.setDescription(version); + return this; + } + + public PolicyTypeBuilder setTargets(List<String> targets) { + policyTypeDataDefinition.setTargets(targets); + return this; + } + + public PolicyTypeBuilder setMetadata(Map<String, String> metadata) { + policyTypeDataDefinition.setMetadata(metadata); + return this; + } + + public PolicyTypeBuilder setModificationTime(long modificationTime) { + policyTypeDataDefinition.setModificationTime(modificationTime); + return this; + } + + public PolicyTypeBuilder setCreationTime(long creationTime) { + policyTypeDataDefinition.setModificationTime(creationTime); + return this; + } + + public PolicyTypeBuilder setOwner(String owner) { + policyTypeDataDefinition.setOwnerId(owner); + return this; + } + + public PolicyTypeBuilder setHighestVersion(boolean isHighestVersion) { + policyTypeDataDefinition.setHighestVersion(isHighestVersion); + return this; + } + + public PolicyTypeBuilder setProperties(List<PropertyDefinition> properties) { + policyTypeDataDefinition.setProperties(properties); + return this; + } + + public PolicyTypeDefinition build() { + return policyTypeDataDefinition; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java new file mode 100644 index 0000000000..9d5d71d67c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java @@ -0,0 +1,94 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; + +import java.util.ArrayList; + +public abstract class PropertyDataDefinitionAbstractBuilder<B extends PropertyDataDefinition, T extends PropertyDataDefinitionAbstractBuilder<B, T>> { + + B propertyDefinition; + + protected abstract PropertyDataDefinitionAbstractBuilder<B, T> self(); + + abstract B propertyDefinition(); + + PropertyDataDefinitionAbstractBuilder() { + propertyDefinition = propertyDefinition(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setUniqueId(String id) { + this.propertyDefinition.setUniqueId(id); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setName(String name) { + this.propertyDefinition.setName(name); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setValue(String value) { + this.propertyDefinition.setValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setDefaultValue(String value) { + this.propertyDefinition.setDefaultValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setType(String type) { + this.propertyDefinition.setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setOwnerId(String ownerId) { + this.propertyDefinition.setOwnerId(ownerId); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setSchemaType(String type) { + if (propertyDefinition.getSchema() == null) { + propertyDefinition.setSchema(new SchemaDefinition()); + } + if (propertyDefinition.getSchema().getProperty() == null) { + propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); + } + propertyDefinition.getSchema().getProperty().setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> addGetInputValue(String inputName) { + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputName(inputName); + getInputValueDataDefinition.setInputId(inputName); + if (propertyDefinition.getGetInputValues() == null) { + propertyDefinition.setGetInputValues(new ArrayList<>()); + } + propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setIsRequired(boolean required) { + this.propertyDefinition.setRequired(required); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setDescription(String description) { + this.propertyDefinition.setDescription(description); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setIsPassword(boolean isPassword) { + this.propertyDefinition.setRequired(isPassword); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder<B, T> setStatus(String status) { + this.propertyDefinition.setStatus(status); + return self(); + } + + public abstract B build(); +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java index e7ed170414..85b2228933 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java @@ -1,68 +1,29 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; -public class PropertyDataDefinitionBuilder { - - private PropertyDefinition propertyDefinition; - - public PropertyDataDefinitionBuilder() { - propertyDefinition = new PropertyDefinition(); - } - - public PropertyDataDefinitionBuilder setUniqueId(String id) { - this.propertyDefinition.setUniqueId(id); - return this; - } - - public PropertyDataDefinitionBuilder setName(String name) { - this.propertyDefinition.setName(name); - return this; - } +import java.util.List; - public PropertyDataDefinitionBuilder setValue(String value) { - this.propertyDefinition.setValue(value); - return this; - } +public class PropertyDataDefinitionBuilder extends PropertyDataDefinitionAbstractBuilder<PropertyDefinition, PropertyDataDefinitionBuilder> { - public PropertyDataDefinitionBuilder setDefaultValue(String value) { - this.propertyDefinition.setDefaultValue(value); + protected PropertyDataDefinitionBuilder self() { return this; } - public PropertyDataDefinitionBuilder setType(String type) { - this.propertyDefinition.setType(type); - return this; + @Override + PropertyDefinition propertyDefinition() { + return new PropertyDefinition(); } - public PropertyDataDefinitionBuilder setSchemaType(String type) { - if (propertyDefinition.getSchema() == null) { - propertyDefinition.setSchema(new SchemaDefinition()); - } - if (propertyDefinition.getSchema().getProperty() == null) { - propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); - } - propertyDefinition.getSchema().getProperty().setType(type); - return this; + @Override + public PropertyDefinition build() { + return propertyDefinition; } - public PropertyDataDefinitionBuilder addGetInputValue(String inputName) { - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputName(inputName); - getInputValueDataDefinition.setInputId(inputName); - if (propertyDefinition.getGetInputValues() == null) { - propertyDefinition.setGetInputValues(new ArrayList<>()); - } - propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); - return this; + public PropertyDataDefinitionBuilder setConstraints(List<PropertyConstraint> constraints) { + propertyDefinition.setConstraints(constraints); + return self(); } - public PropertyDefinition build() { - return propertyDefinition; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java index 8c457f153f..e0d35c6b6a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.components.utils; -import java.util.Collections; - import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; import org.openecomp.sdc.be.model.RelationshipImpl; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import java.util.Collections; + public class RelationsBuilder { private RequirementCapabilityRelDef relation; @@ -16,8 +16,8 @@ public class RelationsBuilder { RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(); RelationshipImpl relationship = new RelationshipImpl(); requirementAndRelationshipPair.setRelationships(relationship); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(requirementAndRelationshipPair); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(requirementAndRelationshipPair); relation.setRelationships(Collections.singletonList(capReqRel)); } @@ -27,17 +27,17 @@ public class RelationsBuilder { } public RelationsBuilder setRequirementName(String reqName) { - relation.getSingleRelationship().getRelation().setRequirement(reqName); + relation.resolveSingleRelationship().getRelation().setRequirement(reqName); return this; } public RelationsBuilder setRelationType(String type) { - relation.getSingleRelationship().getRelation().getRelationship().setType(type); + relation.resolveSingleRelationship().getRelation().getRelationship().setType(type); return this; } public RelationsBuilder setCapabilityUID(String uid) { - relation.getSingleRelationship().getRelation().setCapabilityUid(uid); + relation.resolveSingleRelationship().getRelation().setCapabilityUid(uid); return this; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java index 3d4a29da71..25468af3c9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java @@ -1,79 +1,26 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.HashMap; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; -public class ResourceBuilder { - - private Resource resource; - - public ResourceBuilder() { - this.resource = new Resource(); - } - - public ResourceBuilder(Resource resource) { - this.resource = resource; - } - - public ResourceBuilder setUniqueId(String id) { - resource.setUniqueId(id); - return this; - } - - public ResourceBuilder setInvariantUUid(String invariantUUid) { - resource.setInvariantUUID(invariantUUid); - return this; - } - - public ResourceBuilder setName(String name) { - resource.setName(name); - return this; - } - - public ResourceBuilder setComponentType(ComponentTypeEnum type) { - resource.setComponentType(type); - return this; - } +import java.util.ArrayList; - public ResourceBuilder setSystemName(String systemName) { - resource.setSystemName(systemName); - return this; - } +public class ResourceBuilder extends ComponentBuilder<Resource, ResourceBuilder> { - public ResourceBuilder addComponentInstance(ComponentInstance componentInstance) { - if (resource.getComponentInstances() == null) { - resource.setComponentInstances(new ArrayList<>()); - } - resource.getComponentInstances().add(componentInstance); - return this; - } + private Resource resource; - public ResourceBuilder addInput(InputDefinition input) { - if (resource.getInputs() == null) { - resource.setInputs(new ArrayList<>()); - } - resource.getInputs().add(input); - return this; + @Override + protected Resource component() { + resource = new Resource(); + return resource; } - public ResourceBuilder addInput(String inputName) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setName(inputName); - inputDefinition.setUniqueId(inputName); - this.addInput(inputDefinition); + @Override + protected ComponentBuilder<Resource, ResourceBuilder> self() { return this; } - public ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { + ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { if (resource.getProperties() == null) { resource.setProperties(new ArrayList<>()); } @@ -81,46 +28,14 @@ public class ResourceBuilder { return this; } - public ResourceBuilder addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { - if (resource.getComponentInstancesProperties() == null) { - resource.setComponentInstancesProperties(new HashMap<>()); - } - resource.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - - public ResourceBuilder addInstanceProperty(String instanceId, String propName) { - ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); - componentInstanceProperty.setName(propName); - this.addInstanceProperty(instanceId, componentInstanceProperty); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, ComponentInstanceInput prop) { - if (resource.getComponentInstancesInputs() == null) { - resource.setComponentInstancesInputs(new HashMap<>()); - } - resource.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, String propName) { - ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); - componentInstanceInput.setName(propName); - this.addInstanceInput(instanceId, componentInstanceInput); - return this; + public ResourceBuilder() { + super(); } - public ResourceBuilder addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { - if (resource.getComponentInstancesRelations() == null) { - resource.setComponentInstancesRelations(new ArrayList<>()); - } - resource.getComponentInstancesRelations().add(requirementCapabilityRelDef); - return this; + public ResourceBuilder(Resource resource) { + super(resource); } - - public Resource build() { - return resource; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java new file mode 100644 index 0000000000..d85ad9bcc2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.Service; + +public class ServiceBuilder extends ComponentBuilder<Service, ServiceBuilder> { + + private Service service; + + public ServiceBuilder(Service component) { + super(component); + } + + public ServiceBuilder() { + super(); + } + + @Override + protected Service component() { + service = new Service(); + return service; + } + + @Override + protected ComponentBuilder<Service, ServiceBuilder> self() { + return this; + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java new file mode 100644 index 0000000000..be19e8b795 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.be.components.utils; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UtilsTest { + + @Test + public void testThatEmptyListReturns0() { + List<String> existingResourceNames = new ArrayList<>(); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isZero(); + } + + @Test + public void testListWithValidValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithInvalidSingleValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithValidValues() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..2"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } + + @Test + public void testListWithInvalidValue() { + List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java new file mode 100644 index 0000000000..df48a538a5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java @@ -0,0 +1,153 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class ServiceDistributionValidationTest { + + private static final String USER_ID = "userId"; + private static final String SERVICE_ID = "serviceId"; + private static final String ENV_ID = "envId"; + + @InjectMocks + private ServiceDistributionValidation testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + + @Mock + private IDistributionEngine distributionEngine; + + @Mock + private ComponentsUtils componentsUtils; + + private User user; + private Service service; + private OperationalEnvironmentEntry operationalEnvironmentEntry; + private ResponseFormat errResponse; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId(USER_ID); + errResponse = new ResponseFormat(); + service = new Service(); + service.setUniqueId(SERVICE_ID); + service.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.COMPLETED); + } + + @Test + public void validateActivateServiceRequest_userNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.right(errResponse)); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(toscaOperationFacade, operationalEnvironmentDao, componentsUtils); + } + + @Test + public void validateActivateServiceRequest_ServiceNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR, ComponentTypeEnum.SERVICE)).thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_ServiceLifeCycleStateNotReadyForDistribution() { + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_operationalEnvNotExist() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(null); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_operationalEnvStatusNotComplete() { + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_couldNotParseDistributionData() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo()); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_distributionDataHasNoWorkloadContext() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_requestValid() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("context")); + assertEquals(service, activateServiceReq.left().value().getServiceToActivate()); + assertEquals("context", activateServiceReq.left().value().getWorkloadContext()); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java new file mode 100644 index 0000000000..0408d31606 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java @@ -0,0 +1,7 @@ +package org.openecomp.sdc.be.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringConfig { +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java new file mode 100644 index 0000000000..4f90a0a42f --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.datamodel; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.utils.ServiceBuilder; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; + +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UiComponentDataConverterTest { + + private PolicyDefinition policy1, policy2; + + @Before + public void setUp() throws Exception { + policy1 = PolicyDefinitionBuilder.create() + .setName("policy1") + .setUniqueId("uid1") + .build(); + + policy2 = PolicyDefinitionBuilder.create() + .setName("policy2") + .setUniqueId("uid2") + .build(); + } + + @Test + public void getUiDataTransferFromResourceByParams_policies_noPoliciesForResource() { + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(new Resource(), Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEmpty(); + } + + @Test + public void getUiDataTransferFromServiceByParams_policies_noPoliciesForResource() { + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(new Service(), Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEmpty(); + } + + @Test + public void getUiDataTransferFromResourceByParams_policies() { + Resource resourceWithPolicies = buildResourceWithPolicies(); + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resourceWithPolicies, Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList()); + } + + @Test + public void getUiDataTransferFromServiceByParams_policies() { + Service resourceWithPolicies = buildServiceWithPolicies(); + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(resourceWithPolicies, Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList()); + } + + private Resource buildResourceWithPolicies() { + return new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + private Service buildServiceWithPolicies() { + return new ServiceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } +} 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 index 290a5f4d1d..a80999a25b 100644 --- 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 @@ -20,18 +20,13 @@ 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.BeConfDependentTest; 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; @@ -43,148 +38,384 @@ 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<>(); +import javax.ws.rs.core.Response; - distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName; + +public class DistributionBusinessLogicTest extends BeConfDependentTest { + + @InjectMocks + DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class); + + CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + AuditHandler auditHandler = Mockito.mock(AuditHandler.class); + + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, + HttpStatus.SC_SERVICE_UNAVAILABLE); + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + Mockito.reset(cambriaHandler); + } + + @Test + public void testHandleRegistrationNoConsumeStatusTopic() { + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + Wrapper<Response> responseWrapper = new Wrapper<>(); + + testHandleRegistrationBasic(registrationRequest, responseWrapper); + + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + @Test + public void testHandleRegistrationConsumeStatusTopic() { + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper<Response> responseWrapper = new Wrapper<>(); + + testHandleRegistrationBasic(registrationRequest, responseWrapper); + + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + } + /** + * Registration Fails When registering as consumer to Notification With Consumer Status flag false. + */ + @Test + public void testHandleRegistrationFailedScenario() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + Wrapper<Response> responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + /** + * Registration Fails When registering as consumer to Notification With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper<Response> responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + } + + /** + * Registration Fails When registering as consumer to status With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic2() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper<Response> responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + //Failing on new registration + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + + } + + + /** + * Registration Fails When registering as PRODUCER to status With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic3() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper<Response> responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + //Failing on new registration + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + @SuppressWarnings("unchecked") + @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.any(SubscriberTypeEnum.class), Mockito.anyString())) + .thenReturn(okResponse); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString()); + + Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), + Mockito.anyString()); + + 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", false); + 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(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(okResponse); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString()); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); - 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); + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); - } + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), + CambriaOperationStatus.AUTHENTICATION_ERROR); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); - @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); + @SuppressWarnings("unchecked") + private void testHandleRegistrationBasic(RegistrationRequest registrationRequest, + Wrapper<Response> responseWrapper) { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString())) + .thenReturn(okResponse); - Wrapper<Response> responseWrapper = new Wrapper<>(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); - distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); - 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); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); - Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_OK); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString()); - TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); - String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); - assertEquals(expectedStatusTopicName, actualStatusTopicName); + TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity(); - String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); - assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); - assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK); - assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + } - } + private void testHandleRegistrationFailed(RegistrationRequest registrationRequest, + Wrapper<Response> responseWrapper, Runnable failWhen) { + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - @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); + when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName)).thenReturn(okResponse); - TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(okResponse); - String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); - assertEquals(expectedStatusTopicName, actualStatusTopicName); + failWhen.run(); - String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); - assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); - assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.AUTHENTICATION_ERROR); - assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - @Before - public void init() { - MockitoAnnotations.initMocks(this); - Mockito.reset(cambriaHandler); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java index 4e27c30f8a..4257a88a02 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java @@ -20,17 +20,9 @@ package org.openecomp.sdc.be.distribution; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.junit.Test; import org.mockito.InjectMocks; -import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.distribution.engine.ArtifactInfoImpl; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -38,69 +30,77 @@ import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -public class ServiceDistributionArtifactsBuilderTest extends BaseConfDependentTest { +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +public class ServiceDistributionArtifactsBuilderTest extends BeConfDependentTest { + + @InjectMocks + ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder(); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testConvertServiceArtifactsToArtifactInfo() { + + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setUniqueId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); - @InjectMocks - ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder(); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testConvertServiceArtifactsToArtifactInfo() { + ArtifactDefinition deploymentArtifact = new ArtifactDefinition(); + deploymentArtifact.setArtifactName("deployment.yaml"); + deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType()); + deploymentArtifact.setArtifactLabel("deployment"); + deploymentArtifact.setEsId("deployment007"); + deploymentArtifact.setUniqueId("deployment007"); + deploymentArtifact.setPayload(payload); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + deploymentArtifacts.put("deployment", deploymentArtifact); + service.setDeploymentArtifacts(deploymentArtifacts); - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setUniqueId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ArtifactDefinition deploymentArtifact = new ArtifactDefinition(); - deploymentArtifact.setArtifactName("deployment.yaml"); - deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType()); - deploymentArtifact.setArtifactLabel("deployment"); - deploymentArtifact.setEsId("deployment007"); - deploymentArtifact.setUniqueId("deployment007"); - deploymentArtifact.setPayload(payload); - Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); - deploymentArtifacts.put("deployment", deploymentArtifact); - service.setDeploymentArtifacts(deploymentArtifacts); - - Class<ServiceDistributionArtifactsBuilder> targetClass = ServiceDistributionArtifactsBuilder.class; - String methodName = "convertServiceArtifactsToArtifactInfo"; - Object[] argObjects = {service}; - Class[] argClasses = {Service.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfoRes = - (List<ArtifactInfoImpl>) method.invoke(serviceDistributionArtifactsBuilder, argObjects); - assertTrue(convertServiceArtifactsToArtifactInfoRes != null); - assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2); - List<String> artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList()); - assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml")); - } - catch (Exception e) { - e.printStackTrace(); - } - } + Class<ServiceDistributionArtifactsBuilder> targetClass = ServiceDistributionArtifactsBuilder.class; + String methodName = "convertServiceArtifactsToArtifactInfo"; + Object[] argObjects = {service}; + Class[] argClasses = {Service.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfoRes = + (List<ArtifactInfoImpl>) method.invoke(serviceDistributionArtifactsBuilder, argObjects); + assertTrue(convertServiceArtifactsToArtifactInfoRes != null); + assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2); + List<String> artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList()); + assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml")); + } + catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java index 74f0eac5ad..29b43c1920 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java @@ -20,6 +20,11 @@ package org.openecomp.sdc.be.distribution; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; + import java.util.ArrayList; import java.util.List; import java.util.Timer; @@ -35,154 +40,148 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; -import org.openecomp.sdc.be.components.distribution.engine.INotificationData; -import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; - public class TestQueue { - public static void main(String[] args) { - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setNameFormat("distribution-notification-thread"); - ThreadFactory threadFactory = threadFactoryBuilder.build(); - // TODO: add the package of google to the pom - - ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); - // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, - // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20)); - - // 2 threads are always up and they handle the tasks. in case core size - // is 0, only one is handles the tasks. - // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, - // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20)); - - // TODO : check what happen when the number of threads are full. Throw - // RejectedExecutionException - // TODO : check what happen whether the pool is full and the size of - // pool - - ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory); - Runnable task = new Runnable() { - - @Override - public void run() { - try { - System.out.println("iN SLEEP" + Thread.currentThread()); - Thread.sleep(10 * 1000); - System.out.println("OUT SLEEP"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }; - - for (int i = 0; i < 4; i++) { - try { - executorService.submit(task); - } catch (RejectedExecutionException e) { - e.printStackTrace(); - } - } - - newCachedThreadPool.submit(task); - System.out.println("After submitting the task"); - - MyWorker[] watchThreads = new MyWorker[1]; - BlockingQueue<String> queue = new ArrayBlockingQueue<>(5); - for (int i = 0; i < watchThreads.length; i++) { - MyWorker myWorker = new MyWorker(queue); - myWorker.start(); - } - - for (int i = 0; i < 1; i++) { - try { - queue.put("message " + i); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - - public static class MyTimerTask extends TimerTask { - - AtomicBoolean state; - Thread thread; - - public MyTimerTask(AtomicBoolean state, Thread thread) { - super(); - this.state = state; - this.thread = thread; - - System.out.println("After create timer"); - } - - @Override - public void run() { - System.out.println("In running of Timer task"); - if (state.get() == false) { - System.out.println("In running of Timer task. Going to interrupt thread"); - // thread.interrupt(); - } else { - System.out.println("In running of Timer task. Finished."); - } - } - - } - - public static class MyWorker extends Thread { - - boolean active = true; - private final BlockingQueue<String> queue; - - public MyWorker(BlockingQueue<String> queue) { - this.queue = queue; - } - - Timer timer = new Timer(); - - public void run() { - try { - while (active) { - String s = queue.take(); - System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s); - - AtomicBoolean atomicBoolean = new AtomicBoolean(false); - MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this); - timer.schedule(myTimerTask, 10 * 1000); - doWork(s); - atomicBoolean.set(true); - - } - } catch (InterruptedException ie) { - - System.out.println("Interrupted our thread"); - ie.printStackTrace(); - } - } - - private void doWork(String s) { - // TODO Auto-generated method stub - - CambriaHandler cambriaHandler = new CambriaHandler(); - INotificationData data = new NotificationDataImpl(); - List<String> servers = new ArrayList<>(); - servers.add("aaaaaaa"); - cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data); - - System.out.println("IN WORK " + s); - try { - Thread.sleep(1 * 1000); - } catch (InterruptedException e) { - - for (int i = 0; i < 10; i++) { - System.out.println("*************************************************"); - } - e.printStackTrace(); - } - } - } + public static void main(String[] args) { + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + threadFactoryBuilder.setNameFormat("distribution-notification-thread"); + ThreadFactory threadFactory = threadFactoryBuilder.build(); + // TODO: add the package of google to the pom + + ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); + // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, + // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20)); + + // 2 threads are always up and they handle the tasks. in case core size + // is 0, only one is handles the tasks. + // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, + // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20)); + + // TODO : check what happen when the number of threads are full. Throw + // RejectedExecutionException + // TODO : check what happen whether the pool is full and the size of + // pool + + ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory); + Runnable task = new Runnable() { + + @Override + public void run() { + try { + System.out.println("iN SLEEP" + Thread.currentThread()); + Thread.sleep(10 * 1000); + System.out.println("OUT SLEEP"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + + for (int i = 0; i < 4; i++) { + try { + executorService.submit(task); + } catch (RejectedExecutionException e) { + e.printStackTrace(); + } + } + + newCachedThreadPool.submit(task); + System.out.println("After submitting the task"); + + MyWorker[] watchThreads = new MyWorker[1]; + BlockingQueue<String> queue = new ArrayBlockingQueue<>(5); + for (int i = 0; i < watchThreads.length; i++) { + MyWorker myWorker = new MyWorker(queue); + myWorker.start(); + } + + for (int i = 0; i < 1; i++) { + try { + queue.put("message " + i); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + } + + public static class MyTimerTask extends TimerTask { + + AtomicBoolean state; + Thread thread; + + public MyTimerTask(AtomicBoolean state, Thread thread) { + super(); + this.state = state; + this.thread = thread; + + System.out.println("After create timer"); + } + + @Override + public void run() { + System.out.println("In running of Timer task"); + if (state.get() == false) { + System.out.println("In running of Timer task. Going to interrupt thread"); + // thread.interrupt(); + } else { + System.out.println("In running of Timer task. Finished."); + } + } + + } + + public static class MyWorker extends Thread { + + boolean active = true; + private final BlockingQueue<String> queue; + + public MyWorker(BlockingQueue<String> queue) { + this.queue = queue; + } + + Timer timer = new Timer(); + + public void run() { + try { + while (active) { + String s = queue.take(); + System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s); + + AtomicBoolean atomicBoolean = new AtomicBoolean(false); + MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this); + timer.schedule(myTimerTask, 10 * 1000); + doWork(s); + atomicBoolean.set(true); + + } + } catch (InterruptedException ie) { + + System.out.println("Interrupted our thread"); + ie.printStackTrace(); + } + } + + private void doWork(String s) { + // TODO Auto-generated method stub + + CambriaHandler cambriaHandler = new CambriaHandler(); + INotificationData data = new NotificationDataImpl(); + List<String> servers = new ArrayList<>(); + servers.add("aaaaaaa"); + cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data); + + System.out.println("IN WORK " + s); + try { + Thread.sleep(1 * 1000); + } catch (InterruptedException e) { + + for (int i = 0; i < 10; i++) { + System.out.println("*************************************************"); + } + e.printStackTrace(); + } + } + } } 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 index 3aa143a389..253fd31390 100644 --- 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 @@ -20,17 +20,8 @@ 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.apache.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; @@ -42,6 +33,7 @@ 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.config.SpringConfig; import org.openecomp.sdc.be.distribution.AuditHandler; import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; @@ -52,107 +44,116 @@ 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.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +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 static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; 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; - } + 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, false); + 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, false); + 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() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(DistributionServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } } 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 index 1df88c3686..8a40e83506 100644 --- 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 @@ -20,56 +20,56 @@ package org.openecomp.sdc.be.ecomp; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +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 java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -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() { + @Test + public void verifyNoDuplicatesInEcompErrorCodes() { - EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); + EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); - Map<EcompErrorCode, List<EcompClassification>> map = new HashMap<EcompErrorCode, List<EcompClassification>>(); - for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) { + 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<EcompClassification> list = map.get(ecompErrorEnum.getEcompErrorCode()); + if (list == null) { + list = new ArrayList<>(); - list.add(ecompErrorEnum.getClassification()); + 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()); - } + 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() { + @Test + public void generateEcompErrorFileInTarget() { - GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); - boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false); - assertTrue("check result from file generation", result); + 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/externalapi/servlet/AssetsDataServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java index 810da4c10b..fa43523c79 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java @@ -21,19 +21,7 @@ package org.openecomp.sdc.be.externalapi.servlet; -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 fj.data.Either; import org.apache.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; @@ -48,6 +36,7 @@ import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; @@ -62,77 +51,88 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +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 java.util.Arrays; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class AssetsDataServletTest 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 ServletUtils servletUtils = Mockito.mock(ServletUtils.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); - public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); - public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class); - public static final Resource resource = Mockito.mock(Resource.class); - public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class); - public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class); - public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class); -// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class); - public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();; - - - - - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - when(request.getSession()).thenReturn(session); - when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId"); - when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID"); - when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources")); - - 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(ServletUtils.class)).thenReturn(servletUtils); - when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic); - - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - mockResponseFormat(); - - when(resource.getName()).thenReturn("MockVFCMT"); - when(resource.getSystemName()).thenReturn("mockvfcmt"); - Either<Resource, ResponseFormat> eitherRet = Either.left(resource); - when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet); - - when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); - when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic); - when(categoryDefinition.getName()).thenReturn("Template"); - when(subCategoryDefinition.getName()).thenReturn("Monitoring Template"); - when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition)); - when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition))); - when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource)); - when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter); - - Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(), - Mockito.eq(true)); - - - - } - - - - private static void mockResponseFormat() { - when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> { + 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 ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); + public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class); + public static final Resource resource = Mockito.mock(Resource.class); + public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class); + public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class); + public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class); +// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class); + public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();; + + + + + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId"); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID"); + when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources")); + + 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(ServletUtils.class)).thenReturn(servletUtils); + when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic); + + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + mockResponseFormat(); + + when(resource.getName()).thenReturn("MockVFCMT"); + when(resource.getSystemName()).thenReturn("mockvfcmt"); + Either<Resource, ResponseFormat> eitherRet = Either.left(resource); + when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet); + + when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); + when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic); + when(categoryDefinition.getName()).thenReturn("Template"); + when(subCategoryDefinition.getName()).thenReturn("Monitoring Template"); + when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition)); + when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition))); + when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource)); + when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter); + + Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(), + Mockito.eq(true)); + + + + } + + + private static void mockResponseFormat() { + when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> { ResponseFormat ret; final ActionStatus actionStatus = invocation.getArgument(0); switch( actionStatus ){ @@ -147,52 +147,52 @@ public class AssetsDataServletTest extends JerseyTest { } return ret; }); - } - - - - @Test - public void createVfcmtHappyScenario() { - final JSONObject createRequest = buildCreateJsonRequest(); - Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID") - .post(Entity.json(createRequest.toJSONString()), Response.class); - assertTrue(response.getStatus() == HttpStatus.SC_CREATED); - - } - private static final String BASIC_CREATE_REQUEST = "{\r\n" + - " \"name\": \"VFCMT_1\",\r\n" + - " \"description\": \"VFCMT Description\",\r\n" + - " \"resourceType\" : \"VFCMT\",\r\n" + - " \"category\": \"Template\",\r\n" + - " \"subcategory\": \"Monitoring Template\",\r\n" + - " \"vendorName\" : \"DCAE\",\r\n" + - " \"vendorRelease\" : \"1.0\",\r\n" + - " \"tags\": [\r\n" + - " \"VFCMT_1\"\r\n" + - " ],\r\n" + - " \"icon\" : \"defaulticon\",\r\n" + - " \"contactId\": \"cs0008\"\r\n" + - "}"; - private JSONObject buildCreateJsonRequest() { - - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST)); - return jsonObj; - - } - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(CrudExternalServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } + } + + + + @Test + public void createVfcmtHappyScenario() { + final JSONObject createRequest = buildCreateJsonRequest(); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID") + .post(Entity.json(createRequest.toJSONString()), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_CREATED); + + } + private static final String BASIC_CREATE_REQUEST = "{\r\n" + + " \"name\": \"VFCMT_1\",\r\n" + + " \"description\": \"VFCMT Description\",\r\n" + + " \"resourceType\" : \"VFCMT\",\r\n" + + " \"category\": \"Template\",\r\n" + + " \"subcategory\": \"Monitoring Template\",\r\n" + + " \"vendorName\" : \"DCAE\",\r\n" + + " \"vendorRelease\" : \"1.0\",\r\n" + + " \"tags\": [\r\n" + + " \"VFCMT_1\"\r\n" + + " ],\r\n" + + " \"icon\" : \"defaulticon\",\r\n" + + " \"contactId\": \"cs0008\"\r\n" + + "}"; + private JSONObject buildCreateJsonRequest() { + + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST)); + return jsonObj; + + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(CrudExternalServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java new file mode 100644 index 0000000000..f185bffc17 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java @@ -0,0 +1,603 @@ +/*- + * ============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.externalapi.servlet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +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.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +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.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; +import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.DAOTitanStrategy; +import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +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.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; +import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +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.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import fj.data.Either; + +public class ExternalRefServletTest extends JerseyTest { + + private static ConfigurationManager configurationManager; + static String serviceVertexUuid; + private static final HttpSession session = Mockito.mock(HttpSession.class); + private static final ServletContext servletContext = Mockito.mock(ServletContext.class); + + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class); + private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class); + private static final ToscaOperationFacade toscaOperationFacadeMock = Mockito.mock(ToscaOperationFacade.class); + private static final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + private static final TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static final ICacheMangerOperation cacheManagerOperation = Mockito.mock(ICacheMangerOperation.class); + + private static final String COMPONENT_ID = "ci-MyComponentName"; + + private static final String FAKE_COMPONENT_ID = "ci-MyFAKEComponentName"; + private static final String MONITORING_OBJECT_TYPE = "monitoring"; + private static final String WORKFLOW_OBJECT_TYPE = "workflow"; + private static final String VERSION = "0.1"; + private static final String FAKE_VERSION = "0.5"; + private static final String REF_1 = "ref1"; + private static final String REF_2 = "ref2"; + private static final String REF_3 = "ref3"; + private static final String REF_4 = "ref4"; + private static final String REF_5 = "ref5"; + //workflow + private static final String REF_6 = "ref6"; + + @Configuration + static class TestSpringConfig { + + private GraphVertex serviceVertex; + private ExternalReferencesOperation externalReferenceOperation; + private TitanDao titanDao; + + @Bean + ExternalRefsServlet externalRefsServlet(){ + return new ExternalRefsServlet(externalRefsBusinessLogic(), componentUtils); + } + + @Bean + ExternalRefsBusinessLogic externalRefsBusinessLogic() { + return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(), graphLockOperation()); + } + + @Bean + ExternalReferencesOperation externalReferencesOperation() { + this.externalReferenceOperation = new ExternalReferencesOperation(titanDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper()); + GraphTestUtils.clearGraph(titanDao); + initGraphForTest(); + return this.externalReferenceOperation; + } + + @Bean + ToscaOperationFacade toscaOperationFacade(){ + Component componentMock = Mockito.mock(Component.class); + when(componentMock.getVersion()).thenReturn(VERSION); + when(componentMock.getUniqueId()).thenReturn(serviceVertexUuid); + List<Component> listComponents = new LinkedList<Component>(); + listComponents.add(componentMock); + when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents)); + when(toscaOperationFacadeMock.getComponentByUuidAndVersion(eq(serviceVertexUuid), eq(VERSION))).thenReturn(Either.left(componentMock)); + when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents.get(0))); + return toscaOperationFacadeMock; + } + + @Bean + IdMapper idMapper() { + IdMapper idMapper = Mockito.mock(IdMapper.class); + when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID); + when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID); + when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null); + return idMapper; + } + + @Bean + TopologyTemplateOperation topologyTemplateOperation() { + return new TopologyTemplateOperation(); + } + + @Bean + NodeTypeOperation nodeTypeOpertaion() { + return new NodeTypeOperation(null); + } + + @Bean + NodeTemplateOperation nodeTemplateOperation(){ + return new NodeTemplateOperation(); + } + + @Bean + GroupsOperation groupsOperation(){ + return new GroupsOperation(); + } + + @Bean + ICacheMangerOperation cacheMangerOperation() { return cacheManagerOperation; } + + @Bean + TitanDao titanDao() { + this.titanDao = new TitanDao(titanGraphClient()); + return titanDao; + } + + @Bean + TitanGraphClient titanGraphClient() { + return new TitanGraphClient(titanClientStrategy()); + } + + @Bean + TitanClientStrategy titanClientStrategy() { + return new DAOTitanStrategy(); + } + + @Bean + CategoryOperation categoryOperation(){ + return new CategoryOperation(); + } + + @Bean + GraphLockOperation graphLockOperation() { return graphLockOperation; } + + @Bean + TitanGenericDao titanGenericDao() { return titanGenericDao; } + + private void initGraphForTest() { + //create a service and add 1 ref + serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + serviceVertexUuid = this.serviceVertex.getUniqueId(); + + //monitoring references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + + //workflow references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); + + final TitanOperationStatus commit = this.titanDao.commit(); + assertThat(commit).isEqualTo(TitanOperationStatus.OK); + } + + + } + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + /* Users */ + private static User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(), System.currentTimeMillis()); + private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System.currentTimeMillis()); + private static User otherUser = new User("other", "other", "other", "other@email.com", Role.OPS.name(), System.currentTimeMillis()); + + + @BeforeClass + public static void setup() { + + //Needed for User Authorization + //======================================================================================================================== + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat); + when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value()); + + //Needed for error configuration + when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value()); + when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value()); + when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + + Either<User, ActionStatus> adminEither = Either.left(adminUser); + Either<User, ActionStatus> designerEither = Either.left(designerUser); + Either<User, ActionStatus> otherEither = Either.left(otherUser); + + when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminEither); + when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerEither); + when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherEither); + //======================================================================================================================== + + //TODO DELETE after successfull merge + //if (ConfigurationManager.getConfigurationManager() == null) { + String appConfigDir = "src/test/resources/config"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); + configuration.setTitanInMemoryGraph(true); + + configurationManager.setConfiguration(configuration); + //} + ExternalConfiguration.setAppName("catalog-be"); + } + + @Before + public void beforeTest() { + + } + + @Test + public void testGetExternalRefsForExistingComponentInstance() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + List<String> dto = response.readEntity(new GenericType<List<String>>() { }); + assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testGetExternalRefsForAsset() { + String path = String.format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() { }); + assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testAddExternalRefForExistingComponentInstance(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value()); + + //Check that GET will include the new reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, adminUser.getUserId()). + get(); + + List<String> dto = response.readEntity(new GenericType<List<String>>() { }); + assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testDeleteExternalRefForExistingComponentInstance(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + //Verify that the deleted reference is returned in body + ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class); + assertThat(dto.getReferenceUUID()).isEqualTo(REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + + //Check that GET will NOT include the deleted reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + List<String> getResponse = response.readEntity(new GenericType<List<String>>() { }); + assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testUpdateExternalRefForExistingComponentInstance(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + //Verify that the updated reference is returned in body + ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class); + assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + + //Check that GET will include the updated reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + + List<String> dto = response.readEntity(new GenericType<List<String>>() { }); + assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + + /* + * Rainy Scenarios + */ + @Test + public void testAddExternalRefForNonExistingAssetId(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid", COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testAddExternalRefForNonExistingCompInstId(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, "FAKE_COM_ID", MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testAddExistingExternalRef(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_1))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned + } + + @Test + public void testUpdateExternalRefForNonExistingAssetId(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + //Verify that the 404 is returned + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + + } + + @Test + public void testUpdateExternalRefForNonExistingObjectIdOrOldRef(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5); + + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + System.out.println(response.readEntity(String.class)); + } + + @Test + public void testDeleteExternalRefForNonExistingAssetId(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testDeleteExternalRefForNonExistingRef(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF"); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + System.out.println(response.readEntity(String.class)); + } + + @Test + public void testGetExternalRefsForNonExistingAsset() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id", VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testGetExternalRefsForNonExistingVersion() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testGetExternalRefsForExistingComponentInstanceWithUnauthorizedUser() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, otherUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(ExternalRefsServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(request.getHeader(eq(Constants.X_ECOMP_INSTANCE_ID_HEADER))).thenReturn("mockXEcompInstIdHeader"); + when(session.getServletContext()).thenReturn(servletContext); + } + }) + .property("contextConfig", context); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java deleted file mode 100644 index 811a3031ae..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java +++ /dev/null @@ -1,288 +0,0 @@ -package org.openecomp.sdc.be.impl; - -import java.util.EnumMap; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; -import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Component; -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.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.tosca.ToscaError; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; -import org.openecomp.sdc.exception.ResponseFormat; - -public class ComponentsUtilsTest { - - private ComponentsUtils createTestSubject() { - return new ComponentsUtils(); - } - - - @Test - public void testInit() throws Exception { - ComponentsUtils testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.Init(); - } - - - @Test - public void testGetAuditingManager() throws Exception { - ComponentsUtils testSubject; - IAuditingManager result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAuditingManager(); - } - - - @Test - public void testSetAuditingManager() throws Exception { - ComponentsUtils testSubject; - IAuditingManager auditingManager = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAuditingManager(auditingManager); - } - - - @Test - public void testAuditResource() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Resource resource = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = null; - - // test 1 - testSubject = createTestSubject(); - actionEnum = null; - testSubject.auditResource(responseFormat, modifier, resource, prevState, prevVersion, actionEnum, - additionalParams); - } - - - @Test - public void testConvertFromStorageResponse() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = null; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponse(storageResponse); - } - - - @Test - public void testConvertFromStorageResponse_1() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = null; - ComponentTypeEnum type = null; - ActionStatus result; - - // test 1 - testSubject = createTestSubject(); - storageResponse = null; - result = testSubject.convertFromStorageResponse(storageResponse, type); - Assert.assertEquals(ActionStatus.GENERAL_ERROR, result); - } - - - @Test - public void testConvertFromToscaError() throws Exception { - ComponentsUtils testSubject; - ToscaError toscaError = null; - ActionStatus result; - - // test 1 - testSubject = createTestSubject(); - toscaError = null; - result = testSubject.convertFromToscaError(toscaError); - Assert.assertEquals(ActionStatus.GENERAL_ERROR, result); - } - - - @Test - public void testConvertFromStorageResponseForCapabilityType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForCapabilityType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForLifecycleType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForLifecycleType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForResourceInstance() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - boolean isRelation = false; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForResourceInstance(storageResponse, isRelation); - } - - - @Test - public void testConvertFromStorageResponseForResourceInstanceProperty() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForResourceInstanceProperty(storageResponse); - } - - - @Test - public void testAuditComponentAdmin() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Component component = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - ComponentTypeEnum type = null; - - // default test - testSubject = createTestSubject(); - testSubject.auditComponentAdmin(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type); - } - - - @Test - public void testAuditComponent() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Component component = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - ComponentTypeEnum type = null; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = null; - - // test 1 - testSubject = createTestSubject(); - actionEnum = null; - testSubject.auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type, - additionalParams); - } - - - @Test - public void testValidateStringNotEmpty_1() throws Exception { - ComponentsUtils testSubject; - String value = ""; - Boolean result; - - // test 1 - testSubject = createTestSubject(); - value = null; - result = testSubject.validateStringNotEmpty(value); - Assert.assertEquals(false, result); - - // test 2 - testSubject = createTestSubject(); - value = ""; - result = testSubject.validateStringNotEmpty(value); - Assert.assertEquals(false, result); - } - - - @Test - public void testConvertFromStorageResponseForAdditionalInformation() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForAdditionalInformation(storageResponse); - } - - - @Test - public void testConvertFromResultStatusEnum() throws Exception { - ComponentsUtils testSubject; - ResultStatusEnum resultStatus = ResultStatusEnum.ELEMENT_NOT_FOUND; - JsonPresentationFields elementType = null; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromResultStatusEnum(resultStatus, elementType); - } - - - @Test - public void testConvertFromStorageResponseForConsumer() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForConsumer(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForGroupType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForGroupType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForDataType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForDataType(storageResponse); - } - - - -}
\ No newline at end of file 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 index cee856d905..be43fa7d62 100644 --- 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 @@ -20,9 +20,17 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; +import fj.data.Either; +import org.apache.commons.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import javax.ws.rs.core.Response; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -32,73 +40,60 @@ import java.nio.file.Paths; import java.util.Map; import java.util.stream.Stream; -import javax.ws.rs.core.Response; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; -import org.apache.commons.codec.binary.Base64; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.be.model.UploadResourceInfo; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; +public class AbstractValidationsServletTest { + private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() {}; -import fj.data.Either; + private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s"; -public class AbstractValidationsServletTest { - private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() { - }; + @Before + public void setUp() throws Exception { + servlet.initLog(mock(Logger.class)); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetScarFromPayload() { - private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s"; + 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(); + } + assertTrue(returnValue.isLeft()); + Map<String, byte[]> csar = returnValue.left().value(); + assertTrue(csar != null); + } - @Before - public void setUp() throws Exception { - servlet.initLog(mock(Logger.class)); - } + @Test + public void testValidToscaVersion() throws Exception { + Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion); + } - - @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(); - } - assertTrue(returnValue.isLeft()); - Map<String, byte[]> csar = returnValue.left().value(); - assertTrue(csar != null); - } + private void testValidToscaVersion(String version) { + Wrapper<Response> responseWrapper = new Wrapper<>(); + servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(), String.format(BASIC_TOSCA_TEMPLATE, version)); + assertTrue(responseWrapper.isEmpty()); + } - @Test - public void testValidToscaVersion() throws Exception { - Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion); - } - private void testValidToscaVersion(String version) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(), - String.format(BASIC_TOSCA_TEMPLATE, version)); - assertTrue(responseWrapper.isEmpty()); - } - } 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 index 6ef8091921..6fe303b495 100644 --- 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 @@ -20,42 +20,41 @@ 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 javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Application; +import java.util.HashSet; +import java.util.Set; + public class ApplicationConfig extends Application { - public Set<Class<?>> getClasses() { - final Set<Class<?>> resources = new HashSet<Class<?>>(); + 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); + // Add your resources. + resources.add(ResourceUploadServlet.class); + resources.add(MultiPart.class); + resources.add(FormDataContentDisposition.class); - final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - ResourceConfig resourceConfig = ResourceConfig.forApplication(this); + ResourceConfig resourceConfig = ResourceConfig.forApplication(this); - resourceConfig.register(new AbstractBinder() { + resourceConfig.register(new AbstractBinder() { - @Override - protected void configure() { - // TODO Auto-generated method stub - bind(request).to(HttpServletRequest.class); - } - }); + @Override + protected void configure() { + // TODO Auto-generated method stub + bind(request).to(HttpServletRequest.class); + } + }); - return resources; - } + return resources; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java new file mode 100644 index 0000000000..218505d8ef --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.servlets; + +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.springframework.context.annotation.Bean; + +import static org.mockito.Mockito.mock; + +public class BaseTestConfig { + + @Bean + ComponentsUtils componentsUtils() {return new ComponentsUtils(mock(AuditingManager.class));} + + @Bean + DefaultExceptionMapper defaultExceptionMapper() {return new DefaultExceptionMapper();} + + @Bean + ComponentExceptionMapper componentExceptionMapper() { + return new ComponentExceptionMapper(componentsUtils()); + } + + @Bean + StorageExceptionMapper storageExceptionMapper() { + return new StorageExceptionMapper(componentsUtils()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java index 97b1fe2a81..c723e0e664 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java @@ -1,17 +1,7 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; -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 javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.glassfish.grizzly.http.util.HttpStatus; +import fj.data.Either; +import org.eclipse.jetty.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; @@ -19,8 +9,8 @@ import org.glassfish.jersey.test.TestProperties; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -29,108 +19,114 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceServlet class */ public class ComponentInstanceServletTest extends JerseyTest { - - private final static String USER_ID = "jh0003"; - private static HttpServletRequest request; - private static HttpSession session; - private static ServletContext servletContext; - private static WebAppContextWrapper webAppContextWrapper; - private static WebApplicationContext webApplicationContext; - private static VFComponentInstanceBusinessLogic vfBusinessLogic; - private static ServiceComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - - @BeforeClass - public static void setup() { - createMocks(); - stubMethods(); - } - @Test - public void testGetRelationByIdSuccess(){ - - String containerComponentType = "resources"; - String componentId = "componentId"; - String relationId = "relationId"; - String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; - Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either.left(new RequirementCapabilityRelDef()); - when(vfBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); - Response response = target() - .path(path) - .request(MediaType.APPLICATION_JSON) - .header("USER_ID", USER_ID) - .get( Response.class); + private final static String USER_ID = "jh0003"; + private static HttpServletRequest request; + private static HttpSession session; + private static ServletContext servletContext; + private static WebAppContextWrapper webAppContextWrapper; + private static WebApplicationContext webApplicationContext; + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + + @BeforeClass + public static void setup() { + createMocks(); + stubMethods(); + } + + @Test + public void testGetRelationByIdSuccess(){ + + String containerComponentType = "resources"; + String componentId = "componentId"; + String relationId = "relationId"; + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; + Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either.left(new RequirementCapabilityRelDef()); + when(componentInstanceBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get( Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200); + } + + @Test + public void testGetRelationByIdFailure(){ + + String containerComponentType = "unknown_type"; + String componentId = "componentId"; + String relationId = "relationId"; + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get( Response.class); - assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); - } - - @Test - public void testGetRelationByIdFailure(){ - - String containerComponentType = "unknown_type"; - String componentId = "componentId"; - String relationId = "relationId"; - String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat); - Response response = target() - .path(path) - .request(MediaType.APPLICATION_JSON) - .header("USER_ID", USER_ID) - .get( Response.class); + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400); + } - assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); - } + @Override + protected ResourceConfig configure() { + forceSet(TestProperties.CONTAINER_PORT, "0"); + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + return new ResourceConfig(ComponentInstanceServlet.class) + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } - @Override - protected Application configure() { + private static void createMocks() { + request = Mockito.mock(HttpServletRequest.class); + session = Mockito.mock(HttpSession.class); + servletContext = Mockito.mock(ServletContext.class); + webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + webApplicationContext = Mockito.mock(WebApplicationContext.class); + componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class); + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + } - ResourceConfig resourceConfig = new ResourceConfig(ComponentInstanceServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - - resourceConfig.register(new AbstractBinder() { - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - return resourceConfig; - } - - private static void createMocks() { - request = Mockito.mock(HttpServletRequest.class); - session = Mockito.mock(HttpSession.class); - servletContext = Mockito.mock(ServletContext.class); - webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - webApplicationContext = Mockito.mock(WebApplicationContext.class); - vfBusinessLogic = Mockito.mock(VFComponentInstanceBusinessLogic.class); - serviceBusinessLogic = Mockito.mock(ServiceComponentInstanceBusinessLogic.class); - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - } - - private static void stubMethods() { - 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(VFComponentInstanceBusinessLogic.class)).thenReturn(vfBusinessLogic); - when(webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class)).thenReturn(serviceBusinessLogic); - when(request.getHeader("USER_ID")).thenReturn(USER_ID); - when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - } + private static void stubMethods() { + 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(ComponentInstanceBusinessLogic.class)).thenReturn(componentInstanceBusinessLogic); + when(request.getHeader("USER_ID")).thenReturn(USER_ID); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java new file mode 100644 index 0000000000..414ffaad59 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java @@ -0,0 +1,179 @@ +//package org.openecomp.sdc.be.servlets; +// +//import com.fasterxml.jackson.databind.DeserializationFeature; +//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +//import fj.data.Either; +//import org.eclipse.jetty.http.HttpStatus; +//import org.glassfish.hk2.utilities.binding.AbstractBinder; +//import org.glassfish.jersey.client.ClientConfig; +//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.Test; +//import org.junit.runner.RunWith; +//import org.mockito.Mock; +//import org.mockito.junit.MockitoJUnitRunner; +//import org.openecomp.sdc.be.DummyConfigurationManager; +//import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; +//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.impl.ServletUtils; +//import org.openecomp.sdc.be.impl.WebAppContextWrapper; +//import org.openecomp.sdc.be.info.GroupDefinitionInfo; +//import org.openecomp.sdc.be.model.GroupDefinition; +//import org.openecomp.sdc.common.api.Constants; +//import org.openecomp.sdc.exception.ResponseFormat; +//import org.springframework.web.context.WebApplicationContext; +// +//import javax.servlet.ServletContext; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpSession; +//import javax.ws.rs.client.ClientBuilder; +//import javax.ws.rs.client.Invocation; +//import javax.ws.rs.core.Application; +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.Response; +// +//import static org.assertj.core.api.Assertions.assertThat; +//import static org.junit.Assert.assertEquals; +//import static org.mockito.ArgumentMatchers.*; +//import static org.mockito.Mockito.when; +// +//@RunWith(MockitoJUnitRunner.class) +//public class GroupEndpointTest extends JerseyTest { +// +// public static final String USER_ID = "jh0003"; +// public static final String INVALID_USER_ID = "jh0001"; +// final static String RESOURCE_TYPE = "resources"; +// private static final String COMPONENT_ID = "1234"; +// private static final String VALID_GROUP_ID = "1"; +// private static final String INVALID_GROUP_ID = "2"; +// private static final String NEW_GROUP_NAME = "new group"; +// private static final String VALID_GROUP_TYPE = "networkConnection"; +// +// @Mock +// private GroupBusinessLogic groupBusinessLogic; +// @Mock +// private ServletContext servletContext; +// @Mock +// private WebAppContextWrapper webAppContextWrapper; +// @Mock +// private WebApplicationContext webApplicationContext; +// @Mock +// private HttpServletRequest request; +// @Mock +// private HttpSession session; +// @Mock +// private ComponentsUtils componentUtils; +// @Mock +// private ServletUtils servletUtils; +// @Mock +// private ResponseFormat responseFormat; +// +// @Override +// protected Application configure() { +// ResourceConfig resourceConfig = new ResourceConfig() +// .register(GroupServlet.class) +// //.register(mapper) +// ; +// forceSet(TestProperties.CONTAINER_PORT, "0"); +// resourceConfig.register(new AbstractBinder() { +// @Override +// protected void configure() { +// bind(request).to(HttpServletRequest.class); +// } +// }); +// return resourceConfig; +// } +// +// @Before +// public void before() { +// 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(GroupBusinessLogic.class)).thenReturn(groupBusinessLogic); +//// when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentUtils); +// when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); +// when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); +//// when(request.getHeader("USER_ID")).thenReturn(USER_ID); +// final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); +// setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider))); +// new DummyConfigurationManager(); +//// when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludePolicyTypesMap()); +// } +// +// //@Test +// public void createGroup() { +// GroupDefinition groupDefinition = new GroupDefinition(); +// groupDefinition.setName(NEW_GROUP_NAME); +// groupDefinition.setType(VALID_GROUP_TYPE); +// when(groupBusinessLogic.createGroup(eq(NEW_GROUP_NAME), eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(USER_ID))) +// .thenReturn(groupDefinition); +// //List<GroupDefinition> gdList = buildCreateGroupCall().post(Response.class); +// +// } +// +// //@Test +// public void deleteGroup_withInvalidUser_shouldReturn_401() { +// int unauthorized401 = HttpStatus.UNAUTHORIZED_401; +// int unauthorized403 = HttpStatus.FORBIDDEN_403; +// when(groupBusinessLogic.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean())) +// .thenReturn(Either.right(new ResponseFormat(unauthorized401))); +// +// Response response = buildDeleteGroupCall(INVALID_USER_ID, VALID_GROUP_ID).delete(); +// assertThat(response.getStatus()).isEqualTo(unauthorized401); +// } +// +// @Test +// public void getGroupById_internalServerError() { +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.right(new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR_500))); +// Response response = buildGetGroupCall(VALID_GROUP_ID).get(); +// assertEquals(response.getStatus(), 500); +// } +// +// @Test +// public void getGroupById_Success() { +// GroupDefinitionInfo groupDefinitionInfo = new GroupDefinitionInfo(); +// groupDefinitionInfo.setUniqueId(VALID_GROUP_ID); +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.left(groupDefinitionInfo)); +// when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); +// when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); +// GroupDefinitionInfo gdi = buildGetGroupCall(VALID_GROUP_ID).get(GroupDefinitionInfo.class); +// assertEquals(gdi.getUniqueId(), VALID_GROUP_ID); +// } +// +// @Test +// public void getGroupById_Failure() { +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(INVALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.right(new ResponseFormat(HttpStatus.NOT_FOUND_404))); +// Response response = buildGetGroupCall(INVALID_GROUP_ID).get(); +// assertEquals(response.getStatus(), 404); +// } +// +// private Invocation.Builder buildGetGroupCall(String groupId) { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, USER_ID); +// } +// +// private Invocation.Builder buildDeleteGroupCall(String userId, String groupId) { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, userId); +// } +// +// private Invocation.Builder buildCreateGroupCall() { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups"; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, USER_ID); +// } +//} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java new file mode 100644 index 0000000000..2d5494354d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java @@ -0,0 +1,197 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Sets; +import fj.data.Either; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.utils.GroupTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class GroupTypesEndpointTest extends JerseySpringBaseTest { + + private static final String USER_ID = "a001"; + private static final String INVALID_USER_ID = "a002"; + private static final GroupTypeDefinition EMPTY_GROUP_TYPE = new GroupTypeDefinition(); + private static final String COMPONENT_TYPE = "VF"; + private static final HashSet<String> EXCLUDED_TYPES = Sets.newHashSet("Root", "Heat"); + + private static ComponentsUtils componentsUtils; + private static GroupTypeOperation groupTypeOperation; + private static TitanDao titanDao; + private static UserValidations userValidations; + private static User user; + + @Configuration + @Import(BaseTestConfig.class) + static class GroupTypesTestConfig { + + @Bean + GroupTypesEndpoint groupTypesEndpoint() { + return new GroupTypesEndpoint(groupTypeBusinessLogic()); + } + + @Bean + GroupTypeBusinessLogic groupTypeBusinessLogic() { + return new GroupTypeBusinessLogic(groupTypeOperation, titanDao, userValidations); + } + } + + @BeforeClass + public static void initClass() { + componentsUtils = mock(ComponentsUtils.class); + groupTypeOperation = mock(GroupTypeOperation.class); + titanDao = mock(TitanDao.class); + userValidations = mock(UserValidations.class); + user = mock(User.class); + } + + @Before + public void init() { + new DummyConfigurationManager(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludeGroupTypesMap()); + ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(Either.left(user)); + // TODO: handle for invalid user test +// when(userValidations.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean())).thenReturn(Either.right(???))); + } + + @Override + protected void configureClient(ClientConfig config) { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + config.register(jacksonJsonProvider); + } + + @Override + protected ResourceConfig configure() { + return super.configure(GroupTypesTestConfig.class) + .register(GroupTypesEndpoint.class); + } + + @Test + public void getGroupTypes_validUser_Success() { + List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList(); + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList()); + List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCall(USER_ID).get(new GenericType<List<GroupTypeDefinition>>(){}); + verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes); + } + + @Test + public void getGroupTypes_whenNoInteranlComponentType_passEmptyAsExcludedTypes() { + List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList(); + when(groupTypeOperation.getAllGroupTypes(null)).thenReturn(buildGroupTypesList()); + List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCallNoInternalComponent(USER_ID).get(new GenericType<List<GroupTypeDefinition>>(){}); + verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes); + } + + @Ignore + public void getGroupTypes_dbError() { + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenThrow(new StorageException(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND)).thenReturn(new ResponseFormat(HttpStatus.NOT_FOUND.value())); + Response response = buildGetGroupTypesCall(USER_ID).get(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + // TODO: simulate proper error with configuration error mapping and eactivate the test + @Ignore + public void getGroupTypes_invalidUser_Failure() { + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList()); + Response response = buildGetGroupTypesCall(INVALID_USER_ID).get(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); + } + + private void verifyGroupTypesList(List<GroupTypeDefinition> groupTypes, List<GroupTypeDefinition> fetchedGroupTypes) { + assertThat(fetchedGroupTypes) + .usingElementComparatorOnFields("version", "type", "uniqueId") + .isEqualTo(groupTypes); + verifyOnlySpecificFieldsInResponse(fetchedGroupTypes, "version", "type", "uniqueId"); + } + + private void verifyOnlySpecificFieldsInResponse(List<GroupTypeDefinition> fetchedGroupTypes, String ... fields) { + assertThat(fetchedGroupTypes) + .usingElementComparatorIgnoringFields(fields) + .containsOnly(EMPTY_GROUP_TYPE); + } + + private Invocation.Builder buildGetGroupTypesCall(String userId) { + return target("/v1/catalog/groupTypes") + .queryParam("internalComponentType", COMPONENT_TYPE) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, userId); + } + + private Invocation.Builder buildGetGroupTypesCallNoInternalComponent(String userId) { + return target("/v1/catalog/groupTypes") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, userId); + } + + private Map<String, Set<String>> buildExcludeGroupTypesMap() { + return new ImmutableMap.Builder<String, Set<String>>() + .put("CR", Sets.newHashSet("VFModule", "Root", "Heat")) + .put(COMPONENT_TYPE, EXCLUDED_TYPES) + .build(); + } + + + private List<GroupTypeDefinition> buildGroupTypesList() { + GroupTypeDefinition type1 = GroupTypeBuilder.create() + .setDerivedFrom("root") + .setType("VFModule") + .setUniqueId("id1") + .setVersion("1.0") + .build(); + GroupTypeDefinition type2 = GroupTypeBuilder.create().setDerivedFrom("root").setType("Heat").setUniqueId("id2").build(); + return asList(type1, type2); + } + + private GroupTypeDefinition[] listOfEmptyGroupTypes(int size) { + return Stream.generate(GroupTypeDefinition::new).limit(size).toArray(GroupTypeDefinition[]::new); + } + + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java new file mode 100644 index 0000000000..9a074c95c2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.servlets; + +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.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import javax.servlet.http.HttpServletRequest; + +import static org.mockito.Mockito.mock; + +public class JerseySpringBaseTest extends JerseyTest { + + protected static HttpServletRequest request; + + @BeforeClass + public static void initBaseClass() { + request = mock(HttpServletRequest.class); + } + + protected ResourceConfig configure() { + return configure(BaseTestConfig.class); + } + + protected ResourceConfig configure(Class<?> springConfig) { + ApplicationContext context = new AnnotationConfigApplicationContext(springConfig); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig() + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .register(DefaultExceptionMapper.class) + .register(ComponentExceptionMapper.class) + .register(StorageExceptionMapper.class) + .property("jersey.config.server.provider.classnames", "org.openecomp.sdc.be.view.MixinModelWriter") + .property("contextConfig", context); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java new file mode 100644 index 0000000000..bb949253b2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java @@ -0,0 +1,338 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import fj.data.Either; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class PolicyServletTest extends JerseySpringBaseTest{ + + private final static String USER_ID = "jh0003"; + private static final String COMPONENT_ID = "componentId"; + private static PolicyBusinessLogic businessLogic; + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + + private static String validComponentType = "resources"; + private static String unsupportedComponentType = "unsupported"; + private static String componentId = "componentId"; + private static String policyTypeName = "policyTypeName"; + + private static final String PROPS_URL = "/v1/catalog/{componentType}/{serviceId}/policies/{policyId}/properties"; + private static final String SERVICE_ID = "serviceId"; + private static final String POLICY_ID = "policyId"; + + private static final String UPDATE_TARGETS_URL = "/v1/catalog/{componentType}/{componentId}/policies/{policyId}/targets"; + + @BeforeClass + public static void initClass() { + createMocks(); + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + } + + @Before + public void beforeMethod() { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider))); + } + + @Test + public void testGetPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition()); + when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get(Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); + } + + @Test + public void testGetPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get(Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testPostPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName; + PolicyDefinition policy = new PolicyDefinition(); + Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy); + when(businessLogic.createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode()); + } + + @Test + public void testPostPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName; + PolicyDefinition policy = new PolicyDefinition(); + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testPutPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy); + when(businessLogic.updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); + } + + @Test + public void testPutPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + PolicyDefinition policy = new PolicyDefinition(); + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testDeletePolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition()); + when(businessLogic.deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.NO_CONTENT_204.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .delete(Response.class); + + assertTrue(response.getStatus() == HttpStatus.NO_CONTENT_204.getStatusCode()); + } + + @Test + public void testDeletePolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .delete(Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void getPolicyProperties_operationForbidden() { + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.right(new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()))); + Response response = buildGetPropertiesRequest().get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); + } + + @Test + public void getPolicyProperties_unHandledError_returnGeneralError() { + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenThrow(new RuntimeException()); + Response response = buildGetPropertiesRequest().get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test + @Ignore + public void getPolicyProperties_wrongComponentType() { + Response response = buildGetPropertiesRequest("unknownType").get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + verifyZeroInteractions(businessLogic); + } + + @Test + public void getPolicyProperties() { + List<PropertyDataDefinition> properties = getPropertiesList(); + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.left(properties)); + List<PropertyDataDefinition> policyProps = buildGetPropertiesRequest().get(new GenericType<List<PropertyDataDefinition>>() {}); + assertThat(policyProps) + .usingElementComparatorOnFields("uniqueId") + .containsExactlyInAnyOrder(properties.get(0), properties.get(1)); + } + + @Test + public void updatePolicyPropertiesSuccess() { + List<PropertyDataDefinition> properties = getPropertiesList(); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.left(properties)); + List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(new GenericType<List<PropertyDataDefinition>>() {}); + assertThat(policyProps) + .usingElementComparatorOnFields("uniqueId") + .containsExactlyInAnyOrder(properties.get(0), properties.get(1)); + } + + @Test + public void updatePolicyTargetsSuccess() { + List<PolicyTargetDTO> targets = getTargetDTOList(); + when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(Either.left(new PolicyDefinition())); + Response policyTargets = buildUpdateTargetsRequest(ComponentTypeEnum.RESOURCE_PARAM_NAME, targets).invoke(); + assertThat(policyTargets.getStatus()).isEqualTo(200); + } + + @Test + public void updatePolicyPropertiesFailure() { + List<PropertyDataDefinition> properties = getPropertiesList(); + ResponseFormat notFoundResponse = new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode()); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.right(notFoundResponse)); + Response policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(); + assertEquals(HttpStatus.NOT_FOUND_404.getStatusCode(), policyProps.getStatus()); + } + + private List<PropertyDataDefinition> getPropertiesList() { + PropertyDefinition prop1 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop1") + .build(); + + PropertyDefinition prop2 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop2") + .build(); + return Arrays.asList(prop1, prop2); + } + + private List<PolicyTargetDTO> getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList("uniqueId")); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList("uniqueId")); + target2.setType("component_Instances"); + + return Arrays.asList(target1, target2); + } + + private Invocation.Builder buildGetPropertiesRequest(String componentType) { + return target(PROPS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + + } + + private Invocation buildUpdatePropertiesRequest(String componentType, List<PropertyDataDefinition> properties) { + return target(PROPS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON)); + } + + private Invocation buildUpdateTargetsRequest(String componentType, List<PolicyTargetDTO> targets) { + return target(UPDATE_TARGETS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("componentId", COMPONENT_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .buildPut(Entity.entity(targets, MediaType.APPLICATION_JSON)); + } + + private Invocation.Builder buildGetPropertiesRequest() { + return target(PROPS_URL) + .resolveTemplate("componentType", "services") + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + @Override + protected ResourceConfig configure() { + return super.configure() + .register(new PolicyServlet(businessLogic, servletUtils, null, componentsUtils)); + } + + private static void createMocks() { + businessLogic = Mockito.mock(PolicyBusinessLogic.class); + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java new file mode 100644 index 0000000000..23f32d169b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import fj.data.Either; +import org.apache.http.HttpStatus; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PolicyTypesEndpointTest extends JerseySpringBaseTest { + + public static final String USER_ID = "userId"; + public static final String COMPONENT_TYPE = "VF"; + private PolicyTypeBusinessLogic policyTypeBusinessLogic; + private ComponentsUtils componentUtils; + + @Override + protected ResourceConfig configure() { + policyTypeBusinessLogic = mock(PolicyTypeBusinessLogic.class); + componentUtils = mock(ComponentsUtils.class); + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return super.configure() + .register(new PolicyTypesEndpoint(policyTypeBusinessLogic)) + .register(jacksonJsonProvider); + } + + @Test + public void getPolicyTypes() { + List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList(); + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.left(policyTypes)); + when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK)); + List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCall().get(new GenericType<List<PolicyTypeDefinition>>(){}); + verifyPolicyTypesList(policyTypes, fetchedPolicyTypes); + } + + @Test + public void getPolicyTypes_whenNoInternalComponent_passNullAsComponentType() { + List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList(); + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, null)).thenReturn(Either.left(policyTypes)); + when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK)); + List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCallNoInternalComponent().get(new GenericType<List<PolicyTypeDefinition>>(){}); + verifyPolicyTypesList(policyTypes, fetchedPolicyTypes); + } + + @Test + public void getPolicyTypes_error() { + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.right(new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + Response response = buildGetPolicyTypesCall().get(); + assertThat(response.getStatus()).isEqualTo(500); + } + + private void verifyPolicyTypesList(List<PolicyTypeDefinition> policyTypes, List<PolicyTypeDefinition> fetchedPolicyTypes) { + assertThat(fetchedPolicyTypes) + .usingElementComparatorOnFields("version", "type", "uniqueId") + .isEqualTo(policyTypes); + assertThat(fetchedPolicyTypes).extracting("derivedFrom")//derivedFrom is not on the PolicyTypeMixin and should not return in response + .containsOnly((String)null); + } + + private Invocation.Builder buildGetPolicyTypesCall() { + return target("/v1/catalog/policyTypes") + .queryParam("internalComponentType", COMPONENT_TYPE) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + private Invocation.Builder buildGetPolicyTypesCallNoInternalComponent() { + return target("/v1/catalog/policyTypes") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + private List<PolicyTypeDefinition> buildPolicyTypesList() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type1").setUniqueId("id1").setVersion("1.0").build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setDerivedFrom("type1").setType("type2").setUniqueId("id2").setVersion("1.0").build(); + PolicyTypeDefinition type3 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type3").setUniqueId("id3").setVersion("1.0").build(); + return asList(type1, type2, type3); + } + + + +} 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 index 7e0c6b7647..e8aeb5fc70 100644 --- 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 @@ -20,19 +20,9 @@ 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.hk2.utilities.binding.AbstractBinder; @@ -46,6 +36,7 @@ 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.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; @@ -59,209 +50,217 @@ 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.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +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 java.util.Arrays; -import fj.data.Either; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; 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) { - byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes()); - mdJson.setPayloadData(new String(encodedBase64Payload)); - } - - 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.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam="; - when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + 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())).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) { + byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes()); + mdJson.setPayloadData(new String(encodedBase64Payload)); + } + + 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.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam="; + when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + + } - private UploadResourceInfo buildValidJson() { - UploadResourceInfo ret = new UploadResourceInfo(); - ret.setName("ciMyCompute"); - ret.setPayloadName("ciMyCompute.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[] { "ciMyCompute" })); - 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; - } + private UploadResourceInfo buildValidJson() { + UploadResourceInfo ret = new UploadResourceInfo(); + ret.setName("ciMyCompute"); + ret.setPayloadName("ciMyCompute.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[] { "ciMyCompute" })); + ret.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); + return ret; + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(ResourcesServlet.class) + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + + } } 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 index ff69241263..23daab9bf9 100644 --- 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 @@ -20,25 +20,7 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.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 com.google.gson.Gson; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.FormDataBodyPart; @@ -53,6 +35,7 @@ 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.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.UploadResourceInfo; @@ -64,125 +47,105 @@ 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.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; +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 java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; 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); - } + private static final Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class); + 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() { + + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + return new ResourceConfig(ResourceUploadServlet.class) + .register(MultiPartFeature.class) + .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); + } + }) + .property("contextConfig", context); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @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 index 37a493de37..690f7427a8 100644 --- 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 @@ -20,22 +20,8 @@ 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 fj.data.Either; +import org.eclipse.jetty.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.FormDataMultiPart; @@ -49,6 +35,7 @@ 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.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; @@ -62,182 +49,109 @@ 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.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +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.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; 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; - } - - private TypesUploadServlet createTestSubject() { - return new TypesUploadServlet(); - } - - - @Test - public void testUploadCapabilityType() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadInterfaceLifecycleType() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadCategories() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadDataTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadGroupTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadPolicyTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + private 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); + private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + private static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class); + private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + private 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); + 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); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @Override + protected ResourceConfig configure() { + + ResourceConfig resourceConfig = new ResourceConfig() + .register(new TypesUploadServlet(importManager, null, null, null, null, null)); + + 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); + } + }); + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + resourceConfig.property("contextConfig", context); + + 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 index afa0907f25..696214f49d 100644 --- 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 @@ -20,24 +20,13 @@ 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 javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import fj.data.Either; 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.junit.Test; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; @@ -52,238 +41,105 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Application; -import fj.data.Either; +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; 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); - } - - private UserAdminServlet createTestSubject() { - return new UserAdminServlet(); - } - - - @Test - public void testGet() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetRole() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUpdateUserRole() throws Exception { - UserAdminServlet testSubject; - String userIdUpdateUser = ""; - HttpServletRequest request = null; - String data = ""; - String modifierUserId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testCreateUser() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String newUserData = ""; - String modifierAttId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testAuthorize() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String userId = ""; - String firstName = ""; - String lastName = ""; - String email = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetAdminsUser() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetUsersList() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String userId = ""; - String roles = ""; - Response result; - - // test 1 - testSubject = createTestSubject(); - roles = null; - - // test 2 - testSubject = createTestSubject(); - roles = ""; - } - - - @Test - public void testDeActivateUser() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - String userIdHeader = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } + 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/tosca/CapabiltyRequirementConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java new file mode 100644 index 0000000000..3c42257446 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.be.tosca; +// + +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; + +public class CapabiltyRequirementConvertorTest { + + CapabiltyRequirementConvertor capabiltyRequirementConvertor = Mockito.spy(new CapabiltyRequirementConvertor()); + ComponentInstance instanceProxy = Mockito.spy( new ComponentInstance() ); + ComponentInstance vfInstance = Mockito.spy( new ComponentInstance() ); + Component vfComponent = Mockito.spy( new Resource() ); + ComponentInstance vfcInstance = Mockito.spy( new ComponentInstance() ); + Component vfcComponent = Mockito.spy( new Resource() ); + + @Test + public void getReducedPathByOwner() throws Exception { + List<String> pathList = new ArrayList<>(); + String uniqueId = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_2"; + + String exerpt = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"; + String duplicate = "a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"; + pathList.add(exerpt); + pathList.add(duplicate); + pathList.add(duplicate); + pathList.add(uniqueId); + + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + List<String> reducedMap = new CapabiltyRequirementConvertor().getReducedPathByOwner( pathList , uniqueId ); + + assertThat( reducedMap ).isNotNull().doesNotContain(exerpt).containsOnlyOnce(duplicate).hasSize(4); + } + + //generate stub capability + private Map<String, List<CapabilityDefinition>> newCapabilities(String capabilityName){ + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + List<CapabilityDefinition> list = new ArrayList<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setName( capabilityName ); + capabilityDefinition.setType("att.Node"); + List<String> pathList = new ArrayList<>(); + + capabilityDefinition.setOwnerId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693"); + pathList.add("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + //pathList.add("a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"); + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + capabilityDefinition.setPath(pathList); + list.add(capabilityDefinition); + capabilities.put(capabilityDefinition.getType() , list ); + + return capabilities; + } + + + @Test + public void testBuildName(){ + doReturn("1").when(instanceProxy).getActualComponentUid(); + doReturn("2").when(vfInstance).getActualComponentUid(); + doReturn("3").when(vfcInstance).getActualComponentUid(); + //region proxy + Component proxyOrigin = new Resource(); + + proxyOrigin.setName( "vepdgtp4837svc_proxy0" ); + proxyOrigin.setComponentType(ComponentTypeEnum.RESOURCE); + proxyOrigin.setComponentInstances( asList( vfInstance ) ); + + //endregion + //region vf+vfc + vfInstance.setName("vepdgtp4837vf0"); + vfInstance.setNormalizedName("vepdgtp4837vf0"); + vfInstance.setUniqueId("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + vfComponent.setName("vepdgtp4837vf0"); //origin + vfComponent.setComponentInstances(Arrays.asList(vfcInstance)); + vfcInstance.setUniqueId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcInstance.setName("lb_1"); + vfcInstance.setNormalizedName("lb_1"); + vfcInstance.setName("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcComponent.setName("lb_1"); + //endregion + Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port"); + vfcComponent.setCapabilities(capabilities); + Map<Component, ComponentInstance> map = Collections.unmodifiableMap(new HashMap<Component, ComponentInstance>() { + { + put( proxyOrigin, null ); + put( vfComponent, vfInstance ); + put( vfcComponent, vfcInstance ); + } } ) ; + Map<String, Component> cache = Collections.unmodifiableMap(new HashMap<String, Component>() {{ + put( "1",proxyOrigin); + put( "2" ,vfComponent); + put( "3" ,vfcComponent); + }}); + instanceProxy.setCapabilities(capabilities); + proxyOrigin.setCapabilities( capabilities ); + List<CapabilityDefinition> flatList = capabilities.values().stream().flatMap(List::stream).collect(Collectors.toList()); + flatList.stream().forEach( (CapabilityDefinition capabilityDefinition) -> { + String name = capabiltyRequirementConvertor.buildCapabilityNameForComponentInstance(cache, instanceProxy, capabilityDefinition); + System.out.println("built name -> " + name); + assertThat(name).isEqualTo( "vepdgtp4837vf0.lb_1."+capabilityDefinition.getName() ); + }); + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java index 7348156923..8883786d7e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java @@ -20,116 +20,71 @@ package org.openecomp.sdc.be.tosca; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.Assert; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; 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 CsarUtilsTest { - @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); - } - - @Test - public void testValidateNonMetaArtifactHappyScenario() { - String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - assertTrue(collectedWarningMessages.isEmpty()); - - artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - assertTrue(collectedWarningMessages.isEmpty()); - } - - @Test - public void testValidateNonMetaArtifactScenarioWithWarnnings() { - String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - - artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - - assertTrue(collectedWarningMessages.size() == 1); - assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); - } - - @Test - public void testValidateNonMetaArtifactUnhappyScenario() { - String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isRight()); - assertTrue(!collectedWarningMessages.isEmpty()); - } - - private CsarUtils createTestSubject() { - return new CsarUtils(); - } - - - @Test - public void testExtractVfcsArtifactsFromCsar() throws Exception { - Map<String, byte[]> csar = null; - Map<String, List<ArtifactDefinition>> result; - - // test 1 - csar = null; - result = CsarUtils.extractVfcsArtifactsFromCsar(csar); - Assert.assertEquals(new HashMap<String, List<ArtifactDefinition>>() , result); - } - - - @Test - public void testHandleWarningMessages() throws Exception { - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - - // default test - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - - - @Test - public void testValidateNonMetaArtifact() throws Exception { - String artifactPath = ""; - byte[] payloadData = new byte[] { ' ' }; - Map<String, Set<List<String>>> collectedWarningMessages = null; - Either<NonMetaArtifactInfo, Boolean> result; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; - // default test - result = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - } +import static org.junit.Assert.assertTrue; +public class CsarUtilsTest { + @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); + } + + @Test + public void testValidateNonMetaArtifactHappyScenario(){ + String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + assertTrue(collectedWarningMessages.isEmpty() ); + + artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + assertTrue(collectedWarningMessages.isEmpty() ); + } + + @Test + public void testValidateNonMetaArtifactScenarioWithWarnnings(){ + String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + + artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + + assertTrue(collectedWarningMessages.size() == 1 ); + assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); + } + + @Test + public void testValidateNonMetaArtifactUnhappyScenario(){ + String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isRight() ); + assertTrue( !collectedWarningMessages.isEmpty() ); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java index 139de137d9..dbdec12193 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java @@ -1,18 +1,6 @@ package org.openecomp.sdc.be.tosca; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; @@ -23,7 +11,18 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.tosca.model.ToscaNodeType; import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class PropertyConvertorTest { private PropertyDefinition property; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java index acfeaf1abc..839095f1ca 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.tosca; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; import java.io.FileInputStream; import java.io.IOException; @@ -31,46 +31,46 @@ import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; -import org.yaml.snakeyaml.Yaml; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class SchemaFiles { - - @Test - public void testValidateYamlNormativeFiles(){ - String importToscaPath = "src/main/resources/import/tosca"; - assertTrue(checkValidYamlInFileTree(importToscaPath)); - } - - @Test - public void testRainyYamlNormativeFiles(){ - String importToscaPathTest = "src/test/resources/yamlValidation"; - assertFalse(checkValidYamlInFileTree(importToscaPathTest)); - } - - private boolean checkValidYamlInFileTree(String fileTree) { - - try { - List<Path> fileTreeYamlList = Files.walk(Paths.get(fileTree)) - .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml")) - .collect(Collectors.toList()); - - for (Path yamlFile : fileTreeYamlList) { - try { - FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString()); - Yaml yaml = new Yaml(); - Object content = yaml.load(inputStream); - } catch (Exception e) { - System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString()); - return false; - } - } - } catch (IOException e) { - System.out.println("Error in reading file from folder : " + fileTree); - return false; - } - return true; - } - - + + @Test + public void testValidateYamlNormativeFiles(){ + String importToscaPath = "src/main/resources/import/tosca"; + assertTrue(checkValidYamlInFileTree(importToscaPath)); + } + + @Test + public void testRainyYamlNormativeFiles(){ + String importToscaPathTest = "src/test/resources/yamlValidation"; + assertFalse(checkValidYamlInFileTree(importToscaPathTest)); + } + + private boolean checkValidYamlInFileTree(String fileTree) { + + try { + List<Path> fileTreeYamlList = Files.walk(Paths.get(fileTree)) + .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml")) + .collect(Collectors.toList()); + + for (Path yamlFile : fileTreeYamlList) { + try { + FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString()); + Yaml yaml = new Yaml(); + Object content = yaml.load(inputStream); + } catch (Exception e) { + System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString()); + return false; + } + } + } catch (IOException e) { + System.out.println("Error in reading file from folder : " + fileTree); + return false; + } + return true; + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java index 4c22cf3599..efc89a9f9d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java @@ -1,124 +1,120 @@ package org.openecomp.sdc.be.tosca; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - public class ToscaExportUtilsTest { - private static Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class.getName()); - @javax.annotation.Resource - private VFComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @javax.annotation.Resource - private ServiceComponentInstanceBusinessLogic serviceInstanceBusinessLogic; - @Autowired - private ToscaExportHandler exportUtils; - @Autowired - private ComponentInstanceOperation componentInstanceOperation; - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @Test - public void testExportService() { - /* Resource resource1 = ResourceTestUtils.prepareResource(0); - resource1.setResourceType(ResourceTypeEnum.VF); - Either<Resource, ResponseFormat> createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null); - assertTrue(createResource1.isLeft()); - Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value()); - - Resource resource2 = ResourceTestUtils.prepareResource(1); - resource2.setResourceType(ResourceTypeEnum.VF); - Either<Resource, ResponseFormat> createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null); - assertTrue(createResource2.isLeft()); - Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value()); - - Service service = ResourceTestUtils.prepareService(0); - Either<Service, ResponseFormat> createService = serviceBusinessLogic.createService(service, getAdminUser()); - assertTrue(createService.isLeft()); - - // add VFC instance to VF - ComponentInstance vfcResourceInstance1 = new ComponentInstance(); - vfcResourceInstance1.setDescription("VFC instance 1"); - vfcResourceInstance1.setName(certifiedVFC1.getName()); - vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId()); - - Either<ComponentInstance, ResponseFormat> createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance1); - assertTrue(createResourceVfcInstance1.isLeft()); - - ComponentInstance vfcResourceInstance2 = new ComponentInstance(); - vfcResourceInstance2.setDescription("VFC instance 2"); - vfcResourceInstance2.setName(certifiedVFC2.getName()); - vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId()); - Either<ComponentInstance, ResponseFormat> createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance2); - assertTrue(createResourceVfcInstance2.isLeft()); - - Either<Service, ResponseFormat> serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser); - assertTrue(serviceFetch.isLeft()); - - List<ComponentInstance> componentInstances = serviceFetch.left().value().getComponentInstances(); - String ciname1 = null; - String ciname2 = null; - - for (ComponentInstance ci : componentInstances) { - if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) { - ciname1 = ci.getName(); - } - if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) { - ciname2 = ci.getName(); - } - } - - Either<ToscaRepresentation, ToscaError> result = exportUtils.exportComponent(serviceFetch.left().value()); - assertTrue(result.isLeft()); - - String mainYaml = result.left().value().getMainYaml(); - assertNotNull(mainYaml); - - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes())); - log.debug(mainYaml); - - Yaml yaml = new Yaml(); - - InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes()); - Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream); - Map<String, Object> imports = (Map<String, Object>) load.get("imports"); - assertNotNull(imports); - assertEquals("Validate imports size in yml", 2, imports.size()); - - Map<String, Object> metadata = (Map<String, Object>) load.get("metadata"); - assertNotNull(metadata); - validateMetadata(metadata, serviceFetch.left().value(), false); - - Map<String, Object> vf1 = (Map<String, Object>) imports.get(certifiedVFC1.getName()); - String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY); - ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName); - - Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template"); - Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates"); - Map<String, Object> inst1 = (Map<String, Object>) node_templates.get(ciname1); - Map<String, Object> inst2 = (Map<String, Object>) node_templates.get(ciname2); - - Map<String, Object> inst1MD = (Map<String, Object>) inst1.get("metadata"); - Map<String, Object> inst2MD = (Map<String, Object>) inst2.get("metadata"); - - validateMetadata(inst1MD, certifiedVFC1, true); - - Map<String, Object> vf2 = (Map<String, Object>) imports.get(certifiedVFC2.getName()); - fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY); - artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName); - - validateMetadata(inst2MD, certifiedVFC2, true);*/ - } + private static final Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class); + @javax.annotation.Resource + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + @Autowired + private ToscaExportHandler exportUtils; + @Autowired + private ComponentInstanceOperation componentInstanceOperation; + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @Test + public void testExportService() { + /* Resource resource1 = ResourceTestUtils.prepareResource(0); + resource1.setResourceType(ResourceTypeEnum.VF); + Either<Resource, ResponseFormat> createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null); + assertTrue(createResource1.isLeft()); + Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value()); + + Resource resource2 = ResourceTestUtils.prepareResource(1); + resource2.setResourceType(ResourceTypeEnum.VF); + Either<Resource, ResponseFormat> createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null); + assertTrue(createResource2.isLeft()); + Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value()); + + Service service = ResourceTestUtils.prepareService(0); + Either<Service, ResponseFormat> createService = serviceBusinessLogic.createService(service, getAdminUser()); + assertTrue(createService.isLeft()); + + // add VFC instance to VF + ComponentInstance vfcResourceInstance1 = new ComponentInstance(); + vfcResourceInstance1.setDescription("VFC instance 1"); + vfcResourceInstance1.setName(certifiedVFC1.getName()); + vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId()); + + Either<ComponentInstance, ResponseFormat> createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), + vfcResourceInstance1); + assertTrue(createResourceVfcInstance1.isLeft()); + + ComponentInstance vfcResourceInstance2 = new ComponentInstance(); + vfcResourceInstance2.setDescription("VFC instance 2"); + vfcResourceInstance2.setName(certifiedVFC2.getName()); + vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId()); + Either<ComponentInstance, ResponseFormat> createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), + vfcResourceInstance2); + assertTrue(createResourceVfcInstance2.isLeft()); + + Either<Service, ResponseFormat> serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser); + assertTrue(serviceFetch.isLeft()); + + List<ComponentInstance> componentInstances = serviceFetch.left().value().getComponentInstances(); + String ciname1 = null; + String ciname2 = null; + + for (ComponentInstance ci : componentInstances) { + if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) { + ciname1 = ci.getName(); + } + if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) { + ciname2 = ci.getName(); + } + } + + Either<ToscaRepresentation, ToscaError> result = exportUtils.exportComponent(serviceFetch.left().value()); + assertTrue(result.isLeft()); + + String mainYaml = result.left().value().getMainYaml(); + assertNotNull(mainYaml); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes())); + log.debug(mainYaml); + + Yaml yaml = new Yaml(); + + InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes()); + Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream); + Map<String, Object> imports = (Map<String, Object>) load.get("imports"); + assertNotNull(imports); + assertEquals("Validate imports size in yml", 2, imports.size()); + + Map<String, Object> metadata = (Map<String, Object>) load.get("metadata"); + assertNotNull(metadata); + validateMetadata(metadata, serviceFetch.left().value(), false); + + Map<String, Object> vf1 = (Map<String, Object>) imports.get(certifiedVFC1.getName()); + String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY); + ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName); + + Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template"); + Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates"); + Map<String, Object> inst1 = (Map<String, Object>) node_templates.get(ciname1); + Map<String, Object> inst2 = (Map<String, Object>) node_templates.get(ciname2); + + Map<String, Object> inst1MD = (Map<String, Object>) inst1.get("metadata"); + Map<String, Object> inst2MD = (Map<String, Object>) inst2.get("metadata"); + + validateMetadata(inst1MD, certifiedVFC1, true); + + Map<String, Object> vf2 = (Map<String, Object>) imports.get(certifiedVFC2.getName()); + fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY); + artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName); + + validateMetadata(inst2MD, certifiedVFC2, true);*/ + } } 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 index 2984d25e20..8d45e42357 100644 --- 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 @@ -20,12 +20,7 @@ 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 fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -51,385 +46,389 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCode import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; import org.slf4j.Logger; -import fj.data.Either; +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; 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; - } + private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); + private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static final 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; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java new file mode 100644 index 0000000000..95c2ac7bdd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.cucumber.runners; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.components.BeConfDependentTest; + +@RunWith(Cucumber.class) +@CucumberOptions(features = "classpath:cucumber/tenantIsolation.feature", glue = "org.openecomp.sdc.be.components.distribution.engine") + +public class RunTenantIsolationTest extends BeConfDependentTest{ + + + +}
\ No newline at end of file |