aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-be/src/test/java/org/openecomp/sdc/be/components/impl')
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java3
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java104
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java569
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java17
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java99
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java82
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java63
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java30
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java242
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java1409
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java400
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java34
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java83
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java21
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java332
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java767
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java146
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java29
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java25
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java73
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java119
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java46
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java69
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java384
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java5515
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java36
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java920
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java16
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestratorTest.java106
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperationTest.java (renamed from catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java)130
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperationTest.java (renamed from catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java)100
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java117
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java46
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java194
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java80
36 files changed, 5145 insertions, 7265 deletions
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java
index ea4df1e4ad..4e41bb39fa 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java
@@ -1,13 +1,12 @@
package org.openecomp.sdc.be.components.impl;
+import fj.data.Either;
import org.junit.Test;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
-
public class AdditionalInformationBusinessLogicTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java
new file mode 100644
index 0000000000..8029e788d9
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java
@@ -0,0 +1,104 @@
+package org.openecomp.sdc.be.components.impl;
+
+import com.google.common.collect.ImmutableList;
+import fj.data.Either;
+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.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation;
+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.auditing.AuditingActionEnum;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ArchiveBusinessLogicTest {
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Mock
+ private User user;
+ @Mock
+ private ResponseFormat responseFormat;
+ @Mock
+ private Component component;
+
+ @InjectMocks
+ private ArchiveBusinessLogic archiveBusinessLogic;
+
+ @Test
+ public void auditLastComponentVersionOnlyAndIgnorePreviousVersions() {
+ List<String> archivedCompIds = Arrays.asList("1", "2", "3", "4", "5");
+ when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class)))
+ .thenReturn(Either.left(component));
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+ when(component.getUUID())
+ .thenReturn("1")
+ .thenReturn("1")
+ .thenReturn("2")
+ .thenReturn("3")
+ .thenReturn("2");
+
+ archiveBusinessLogic.auditAction(ArchiveOperation.Action.ARCHIVE, archivedCompIds, user, ComponentTypeEnum.RESOURCE_PARAM_NAME);
+ verify(componentsUtils, times(3)).auditComponentAdmin(eq(responseFormat), eq(user), eq(component),
+ eq(AuditingActionEnum.ARCHIVE_COMPONENT), eq(ComponentTypeEnum.RESOURCE), any(String.class));
+ }
+
+
+ @Test
+ public void auditLastComponentVersionOnly() {
+ List<String> archivedCompIds = Arrays.asList("1", "2", "3", "4", "5");
+ when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class)))
+ .thenReturn(Either.left(component));
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+ when(component.getUUID())
+ .thenReturn("1")
+ .thenReturn("2")
+ .thenReturn("4")
+ .thenReturn("5")
+ .thenReturn("3");
+
+ archiveBusinessLogic.auditAction(ArchiveOperation.Action.RESTORE, archivedCompIds, user, ComponentTypeEnum.RESOURCE_PARAM_NAME);
+ verify(componentsUtils, times(5)).auditComponentAdmin(eq(responseFormat), eq(user), eq(component),
+ eq(AuditingActionEnum.RESTORE_COMPONENT), eq(ComponentTypeEnum.RESOURCE), any(String.class));
+ }
+
+
+ @Test
+ public void noAuditDoneForEmptyList() {
+ List<String> archivedCompIds = ImmutableList.of();
+ archiveBusinessLogic.auditAction(ArchiveOperation.Action.RESTORE, archivedCompIds, user, ComponentTypeEnum.RESOURCE_PARAM_NAME);
+ verify(componentsUtils, times(0)).auditComponentAdmin(any(ResponseFormat.class), any(User.class), any(Component.class),
+ any(AuditingActionEnum.class), any(ComponentTypeEnum.class), any(String.class));
+ }
+
+
+ @Test
+ public void noAuditOnErrorGetElementResponse() {
+ List<String> archivedCompIds = Arrays.asList("1", "2", "3", "4", "5");
+ when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class)))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ archiveBusinessLogic.auditAction(ArchiveOperation.Action.RESTORE, archivedCompIds, user, ComponentTypeEnum.RESOURCE_PARAM_NAME);
+ verify(componentsUtils, times(0)).auditComponentAdmin(any(ResponseFormat.class), any(User.class), any(Component.class),
+ any(AuditingActionEnum.class), any(ComponentTypeEnum.class), any(String.class));
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
new file mode 100644
index 0000000000..43430adb9e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
@@ -0,0 +1,569 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.components.impl;
+
+import 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;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.utils.ArtifactBuilder;
+import org.openecomp.sdc.be.components.utils.ObjectGenerator;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
+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.elements.ArtifactDataDefinition;
+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.*;
+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.*;
+import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.io.IOException;
+import java.util.*;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+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.*;
+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());
+ 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;
+ @Mock
+ private IInterfaceLifecycleOperation interfaceLifecycleOperation;
+
+ // 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<>();
+ 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("artifact1.yml", ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ 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);
+ assertThat(afterConvert).isEqualTo(ad);
+ }
+
+ private ArtifactDefinition createArtifactDef(String artifactName, ArtifactGroupTypeEnum groupTypeEnum) {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName(artifactName);
+ ad.setArtifactLabel("label1");
+ ad.setDescription("description");
+ ad.setArtifactType(ArtifactTypeEnum.HEAT.getType());
+ ad.setArtifactGroupType(groupTypeEnum);
+ 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);
+ assertThat(afterConvert).isNull();
+ }
+
+ @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);
+ assertThat(afterConvert).isNull();
+ }
+
+ @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);
+ assertThat(afterConvert).isNull();
+ }
+
+ @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);
+ assertThat(afterConvert).isNull();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_Unique() {
+
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName3.yml", ArtifactGroupTypeEnum.DEPLOYMENT);
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put("informationArtifact", informationArtifactDefinition1);
+ artifactDefinitionMap.put("DeploymentArtifact", deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getAllInstanceArtifacts(anyString(), anyString())).thenReturn(artifacts);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent,
+ artifactInfo , ComponentTypeEnum.RESOURCE_INSTANCE)).isTrue();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_nonUniqueResourceInterfaces() {
+
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName3.yml", ArtifactGroupTypeEnum.DEPLOYMENT);
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put("informationArtifact", informationArtifactDefinition1);
+ artifactDefinitionMap.put("DeploymentArtifact", deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getArtifacts(anyString())).thenReturn(artifacts);
+
+
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource =
+ Either.left(createInterfaceDefinitionMap("artifactName3.yml"));
+ when(interfaceLifecycleOperation.getAllInterfacesOfResource("componentId", true, true))
+ .thenReturn(allInterfacesOfResource);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent,
+ artifactInfo, ComponentTypeEnum.RESOURCE)).isFalse();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_UniqueInterface() {
+
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName2.yml", ArtifactGroupTypeEnum.DEPLOYMENT);
+ artifactInfo.setArtifactLabel("uniqueLabel");
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put(informationArtifactDefinition1.getArtifactLabel(), informationArtifactDefinition1);
+ artifactDefinitionMap.put(deploymentArtifactDefinition2.getArtifactLabel(), deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getArtifacts(anyString())).thenReturn(artifacts);
+
+
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource =
+ Either.left(createInterfaceDefinitionMap("artifactName3.yml"));
+ when(interfaceLifecycleOperation.getAllInterfacesOfResource("componentId", true, true))
+ .thenReturn(allInterfacesOfResource);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent,
+ artifactInfo, ComponentTypeEnum.RESOURCE)).isFalse();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_updateName() {
+
+ //artifacts with the same name have the same label
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName2.yml", ArtifactGroupTypeEnum.DEPLOYMENT);
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ informationArtifactDefinition1.setArtifactLabel("label2");
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put(artifactInfo.getArtifactLabel(), artifactInfo);
+ artifactDefinitionMap.put(informationArtifactDefinition1.getArtifactLabel(), informationArtifactDefinition1);
+ artifactDefinitionMap.put(deploymentArtifactDefinition2.getArtifactLabel(), deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getAllInstanceArtifacts(anyString(), anyString())).thenReturn(artifacts);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent,
+ artifactInfo, ComponentTypeEnum.RESOURCE_INSTANCE)).isTrue();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_UniqueInGroupType() {
+
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName2.yml", ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put("informationArtifact", informationArtifactDefinition1);
+ artifactDefinitionMap.put("DeploymentArtifact", deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getAllInstanceArtifacts(anyString(), anyString())).thenReturn(artifacts);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent, artifactInfo,
+ ComponentTypeEnum.RESOURCE_INSTANCE)).isTrue();
+ }
+
+ @Test
+ public void validateArtifactNameUniqueness_NonUnique() {
+
+ ArtifactDefinition artifactInfo = createArtifactDef("artifactName1.yml", ArtifactGroupTypeEnum.INFORMATIONAL);
+ artifactInfo.setArtifactLabel("artifactLabel");
+ ArtifactDefinition informationArtifactDefinition1 = createArtifactDef("artifactName1.yml",
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition deploymentArtifactDefinition2 = createArtifactDef("artifactName2.yml",
+ ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ Map<String, ArtifactDefinition> artifactDefinitionMap = new HashMap<>();
+ artifactDefinitionMap.put("informationArtifact", informationArtifactDefinition1);
+ artifactDefinitionMap.put("DeploymentArtifact", deploymentArtifactDefinition2);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = Either.left(artifactDefinitionMap);
+ when(artifactsOperations.getAllInstanceArtifacts(anyString(), anyString())).thenReturn(artifacts);
+
+ Resource parent = new Resource();
+ parent.setUniqueId("uniqueId");
+
+ assertThat(artifactBL.validateArtifactNameUniqueness("componentId", parent, artifactInfo,
+ ComponentTypeEnum.RESOURCE_INSTANCE)).isFalse();
+ }
+
+
+ private Map<String, InterfaceDefinition> createInterfaceDefinitionMap(String artifactName) {
+
+ InterfaceDefinition id1 = new InterfaceDefinition();
+ Map<String, Operation> operationMap = new HashMap<>();
+ Operation operation1 = new Operation();
+ ArtifactDataDefinition dataImplementation = new ArtifactDataDefinition();
+ dataImplementation.setArtifactName(artifactName);
+ operation1.setImplementation(dataImplementation);
+ operationMap.put("operation1", operation1);
+ id1.setOperationsMap(operationMap);
+ Map<String, InterfaceDefinition> interfaceDefMap = new HashMap<>();
+ interfaceDefMap.put("id1",id1);
+ return interfaceDefMap;
+ }
+
+ @Test
+ public void testValidMibAritactsConfiguration() {
+ Map<String, ArtifactTypeConfig> componentDeploymentArtifacts =
+ ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
+ Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts =
+ ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
+ assertThat(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())).isTrue();
+ assertThat(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())).isTrue();
+ assertThat(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())).isTrue();
+ assertThat(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())).isTrue();
+ }
+
+ @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);
+ assertThat(downloadServiceArtifactByNamesRes.isLeft()).isTrue();
+ assertThat(downloadServiceArtifactByNamesRes.left().value() !=null &&
+ downloadServiceArtifactByNamesRes.left().value().length == payload.length).isTrue();
+ }
+
+ @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());
+ assertThat(heatEnvPlaceHolder.isLeft()).isTrue();
+ assertThat(heatEnvPlaceHolder.left().value().getListHeatParameters()).isNull();
+ }
+
+ @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());
+
+ assertThat(heatEnvPlaceHolder.isLeft()).isTrue();
+ ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value();
+ List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters();
+ assertThat(listHeatParameters.size()).isEqualTo(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);
+ //TODO Remove if passes
+ when(artifactsOperations.updateArtifactOnResource(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);
+ //TODO Remove if passes
+ when(artifactsOperations.updateArtifactOnResource(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) {
+ assertThat(heatYamlParam.getCurrentValue()).isEqualTo(heatEnvParam.getDefaultValue());
+ assertThat(heatEnvParam.getCurrentValue()).isNull();
+ }
+}
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 fa0366fbef..140957f8fa 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,22 +20,17 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
public class ArtifactResolverTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java
index 52e5e29725..f35de43613 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java
@@ -36,6 +36,7 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.MockGenerator;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
import org.openecomp.sdc.be.components.utils.ArtifactBuilder;
@@ -54,29 +55,13 @@ 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.info.ArtifactTemplateInfo;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.Operation;
-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.cache.ApplicationDataTypeCache;
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;
+import org.openecomp.sdc.be.model.operations.api.*;
import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -86,29 +71,23 @@ import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.ConfigurationSource;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import java.util.*;
+
import static org.junit.Assert.assertTrue;
+
+import static org.junit.Assert.*;
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.mockito.Mockito.*;
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;
@@ -171,7 +150,7 @@ public class ArtifactsBusinessLogicTest {
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static List<ArtifactType> getAllTypes() {
- List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
+ List<ArtifactType> artifactTypes = new ArrayList<>();
List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration()
.getArtifactTypes();
for (String artifactType : artifactTypesList) {
@@ -219,10 +198,9 @@ public class ArtifactsBusinessLogicTest {
// 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(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(StorageOperationStatus.OK);
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK);
@@ -420,6 +398,7 @@ public class ArtifactsBusinessLogicTest {
.addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")).build();
Resource component = new Resource();
+ component.setComponentType(ComponentTypeEnum.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")))
@@ -544,6 +523,7 @@ public class ArtifactsBusinessLogicTest {
public void testCheckArtifactInComponent() throws Exception {
ArtifactsBusinessLogic testSubject;
Component component = new Resource();
+ component.setComponentType(ComponentTypeEnum.RESOURCE);
String artifactId = "";
boolean result;
@@ -707,7 +687,7 @@ public class ArtifactsBusinessLogicTest {
// default test
testSubject = createTestSubject();
result = Deencapsulation.invoke(testSubject, "updateGroupForHeat", new Object[] { artifactInfo,
- artifactInfo, component, componentType });
+ artifactInfo, component,componentType});
}
@@ -723,7 +703,7 @@ public class ArtifactsBusinessLogicTest {
testSubject = createTestSubject();
result = Deencapsulation.invoke(testSubject, "updateGroupForHeat",
new Object[] { artifactInfo, artifactInfo, artifactInfo,
- artifactInfo, component, componentType });
+ artifactInfo, component,componentType});
}
@@ -744,30 +724,12 @@ public class ArtifactsBusinessLogicTest {
// test 1
testSubject = createTestSubject();
+ testSubject.setComponentsUtils(MockGenerator.mockComponentUtils());
testSubject.handleAuditing(auditingActionEnum, component, componentId, user, artifactDefinition,
prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
}
@Test
- public void testCreateArtifactAuditingFields() throws Exception {
- ArtifactsBusinessLogic testSubject;
- ArtifactDefinition artifactDefinition = null;
- String prevArtifactUuid = "";
- String currentArtifactUuid = "";
- Map<AuditingFieldsKeysEnum, Object> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
- }
-
-
-
-
-
-
-
- @Test
public void testIgnoreUnupdateableFieldsInUpdate() throws Exception {
ArtifactsBusinessLogic testSubject;
ArtifactsBusinessLogic arb = new ArtifactsBusinessLogic();
@@ -1119,7 +1081,6 @@ public class ArtifactsBusinessLogicTest {
new Object[] { artifactInfo, artifactInfo });
}
-
@Test
public void testValidateAndSetArtifactname() throws Exception {
ArtifactsBusinessLogic testSubject;
@@ -1132,7 +1093,6 @@ public class ArtifactsBusinessLogicTest {
new Object[] { artifactInfo });
}
-
@Test
public void testValidateArtifactTypeNotChanged() throws Exception {
ArtifactsBusinessLogic testSubject;
@@ -1394,8 +1354,9 @@ public class ArtifactsBusinessLogicTest {
testSubject = createTestSubject();
prevUUID = "";
result = Deencapsulation.invoke(testSubject, "updateArtifactOnGroupInstance",
- new Object[] { componentType, component, instanceId, prevUUID, artifactInfo,
+ new Object[] {componentType, component, instanceId, prevUUID, artifactInfo,
artifactInfo });
+
}
@@ -1544,28 +1505,6 @@ public class ArtifactsBusinessLogicTest {
}
-
-
-
-
-
-
-
-
-
- @Test
- public void testUpdateAuditParametersWithArtifactDefinition() throws Exception {
- ArtifactsBusinessLogic testSubject;
- Map<AuditingFieldsKeysEnum,Object> additionalParams = new HashMap<>();
- ArtifactDefinition artifactInfo = buildArtifactPayload();;;
-
-
- // test 1
- testSubject=createTestSubject();
- Deencapsulation.invoke(testSubject, "updateAuditParametersWithArtifactDefinition", new Object[]{additionalParams, artifactInfo});
- }
-
-
@Test
public void testSetNodeTemplateOperation() throws Exception {
ArtifactsBusinessLogic testSubject;
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java
deleted file mode 100644
index 630f41f905..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package org.openecomp.sdc.be.components.impl;
-
-import java.util.List;
-
-import org.junit.Test;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import fj.data.Either;
-
-
-public class AttributeBusinessLogicTest {
-
- private AttributeBusinessLogic createTestSubject() {
- return new AttributeBusinessLogic();
- }
-
-
- @Test
- public void testCreateAttribute() throws Exception {
- AttributeBusinessLogic testSubject;
- String resourceId = "";
- PropertyDefinition newAttributeDef = null;
- String userId = "";
- Either<PropertyDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testIsAttributeExist() throws Exception {
- AttributeBusinessLogic testSubject;List<PropertyDefinition> attributes = null;
- String resourceUid = "";
- String propertyName = "";
- boolean result;
-
- // test 1
- testSubject=createTestSubject();attributes = null;
- }
-
-
- @Test
- public void testGetAttribute() throws Exception {
- AttributeBusinessLogic testSubject;
- String resourceId = "";
- String attributeId = "";
- String userId = "";
- Either<PropertyDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUpdateAttribute() throws Exception {
- AttributeBusinessLogic testSubject;
- String resourceId = "";
- String attributeId = "";
- PropertyDefinition newAttDef = null;
- String userId = "";
- Either<PropertyDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testDeleteAttribute() throws Exception {
- AttributeBusinessLogic testSubject;
- String resourceId = "";
- String attributeId = "";
- String userId = "";
- Either<PropertyDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-} \ No newline at end of file
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 9f5fdb8d8f..00c172e8e6 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,53 +20,57 @@
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 static org.junit.Assert.assertEquals;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
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.mock;
+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);
+ private static final CapabilityTypeOperation capabilityTypeOperation = mock(CapabilityTypeOperation.class);
+ private static final ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
+ private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class);
+ private static final PropertyOperation propertyOperation = mock(PropertyOperation.class);
+ private CommonImportManager commonImportManager = new CommonImportManager(componentsUtils, propertyOperation);
+ private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(capabilityTypeOperation, commonImportManager);
@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;
+ return Either.left((CapabilityTypeDefinition) args[0]);
}
});
- when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
- when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod();
+
+ when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao);
+ when(capabilityTypeOperation.getCapabilityType(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
}
@Before
@@ -77,16 +81,16 @@ public class CapabilityTypeImportManagerTest {
@Test
public void testCreateCapabilityTypes() throws IOException {
String ymlContent = getCapabilityTypesYml();
- Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent);
+ Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent);
assertTrue(createCapabilityTypes.isLeft());
- List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value();
- assertTrue(capabilityTypesList.size() == 14);
+ List<ImmutablePair<CapabilityTypeDefinition, Boolean>> capabilityTypesList = createCapabilityTypes.left().value();
+ assertEquals(14, capabilityTypesList.size());
Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>();
- for (CapabilityTypeDefinition capType : capabilityTypesList) {
- capibilityTypeMap.put(capType.getType(), capType);
+ for (ImmutablePair<CapabilityTypeDefinition, Boolean> capTypePair : capabilityTypesList) {
+ capibilityTypeMap.put(capTypePair.left.getType(), capTypePair.left);
}
- assertTrue(capabilityTypesList.size() == 14);
+ assertEquals(14, capabilityTypesList.size());
for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) {
assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName()));
@@ -97,8 +101,7 @@ public class CapabilityTypeImportManagerTest {
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;
+ return new String(fileContent);
}
}
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 353a6feb86..4be50e81ae 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;
@@ -46,7 +37,15 @@ import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
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.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class CategoriesImportManagerTest {
@InjectMocks
@@ -64,15 +63,13 @@ public class CategoriesImportManagerTest {
Object[] args = invocation.getArguments();
CategoryDefinition category = (CategoryDefinition) args[0];
category.setUniqueId("123");
- Either<CategoryDefinition, ActionStatus> ans = Either.left(category);
- return ans;
+ return Either.left(category);
});
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;
+ return Either.left(subcategory);
}
});
@@ -96,7 +93,6 @@ public class CategoriesImportManagerTest {
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;
+ return new String(fileContent);
}
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java
new file mode 100644
index 0000000000..15eeb31f48
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java
@@ -0,0 +1,242 @@
+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.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.openecomp.sdc.exception.ServiceException;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.*;
+
+@RunWith(MockitoJUnitRunner.class)
+public class CommonImportManagerTest {
+ private CommonImportManager commonImportManager;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ PropertyOperation propertyOperation;
+ @Mock
+ private TitanGenericDao titanGenericDao;
+
+ @Mock
+ private Function<Object, Either<ActionStatus, ResponseFormat>> validator;
+ @Mock
+ private Function<Object, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter;
+ @Mock
+ private Function<String, Either<Object, StorageOperationStatus>> elementFetcher;
+ @Mock
+ private Function<Object, Either<Object, StorageOperationStatus>> elementAdder;
+ @Mock
+ private BiFunction<Object, Object, Either<Object, StorageOperationStatus>> elementUpgrader;
+
+ @Before
+ public void startUp() {
+ commonImportManager = new CommonImportManager(componentsUtils, propertyOperation);
+
+ when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao);
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_validationFailed() {
+ Object type1 = new Object();
+ List<Object> elementTypesToCreate = Arrays.asList(type1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1)).thenReturn(elementInfo);
+
+ ResponseFormat responseFormat = new ResponseFormat();
+ responseFormat.setServiceException(new ServiceException());
+ when(validator.apply(type1)).thenReturn(Either.right(responseFormat));
+
+
+ commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any());
+ verify(titanGenericDao).rollback();
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_RuntTimeExceptionInValidation() {
+ Object type1 = new Object();
+ List<Object> elementTypesToCreate = Arrays.asList(type1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1)).thenReturn(elementInfo);
+ when(validator.apply(type1)).thenThrow(new RuntimeException("Test Exception"));
+
+ try {
+ commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+ }
+ catch(Exception skip) {
+ }
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any());
+ verify(titanGenericDao).rollback();
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeFetcherFailed() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
+ ResponseFormat responseFormat = new ResponseFormat();
+ responseFormat.setServiceException(new ServiceException());
+ when(componentsUtils.convertFromStorageResponseForCapabilityType(Mockito.any())).thenCallRealMethod();
+ when(componentsUtils.getResponseFormatByCapabilityType(ActionStatus.INVALID_CONTENT, type1)).thenReturn(responseFormat);
+
+
+ commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any());
+ verify(titanGenericDao).rollback();
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeNotFound_AddFailed() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(elementAdder.apply(type1)).thenReturn(Either.right(StorageOperationStatus.SCHEMA_VIOLATION));
+
+ ResponseFormat responseFormat = new ResponseFormat();
+ responseFormat.setServiceException(new ServiceException());
+ when(componentsUtils.convertFromStorageResponseForCapabilityType(Mockito.any())).thenCallRealMethod();
+ when(componentsUtils.getResponseFormatByCapabilityType(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, type1)).thenReturn(responseFormat);
+
+
+ commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder).apply(type1);
+ verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any());
+ verify(titanGenericDao).rollback();
+ }
+
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeNotFound_AddSucceeded() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(elementAdder.apply(type1)).thenReturn(Either.left(type1));
+
+
+ Either<List<ImmutablePair<Object, Boolean>>, ResponseFormat> result = commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder).apply(type1);
+ verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any());
+ verify(titanGenericDao).commit();
+
+ assertEquals(type1, result.left().value().get(0).getLeft());
+ assertEquals(true, result.left().value().get(0).getRight());
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeFound_UpgradeFailed() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ CapabilityTypeDefinition type1_1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1_1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1_1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1_1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.left(type1));
+ when(elementUpgrader.apply(type1_1, type1)).thenReturn(Either.right(StorageOperationStatus.SCHEMA_VIOLATION));
+
+ ResponseFormat responseFormat = new ResponseFormat();
+ responseFormat.setServiceException(new ServiceException());
+ when(componentsUtils.convertFromStorageResponseForCapabilityType(Mockito.any())).thenCallRealMethod();
+ when(componentsUtils.getResponseFormatByCapabilityType(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, type1_1)).thenReturn(responseFormat);
+
+
+ commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader).apply(type1_1, type1);
+ verify(titanGenericDao).rollback();
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeFound_UpgradeSucceeded() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ CapabilityTypeDefinition type1_1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1_1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1_1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1_1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.left(type1));
+ when(elementUpgrader.apply(type1_1, type1)).thenReturn(Either.left(type1_1));
+
+ Either<List<ImmutablePair<Object, Boolean>>, ResponseFormat> result = commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader).apply(type1_1, type1);
+ verify(titanGenericDao).commit();
+
+ assertEquals(type1_1, result.left().value().get(0).getLeft());
+ assertEquals(true, result.left().value().get(0).getRight());
+ }
+
+ @Test
+ public void testCreateElementTypesByDao_capabilityTypeFound_UpgradeAlreadyExists() {
+ CapabilityTypeDefinition type1 = new CapabilityTypeDefinition();
+ CapabilityTypeDefinition type1_1 = new CapabilityTypeDefinition();
+ List<Object> elementTypesToCreate = Arrays.asList(type1_1);
+
+ ImmutablePair<ElementTypeEnum, String> elementInfo = new ImmutablePair<>(ElementTypeEnum.CAPABILITY_TYPE, "TestCapability");
+ when(elementInfoGetter.apply(type1_1)).thenReturn(elementInfo);
+
+ when(validator.apply(type1_1)).thenReturn(Either.left(ActionStatus.OK));
+ when(elementFetcher.apply("TestCapability")).thenReturn(Either.left(type1));
+ when(elementUpgrader.apply(type1_1, type1)).thenReturn(Either.right(StorageOperationStatus.OK));
+
+ Either<List<ImmutablePair<Object, Boolean>>, ResponseFormat> result = commonImportManager.createElementTypesByDao(elementTypesToCreate , validator , elementInfoGetter, elementFetcher, elementAdder, elementUpgrader);
+
+ verify(elementAdder, never()).apply(Mockito.any());
+ verify(elementUpgrader).apply(type1_1, type1);
+ verify(titanGenericDao).commit();
+
+ assertEquals(type1_1, result.left().value().get(0).getLeft());
+ assertEquals(false, result.left().value().get(0).getRight());
+ }
+
+
+}
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 329ac3d609..ba74df91ed 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,56 +1,36 @@
package org.openecomp.sdc.be.components.impl;
+import static org.junit.Assert.assertSame;
+import static org.assertj.core.api.Assertions.assertThat;
import fj.data.Either;
-import mockit.Deencapsulation;
-import org.apache.commons.lang3.tuple.ImmutablePair;
+
+import java.util.*;
+
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
-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.elements.*;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
-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.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-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.*;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
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.IComponentInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
import java.util.function.BiPredicate;
import static org.junit.Assert.assertTrue;
@@ -60,1078 +40,299 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
+
/**
- * The test suite designed for test functionality of
- * ComponentInstanceBusinessLogic class
+ * 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 IComponentInstanceOperation componentInstanceOperation;
- 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;
- private static BaseBusinessLogic baseBusinessLogic;
- private static ArtifactsBusinessLogic artifactsBusinessLogic;
- private static ToscaDataDefinition toscaDataDefinition;
-
- @Before
- public void init() {
- createMocks();
- setMocks();
- stubMethods();
- createComponents();
- 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.setComponentInstances(Arrays.asList(createComponentIstance("NodeA2"),createComponentIstance("NodeB2"),
- createComponentIstance(componentInstanceID)));
-
- component.addForwardingPath(createPath("path1", componentInstanceID, "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<>()));
- final ComponentInstance ci = new ComponentInstance();
- ci.setName(componentInstanceID);
- Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance(
- containerComponentID, containerComponentType, Either.left(ci));
- Assert.assertTrue(responseFormatEither.isLeft());
-
- }
-
- private ComponentInstance createComponentIstance(String path1) {
- ComponentInstance componentInstance = new ComponentInstance();
- componentInstance.setName(path1);
- return componentInstance;
- }
-
- @Test
- public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete() {
-
- ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services");
- String containerComponentID = "Service-comp";
- 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,
- 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) {
- 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);
- baseBusinessLogic = Mockito.mock(BaseBusinessLogic.class);
- userValidations = Mockito.mock(UserValidations.class);
- forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class);
- componentInstanceOperation = Mockito.mock(IComponentInstanceOperation.class);
- artifactsBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
- toscaDataDefinition = Mockito.mock(ToscaDataDefinition.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);
- Either<User, ActionStatus> eitherGetUser = Either.left(user);
- when(userAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
- when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false)))
- .thenReturn(Either.left(user));
- }
-
- private static void createComponents() {
- createRelation();
- createInstances();
- createService();
- createResource();
- }
-
- private static Component 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);
- return resource;
- }
-
- private static Component 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);
- return service;
- }
-
- private static ComponentInstance createInstances() {
- toInstance = new ComponentInstance();
- toInstance.setUniqueId(TO_INSTANCE_ID);
- toInstance.setComponentUid("uuuiiid");
- toInstance.setName("tests");
-
- 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);
- return toInstance;
- }
-
- 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);
- }
-
- ///////////////////////////////////////////////////////////////////////////////
- /////////////////////////////new test//////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////
-
-
- private ComponentInstanceBusinessLogic createTestSubject() {
- return componentInstanceBusinessLogic;
- }
-
-
-
-
-
- @Test
- public void testChangeServiceProxyVersion() throws Exception {
- ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- String containerComponentType = "";
- String containerComponentId = "";
- String serviceProxyId = "";
- String userId = user.getUserId();
- Either<ComponentInstance, ResponseFormat> result;
-
- // default test
- componentInstanceBusinessLogic = createTestSubject();
- result = componentInstanceBusinessLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId,
- userId);
- }
-
-
-
-
-
-
-
- @Test
- public void testCreateServiceProxy() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String containerComponentType = "";
- String containerComponentId = "";
- String userId = user.getUserId();
- ComponentInstance componentInstance = createInstances();
- Either<ComponentInstance, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.createServiceProxy(containerComponentType, containerComponentId, userId,
- componentInstance);
- }
-
-
-
-
-
- @Test
- public void testDeleteForwardingPathsRelatedTobeDeletedComponentInstance() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String containerComponentId = "";
- String componentInstanceId = "";
- ComponentTypeEnum containerComponentType = ComponentTypeEnum.RESOURCE;
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- Either<ComponentInstance, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
- containerComponentType, resultOp);
- }
-
-
- @Test
- public void testDeleteServiceProxy() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String containerComponentType = "";
- String containerComponentId = "";
- String serviceProxyId = "";
- String userId = user.getUserId();
- Either<ComponentInstance, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId);
- }
-
-
-
-
-
-
- @Test
- public void testGetComponentInstanceInputsByInputId() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component component = new Service();
- String inputId = "";
- List<ComponentInstanceInput> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getComponentInstanceInputsByInputId(component, inputId);
- }
-
-
-
- @Test
- public void testGetComponentInstancePropertiesByInputId() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component component = new Service();
- String inputId = "";
- List<ComponentInstanceProperty> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getComponentInstancePropertiesByInputId(component, inputId);
- }
-
-
- @Test
- public void testGetRelationById() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String componentId = "";
- String relationId = "";
- String userId = user.getUserId();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE_INSTANCE;
- Either<RequirementCapabilityRelDef, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getRelationById(componentId, relationId, userId, componentTypeEnum);
- }
-
-
-
-
-
- @Test
- public void testCreateComponentInstance_1() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String containerComponentParam = "";
- String containerComponentId = "";
- String userId = user.getUserId();
- ComponentInstance resourceInstance = null;
- boolean inTransaction = false;
- boolean needLock = false;
- Either<ComponentInstance,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, inTransaction, needLock);
- }
-
-
-
-
-
- @Test
- public void testCreateAndAssociateRIToRI() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
-
- String containerComponentParam = "";
- String containerComponentId = "";
- String userId = user.getUserId();
- CreateAndAssotiateInfo createAndAssotiateInfo = new CreateAndAssotiateInfo(null, null);
- Either<CreateAndAssotiateInfo,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.createAndAssociateRIToRI(containerComponentParam, containerComponentId, userId, createAndAssotiateInfo);
- }
-
- @Test
- public void testGetOriginComponentFromComponentInstance_1() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component compoent = createResource();
- String componentInstanceName = "";
- String origComponetId = compoent.getUniqueId();
- Either<Component, StorageOperationStatus> oldResourceRes = Either.left(compoent);
- when(toscaOperationFacade.getToscaFullElement(compoent.getUniqueId())).thenReturn(oldResourceRes);
- Either<Component,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getOriginComponentFromComponentInstance", new Object[]{componentInstanceName, origComponetId});
- }
-
-
- @Test
- public void testCreateComponentInstanceOnGraph() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- Component originComponent = null;
- ComponentInstance componentInstance = createInstances();
- Either<ComponentInstance,ResponseFormat> result;
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result2 = Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, containerComponent,componentInstance, false, user)).thenReturn(result2);
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createComponentInstanceOnGraph", new Object[]{containerComponent, containerComponent, componentInstance, user});
- }
-
- /*@Test
- public void testCreateComponentInstanceOnGraph2() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- containerComponent.setName("name");
- ComponentInstance componentInstance = createInstances();
- Either<ComponentInstance,ResponseFormat> result;
- ImmutablePair<Component, String> pair = new ImmutablePair<>(containerComponent,"");
-
-
-
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result2 = Either.left(pair);
- when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, containerComponent,componentInstance, false, user)).thenReturn(result2);
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createComponentInstanceOnGraph", new Object[]{containerComponent, containerComponent, componentInstance, user});
- }*/
-
- @Test
- public void testUpdateComponentInstanceMetadata() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String containerComponentParam = "";
- String containerComponentId = "";
- String componentInstanceId = "";
- String userId = user.getUserId();
- ComponentInstance componentInstance = createInstances();
- Either<ComponentInstance,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance);
- }
-
-
- @Test
- public void testUpdateComponentInstanceMetadata_1() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String containerComponentParam = "";
- String containerComponentId = "";
- String componentInstanceId = "";
- String userId = user.getUserId();
- ComponentInstance componentInstance = createInstances();
- boolean inTransaction = false;
- boolean needLock = false;
- boolean createNewTransaction = false;
- Either<ComponentInstance,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, inTransaction, needLock, createNewTransaction);
- }
-
-
-
-
-
- @Test
- public void testValidateParent() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- String nodeTemplateId = "";
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateParent", new Object[]{containerComponent, nodeTemplateId});
- }
-
-
- @Test
- public void testGetComponentType() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum containerComponentType = ComponentTypeEnum.RESOURCE;
- ComponentTypeEnum result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getComponentType", new Object[]{ComponentTypeEnum.class});
- }
-
-
-
- @Test
- public void testGetNewGroupName() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String oldPrefix = "";
- String newNormailzedPrefix = "";
- String qualifiedGroupInstanceName = "";
- String result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "getNewGroupName", new Object[]{oldPrefix, newNormailzedPrefix, qualifiedGroupInstanceName});
- }
-
-
- @Test
- public void testUpdateComponentInstanceMetadata_3() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentInstance oldComponentInstance = createInstances();
- ComponentInstance newComponentInstance = null;
- ComponentInstance result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updateComponentInstanceMetadata", new Object[]{oldComponentInstance, oldComponentInstance});
- }
-
-
- @Test
- public void testDeleteComponentInstance() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String containerComponentParam = "";
- String containerComponentId = "";
- String componentInstanceId = "";
- String userId = user.getUserId();
- Either<ComponentInstance,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.deleteComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId);
- }
-
-
- @Test
- public void testDeleteForwardingPaths() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component service = createService();
- String serviceId = service.getUniqueId();
- List<String> pathIdsToDelete = new ArrayList<>();
- Either<Set<String>,ResponseFormat> result;
-
- // Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
- when(toscaOperationFacade.getToscaElement(serviceId)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "deleteForwardingPaths", new Object[]{serviceId, pathIdsToDelete});
- }
-
-
- @Test
- public void testAssociateRIToRIOnGraph() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- boolean inTransaction = false;
- Either<RequirementCapabilityRelDef,ResponseFormat> result;
-
-
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> getResourceResult = Either.left(requirementDef);
- when(toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef)).thenReturn(getResourceResult);
-
- // default test
- testSubject=createTestSubject();result=testSubject.associateRIToRIOnGraph(containerComponent, requirementDef, componentTypeEnum, inTransaction);
- }
-
-
-
- @Test
- public void testFindRelation() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String relationId = "";
- List<RequirementCapabilityRelDef> requirementCapabilityRelations = new ArrayList<>();
- RequirementCapabilityRelDef result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findRelation", new Object[]{relationId, requirementCapabilityRelations});
- }
-
-
- @Test
- public void testIsNetworkRoleServiceProperty() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentInstanceProperty property = new ComponentInstanceProperty();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isNetworkRoleServiceProperty", new Object[]{property, componentTypeEnum});
- }
-
-
- @Test
- public void testConcatServiceNameToVLINetworkRolePropertiesValues() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ToscaOperationFacade toscaOperationFacade = new ToscaOperationFacade();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- String componentId = "";
- String resourceInstanceId = "";
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- StorageOperationStatus result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "concatServiceNameToVLINetworkRolePropertiesValues", new Object[]{toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties});
- }
-
-
- @Test
- public void testCreateOrUpdatePropertiesValues() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component component = createResource();
- String componentId = component.getUniqueId();
- String resourceInstanceId = "";
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- String userId = user.getUserId();
- Either<List<ComponentInstanceProperty>,ResponseFormat> result;
-
- // Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(component));
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties, userId);
-
- componentTypeEnum =null;
- result=testSubject.createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties, userId);
-
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- result=testSubject.createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties, userId);
-
- }
-
-
- @Test
- public void testUpdateCapabilityPropertyOnContainerComponent() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentInstanceProperty property = new ComponentInstanceProperty();
- String newValue = "";
- Component containerComponent = createResource();
- ComponentInstance foundResourceInstance = createInstances();
- String capabilityType = "";
- String capabilityName = "";
- ResponseFormat result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updateCapabilityPropertyOnContainerComponent", new Object[]{property, newValue, containerComponent, foundResourceInstance, capabilityType, capabilityName});
- }
-
-
-
- @Test
- public void testCreateOrUpdateInstanceInputValues() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component resource = createResource();
- String componentId = resource.getUniqueId();
- String resourceInstanceId = "";
- List<ComponentInstanceInput> inputs = new ArrayList<>();
- String userId = user.getUserId();
- Either<List<ComponentInstanceInput>,ResponseFormat> result;
-
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(resource));
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs, userId);
- componentTypeEnum =null;
- result=testSubject.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs, userId);
-
-
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- result=testSubject.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs, userId);
-
- }
-
-
- @Test
- public void testCreateOrUpdateGroupInstancePropertyValue() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component resource = createResource();
- String componentId = resource.getUniqueId();
- String resourceInstanceId = "";
- String groupInstanceId = "";
- ComponentInstanceProperty property = new ComponentInstanceProperty();
- String userId = user.getUserId();
- Either<ComponentInstanceProperty,ResponseFormat> result;
-
-
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(resource));
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId, groupInstanceId, property, userId);
- componentTypeEnum = null;
- result=testSubject.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId, groupInstanceId, property, userId);
-
- when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- result=testSubject.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId, groupInstanceId, property, userId);
- }
-
-
- @Test
- public void testCreateOrUpdateInputValue() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component component = createResource();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- String componentId = component.getUniqueId();
- String resourceInstanceId = component.getUniqueId();
- ComponentInstanceInput inputProperty = new ComponentInstanceInput();
- String userId = user.getUserId();
- Either<ComponentInstanceInput,ResponseFormat> result;
-
-
- Either<Component, StorageOperationStatus> getResourceResult = Either.left(component);
- when(toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata)).thenReturn(getResourceResult);
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.createOrUpdateInputValue(componentTypeEnum, componentId, resourceInstanceId, inputProperty, userId);
-
- componentTypeEnum = null;
- result=testSubject.createOrUpdateInputValue(componentTypeEnum, componentId, resourceInstanceId, inputProperty, userId);
-
- when(toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- result=testSubject.createOrUpdateInputValue(componentTypeEnum, componentId, resourceInstanceId, inputProperty, userId);
- }
-
-
- @Test
- public void testDeletePropertyValue() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component service = createService();
- String serviceId = service.getUniqueId();
- String resourceInstanceId = "";
- String propertyValueId = "";
- String userId = user.getUserId();
- Either<ComponentInstanceProperty,ResponseFormat> result;
-
- when(toscaOperationFacade.getToscaElement(serviceId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(service));
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId, userId);
- componentTypeEnum= null;
- result=testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId, userId);
-
- when(toscaOperationFacade.getToscaElement(serviceId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- result=testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId, userId);
- }
-
-
- @Test
- public void testGetAndValidateOriginComponentOfComponentInstance() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum containerComponentType = ComponentTypeEnum.RESOURCE;
- Component resource = createResource();
- ComponentInstance componentInstance = createInstances();
- Either<Component,ResponseFormat> result;
-
- when(toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid())).thenReturn(Either.left(resource));
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getAndValidateOriginComponentOfComponentInstance", new Object[]{containerComponentType, componentInstance});
- }
-
-
-
-
-
- @Test
- public void testGetComponentParametersViewForForwardingPath() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentParametersView result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getComponentParametersViewForForwardingPath");
- }
-
-
- @Test
- public void testChangeComponentInstanceVersion() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- String containerComponentParam = "";
- String containerComponentId = "";
- String componentInstanceId = "";
- String userId = user.getUserId();
- ComponentInstance newComponentInstance = createInstances();
- Either<ComponentInstance,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.changeComponentInstanceVersion(containerComponentParam, containerComponentId, componentInstanceId, userId, newComponentInstance);
- newComponentInstance = null;
- testSubject=createTestSubject();result=testSubject.changeComponentInstanceVersion(containerComponentParam, containerComponentId, componentInstanceId, userId, newComponentInstance);
-
- }
-
- @Test
- public void testValidateInstanceNameUniquenessUponUpdate() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- ComponentInstance oldComponentInstance = createInstances();
- String newInstanceName = oldComponentInstance.getName();
- Boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateInstanceNameUniquenessUponUpdate", new Object[]{containerComponent, oldComponentInstance, newInstanceName});
- }
-
-
- @Test
- public void testGetResourceInstanceById() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- Component containerComponent = createResource();
- String instanceId = "";
- Either<ComponentInstance,StorageOperationStatus> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getResourceInstanceById", new Object[]{containerComponent, instanceId});
- }
-
-
- @Test
- public void testBuildComponentInstance() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentInstance resourceInstanceForUpdate = createInstances();
- ComponentInstance origInstanceForUpdate = null;
- ComponentInstance result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "buildComponentInstance", new Object[]{resourceInstanceForUpdate, resourceInstanceForUpdate});
- }
-
-
-
-
-
- @Test
- public void testFindCapabilityOfInstance() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String componentId = "";
- String instanceId = "";
- String capabilityType = "";
- String capabilityName = "";
- String ownerId = "";
- Map<String,List<CapabilityDefinition>> instanceCapabilities = new HashMap<>();
- Either<List<ComponentInstanceProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findCapabilityOfInstance", new Object[]{componentId, instanceId, capabilityType, capabilityName, ownerId, instanceCapabilities});
- }
-
-
- @Test
- public void testFetchComponentInstanceCapabilityProperties() throws Exception {
- ComponentInstanceBusinessLogic testSubject;String componentId = "";
- String instanceId = "";
- String capabilityType = "";
- String capabilityName = "";
- String ownerId = "";
- Either<List<ComponentInstanceProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "fetchComponentInstanceCapabilityProperties", new Object[]{componentId, instanceId, capabilityType, capabilityName, ownerId});
- }
-
-
- @Test
- public void testUpdateCapabilityPropertyOnContainerComponent_1() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentInstanceProperty property = new ComponentInstanceProperty();
- String newValue = "";
- Component containerComponent = createResource();
- ComponentInstance foundResourceInstance = createInstances();
- String capabilityType = "";
- String capabilityName = "";
- String ownerId = "";
- ResponseFormat result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updateCapabilityPropertyOnContainerComponent", new Object[]{property, newValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId});
- }
-
-
- @Test
- public void testUpdateInstanceCapabilityProperties() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component resource = createResource();
- String containerComponentId = resource.getUniqueId();
- String componentInstanceUniqueId = "";
- String capabilityType = "";
- String capabilityName = "";
- String ownerId = "";
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- String userId = user.getUserId();
- Either<List<ComponentInstanceProperty>,ResponseFormat> result;
-
-
- when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.left(resource));
-
-
-
- // test 1
- testSubject=createTestSubject();
- result=testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, properties, userId);
- when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND));
- result=testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, properties, userId);
- componentTypeEnum = null;
- result=testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, properties, userId);
-
-
- }
-
-
- @Test
- public void testUpdateInstanceCapabilityProperties_1() throws Exception {
- ComponentInstanceBusinessLogic testSubject;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- Component component = createResource();
- String containerComponentId = component.getUniqueId();
- String componentInstanceUniqueId = "";
- String capabilityType = "";
- String capabilityName = "";
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- String userId = user.getUserId();
- Either<List<ComponentInstanceProperty>,ResponseFormat> result;
-
-
- when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- // test 1
- testSubject=createTestSubject();
- result=testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
- when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.left(component));
- result=testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
- }
+@RunWith(MockitoJUnitRunner.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";
+
+ @InjectMocks
+ private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private ServletUtils servletUtils;
+ @Mock
+ private ResponseFormat responseFormat;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Mock
+ private UserBusinessLogic userAdmin;
+ @Mock
+ private ForwardingPathOperation forwardingPathOperation;
+ @Mock
+ private User user;
+ @Mock
+ private UserValidations userValidations;
+ private Component service;
+ private Component resource;
+ private ComponentInstance toInstance;
+ private ComponentInstance fromInstance;
+ private CapabilityDataDefinition capability;
+ private RequirementDataDefinition requirement;
+ private RequirementCapabilityRelDef relation;
+
+
+ @Before
+ public void init(){
+ 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);
+ }
+
+ @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.setName(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));
+ 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.setComponentInstances(Arrays.asList(createComponentIstance("NodeA2"),createComponentIstance("NodeB2"),
+ createComponentIstance(componentInstanceID)));
+
+ component.addForwardingPath(createPath("path1", componentInstanceID, "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<>()));
+ final ComponentInstance ci = new ComponentInstance();
+ ci.setName(componentInstanceID);
+ Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance(
+ containerComponentID, containerComponentType, Either.left(ci));
+ assertThat(responseFormatEither.isLeft()).isEqualTo(true);
+
+ }
+
+ private ComponentInstance createComponentIstance(String path1) {
+ ComponentInstance componentInstance = new ComponentInstance();
+ componentInstance.setName(path1);
+ return componentInstance;
+ }
+
+ 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<Component, StorageOperationStatus> getComponentRes = Either.left(component);
+ 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.isLeft());
+ }
+
+ private void getServiceRelationByIdUserValidationFailure(Component component){
+ when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenThrow(new ComponentException(ActionStatus.USER_NOT_FOUND));
+ try{
+ componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
+ } catch(ComponentException e){
+ assertSame(e.getActionStatus(), ActionStatus.USER_NOT_FOUND);
+ }
+ }
+
+ private void getRelationByIdComponentNotFoundFailure(Component component){
+ Either<User, ActionStatus> eitherCreator = Either.left(user);
+ 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 void stubMethods() {
+ when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(user);
+ }
+
+ private void createComponents() {
+ createRelation();
+ createInstances();
+ createService();
+ createResource();
+ }
+
+ private 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);
+ resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+
+ private 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);
+ service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+
+ private 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 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
index 7ecd069448..f3fa747901 100644
--- 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
@@ -1,45 +1,5 @@
package org.openecomp.sdc.be.components.impl;
-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;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -50,26 +10,27 @@ 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.auditing.impl.externalapi.AuditChangeLifecycleExternalApiEventFactory;
+import org.openecomp.sdc.be.auditing.impl.externalapi.AuditCreateResourceExternalApiEventFactory;
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.model.*;
+import org.openecomp.sdc.be.resources.data.auditing.*;
import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
+import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.exception.ResponseFormat;
+import javax.servlet.http.HttpServletRequest;
+
+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.*;
+
@RunWith(MockitoJUnitRunner.class)
public class ComponentsUtilsTest {
@@ -79,12 +40,15 @@ public class ComponentsUtilsTest {
@Mock
private AuditingManager manager;
-
@Mock
private ResponseFormat responseFormat;
+ @Mock
+ private HttpServletRequest request;
+
+ private ArtifactDefinition artifactDefinition = null;
@Captor
- private ArgumentCaptor<AuditBaseEventFactory> factoryCaptor;
+ private ArgumentCaptor<AuditEventFactory> factoryCaptor;
@InjectMocks
private static ComponentsUtils utils;
@@ -110,20 +74,21 @@ public class ComponentsUtilsTest {
service.setUUID(SERVICE_INSTANCE_ID);
service.setInvariantUUID(INVARIANT_UUID);
- utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(),
- ResourceAuditData.newBuilder()
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE,
+ new ResourceCommonInfo(RESOURCE_NAME, service.getComponentType().getValue()),
+ ResourceVersionInfo.newBuilder()
.state(PREV_RESOURCE_STATE)
.version(PREV_RESOURCE_VERSION)
.artifactUuid(ARTIFACT_UUID)
.distributionStatus(DPREV_STATUS).build(),
- ResourceAuditData.newBuilder()
+ ResourceVersionInfo.newBuilder()
.state(CURRENT_STATE)
.version(CURRENT_VERSION)
.artifactUuid(ARTIFACT_UUID)
.distributionStatus(DCURR_STATUS).build(),
- RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID);
+ COMMENT, artifactDefinition, DIST_ID);
verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(),
- false, true, true, true, true, true);
+ false, true, true, false, true, true, true);
}
@Test
@@ -135,18 +100,19 @@ public class ComponentsUtilsTest {
service.setInvariantUUID(INVARIANT_UUID);
service.setState(LifecycleStateEnum.CERTIFIED);
service.setVersion(CURRENT_VERSION);
- utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(),
- ResourceAuditData.newBuilder()
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE,
+ new ResourceCommonInfo(RESOURCE_NAME, service.getComponentType().getValue()),
+ ResourceVersionInfo.newBuilder()
.state(PREV_RESOURCE_STATE)
.version(PREV_RESOURCE_VERSION)
.artifactUuid(ARTIFACT_UUID)
.distributionStatus(DPREV_STATUS).build(),
- ResourceAuditData.newBuilder()
+ ResourceVersionInfo.newBuilder()
.artifactUuid(ARTIFACT_UUID)
.distributionStatus(DCURR_STATUS).build(),
- RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID);
+ COMMENT, artifactDefinition, DIST_ID);
verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(),
- false, true, true, true, true, true);
+ false, true, true, false, true, true, true);
}
@@ -160,18 +126,19 @@ public class ComponentsUtilsTest {
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()
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
+ new ResourceCommonInfo(service.getComponentType().getValue()),
+ ResourceVersionInfo.newBuilder()
.state(PREV_RESOURCE_STATE)
.version(PREV_RESOURCE_VERSION)
.artifactUuid(ARTIFACT_UUID)
.distributionStatus(DPREV_STATUS).build(),
- ResourceAuditData.newBuilder()
+ ResourceVersionInfo.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);
+ false, true, true, false, false, true, false);
}
@Test
@@ -186,10 +153,10 @@ public class ComponentsUtilsTest {
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());
+ new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.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);
+ service.getComponentType().getValue(), false, true, false, false, false, false, false);
}
@Test
@@ -198,9 +165,9 @@ public class ComponentsUtilsTest {
when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE,
- RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT);
+ new ResourceCommonInfo(RESOURCE_NAME, ComponentTypeEnum.SERVICE.getValue()), COMMENT);
verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(),
- true, false, false, false, true, false);
+ true, false, false, false, true, false, false);
}
@Test
@@ -215,7 +182,7 @@ public class ComponentsUtilsTest {
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);
+ false, false, false, false, false, false, false);
}
@Test
@@ -230,14 +197,14 @@ public class ComponentsUtilsTest {
resource.setVersion(CURRENT_VERSION);
resource.setToscaResourceName(TOSCA_NODE_TYPE);
utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceAuditData.newBuilder()
+ ResourceVersionInfo.newBuilder()
.state(PREV_RESOURCE_STATE)
.version(PREV_RESOURCE_VERSION)
.artifactUuid(ARTIFACT_UUID)
.build(),
- ARTIFACT_UUID, ARTIFACT_DATA);
+ ARTIFACT_UUID, artifactDefinition);
verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(),
- false, true, true, true, false, false);
+ false, true, true, false, false, false, false);
}
@Test
@@ -253,7 +220,7 @@ public class ComponentsUtilsTest {
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);
+ false, false, false, false, false, false, false);
}
@Test
@@ -263,7 +230,7 @@ public class ComponentsUtilsTest {
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);
+ true, false, false, false, false, false, false);
}
@Test
@@ -325,7 +292,7 @@ public class ComponentsUtilsTest {
private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull,
boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided,
- boolean isDistStatusProvided) {
+ boolean isDistStatusProvided, boolean isDidProvided) {
verify(manager).auditEvent(factoryCaptor.capture());
AuditEventFactory factory = factoryCaptor.getValue();
ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent();
@@ -373,15 +340,14 @@ public class ComponentsUtilsTest {
}
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.getArtifactData()).isEmpty();
+ }
+ if (isDidProvided) {
+ assertThat(event.getDid()).isEqualTo(DIST_ID);
+ }
+ else {
assertThat(event.getDid()).isNull();
}
if (isCommentProvided) {
@@ -399,4 +365,262 @@ public class ComponentsUtilsTest {
assertThat(event.getDprevStatus()).isNull();
}
}
+
+ @Test
+ public void auditChangeLifeCycleExternalApiEventWhenComponentAndResponseObjectAreNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ utils.auditChangeLifecycleAction(responseFormat, ComponentTypeEnum.RESOURCE, REQUEST_ID,
+ null, null, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL), modifier);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditChangeLifecycleExternalApiEventFactory factory = (AuditChangeLifecycleExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+ verifyCommonDataForExternalApiEvent(event, false);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyCurrentResourceVersionInfoForExternalApiEvent(event, true);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getInvariantUuid()).isEmpty();
+ assertThat(event.getResourceName()).isNull();
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void auditChangeLifeCycleExternalApiEventWhenComponentIsNullAndResponseObjectIsNotNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+ Component responseObject = new Resource();
+ responseObject.setVersion(CURRENT_VERSION);
+ responseObject.setState(LifecycleStateEnum.CERTIFIED);
+ responseObject.setInvariantUUID(INVARIANT_UUID);
+ responseObject.setUUID(SERVICE_INSTANCE_ID);
+
+ utils.auditChangeLifecycleAction(responseFormat, ComponentTypeEnum.RESOURCE, REQUEST_ID,
+ null, responseObject, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL), modifier);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditChangeLifecycleExternalApiEventFactory factory = (AuditChangeLifecycleExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+ verifyCommonDataForExternalApiEvent(event, true);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyCurrentResourceVersionInfoForExternalApiEvent(event, false);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getInvariantUuid()).isEqualTo(INVARIANT_UUID);
+ assertThat(event.getResourceName()).isNull();
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void auditChangeLifeCycleExternalApiEventWhenComponentIsNotNullAndResponseObjectIsNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+ Component component = new Resource();
+ component.setVersion(PREV_RESOURCE_VERSION);
+ component.setState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ component.setInvariantUUID(INVARIANT_UUID);
+ component.setName(RESOURCE_NAME);
+
+ utils.auditChangeLifecycleAction(responseFormat, ComponentTypeEnum.RESOURCE, REQUEST_ID,
+ component, null, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL), modifier);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditChangeLifecycleExternalApiEventFactory factory = (AuditChangeLifecycleExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+
+ verifyCommonDataForExternalApiEvent(event, false);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, false);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getInvariantUuid()).isEqualTo(INVARIANT_UUID);
+ assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void auditChangeLifeCycleExternalApiEventWhenComponentAndResponseObjectAreNotNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+ Component responseObject = new Resource();
+ responseObject.setVersion(CURRENT_VERSION);
+ responseObject.setState(LifecycleStateEnum.CERTIFIED);
+ responseObject.setInvariantUUID(INVARIANT_UUID);
+ responseObject.setUUID(SERVICE_INSTANCE_ID);
+
+ Component component = new Resource();
+ component.setVersion(PREV_RESOURCE_VERSION);
+ component.setState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ component.setInvariantUUID(INVARIANT_UUID);
+ component.setUUID(SERVICE_INSTANCE_ID);
+ component.setName(RESOURCE_NAME);
+
+ utils.auditChangeLifecycleAction(responseFormat, ComponentTypeEnum.RESOURCE, REQUEST_ID,
+ null, responseObject, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL), modifier);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditChangeLifecycleExternalApiEventFactory factory = (AuditChangeLifecycleExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+ verifyCommonDataForExternalApiEvent(event, true);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyCurrentResourceVersionInfoForExternalApiEvent(event, false);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getInvariantUuid()).isEqualTo(INVARIANT_UUID);
+ assertThat(event.getResourceName()).isNull();
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+
+ }
+
+ private void verifyDistributionDataForExternalApiEvent(ExternalApiEvent event) {
+ assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(event.getResourceURL()).isEqualTo(DIST_RESOURCE_URL);
+ }
+
+ private void verifyDistributionDataNotSetForExternalApiEvent(ExternalApiEvent event) {
+ assertThat(event.getConsumerId()).isNull();
+ assertThat(event.getResourceURL()).isNull();
+ }
+
+ private void verifyCommonDataForExternalApiEvent(ExternalApiEvent event, boolean isSucceeded) {
+ if (isSucceeded) {
+ assertThat(event.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(event.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ }
+ else {
+ assertThat(event.getDesc()).isEqualTo(DESC_ERROR);
+ assertThat(event.getStatus()).isEqualTo(STATUS_500);
+ assertThat(event.getServiceInstanceId()).isNullOrEmpty();
+ }
+ assertThat(event.getRequestId()).isEqualTo(REQUEST_ID);
+ }
+
+ private void verifyCurrentResourceVersionInfoForExternalApiEvent(ExternalApiEvent event, boolean isNull) {
+ assertThat(event.getCurrArtifactUuid()).isNull();
+ if (isNull) {
+ assertThat(event.getCurrState()).isNull();
+ assertThat(event.getCurrVersion()).isNull();
+ }
+ else {
+ assertThat(event.getCurrState()).isEqualTo(LifecycleStateEnum.CERTIFIED.name());
+ assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ }
+ }
+
+ private void verifyPreviousResourceVersionInfoForExternalApiEvent(ExternalApiEvent event, boolean isNull) {
+ assertThat(event.getPrevArtifactUuid()).isNull();
+ if (isNull) {
+ assertThat(event.getPrevState()).isNull();
+ assertThat(event.getPrevVersion()).isNull();
+ }
+ else {
+ assertThat(event.getPrevState()).isEqualTo(LifecycleStateEnum.READY_FOR_CERTIFICATION.name());
+ assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION);
+ }
+ }
+
+ @Test
+ public void auditExternalCreateResourceEventWhenResourceObjectIsNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(USER_ID);
+ when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn(DIST_CONSUMER_ID);
+ when(request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(REQUEST_ID);
+ when(request.getRequestURI()).thenReturn(DIST_RESOURCE_URL);
+
+ utils.auditCreateResourceExternalApi(responseFormat, new ResourceCommonInfo(RESOURCE_NAME, ComponentTypeEnum.RESOURCE.getValue()),
+ request, null);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditCreateResourceExternalApiEventFactory factory = (AuditCreateResourceExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ verifyCommonDataForExternalApiEvent(event, false);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyCurrentResourceVersionInfoForExternalApiEvent(event, true);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEqualTo("(" + USER_ID + ")");
+ assertThat(event.getInvariantUuid()).isNull();
+ assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void auditExternalCreateResourceEventWhenResourceObjectIsNullAndRequestDataIsNotProvided() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(null);
+ when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn(null);
+ when(request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(REQUEST_ID);
+ when(request.getRequestURI()).thenReturn(null);
+
+ utils.auditCreateResourceExternalApi(responseFormat, new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue()),
+ request, null);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditCreateResourceExternalApiEventFactory factory = (AuditCreateResourceExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ verifyCommonDataForExternalApiEvent(event, false);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyCurrentResourceVersionInfoForExternalApiEvent(event, true);
+ verifyDistributionDataNotSetForExternalApiEvent(event);
+ assertThat(event.getModifier()).isEmpty();
+ assertThat(event.getInvariantUuid()).isNull();
+ assertThat(event.getResourceName()).isNull();
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void auditExternalCreateResourceEventWhenResourceObjectAndRequestDataProvided() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(USER_ID);
+ when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn(DIST_CONSUMER_ID);
+ when(request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(REQUEST_ID);
+ when(request.getRequestURI()).thenReturn(DIST_RESOURCE_URL);
+
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.setInvariantUUID(INVARIANT_UUID);
+ resource.setUUID(SERVICE_INSTANCE_ID);
+
+ utils.auditCreateResourceExternalApi(responseFormat, new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue()),
+ request, resource);
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditCreateResourceExternalApiEventFactory factory = (AuditCreateResourceExternalApiEventFactory)factoryCaptor.getValue();
+
+ ExternalApiEvent event = (ExternalApiEvent)factory.getDbEvent();
+ verifyCommonDataForExternalApiEvent(event, true);
+ verifyPreviousResourceVersionInfoForExternalApiEvent(event, true);
+ verifyDistributionDataForExternalApiEvent(event);
+ assertThat(event.getCurrArtifactUuid()).isNull();
+ assertThat(event.getCurrState()).isEqualTo(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ assertThat(event.getCurrVersion()).isEqualTo(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+ assertThat(event.getModifier()).isEqualTo("(" + USER_ID + ")");
+ assertThat(event.getInvariantUuid()).isEqualTo(INVARIANT_UUID);
+ assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(event.getResourceType()).isEqualTo(ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void checkIfAuditEventIsExternal() {
+ assertThat(utils.isExternalApiEvent(AuditingActionEnum.ARTIFACT_UPLOAD_BY_API)).isTrue();
+ assertThat(utils.isExternalApiEvent(AuditingActionEnum.ARTIFACT_UPLOAD)).isFalse();
+ }
+
}
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 5797516938..23363bef47 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,15 +20,6 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Test;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
@@ -37,6 +28,13 @@ 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.*;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
public class CompositionBusinessLogicTest {
CompositionBusinessLogic compBl = new CompositionBusinessLogic();
@@ -48,7 +46,7 @@ public class CompositionBusinessLogicTest {
FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance());
}
Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF);
- assertTrue(componentInstances.size() == instancesNum);
+ assertEquals(componentInstances.size(), instancesNum);
// Verify Spiral Pattern
ImmutablePair<Double, Double> key;
key = new ImmutablePair<>(0D, 0D);
@@ -80,11 +78,11 @@ public class CompositionBusinessLogicTest {
ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF);
Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF);
- assertTrue(cpsConnectedToVFC.size() == 1);
+ assertEquals(1, cpsConnectedToVFC.size());
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));
+ assertEquals(3, cps.size());
+ cps.stream().forEach(e -> assertSame(e.getOriginType(), OriginTypeEnum.CP));
}
@@ -96,16 +94,16 @@ public class CompositionBusinessLogicTest {
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);
+ componentInstLocations.put(new ImmutablePair<>(0D, 0D), vfcInstance);
compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC);
- assertTrue(componentInstLocations.size() == 4);
+ assertEquals(4, componentInstLocations.size());
- Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet());
+ Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(Map.Entry::getKey).collect(Collectors.toSet());
// Verify that all cps are located at different positions
- assertTrue(cpsLocations.size() == 3);
+ assertEquals(3, cpsLocations.size());
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);
+ assertEquals(1, distances.size());
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java
deleted file mode 100644
index db95ee8827..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package org.openecomp.sdc.be.components.impl;
-
-import org.junit.Test;
-import org.openecomp.sdc.be.model.ConsumerDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import fj.data.Either;
-
-
-public class ConsumerBusinessLogicTest {
-
- private ConsumerBusinessLogic createTestSubject() {
- return new ConsumerBusinessLogic();
- }
-
-
- @Test
- public void testCreateConsumer() throws Exception {
- ConsumerBusinessLogic testSubject;
- User user = null;
- ConsumerDefinition consumer = null;
- Either<ConsumerDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-
-
- @Test
- public void testGetConsumer() throws Exception {
- ConsumerBusinessLogic testSubject;
- String consumerId = "";
- User user = null;
- Either<ConsumerDefinition, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- user = null;
- }
-
-
- @Test
- public void testGetConsumer_1() throws Exception {
- ConsumerBusinessLogic testSubject;
- String consumerId = "";
- Either<ConsumerDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testDeleteConsumer() throws Exception {
- ConsumerBusinessLogic testSubject;
- String consumerId = "";
- User user = null;
- Either<ConsumerDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUpdateConsumer() throws Exception {
- ConsumerBusinessLogic testSubject;
- ConsumerDefinition consumer = null;
- User modifier = null;
- boolean isCreateRequest = false;
- Either<ConsumerDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-} \ No newline at end of file
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 3c283ac3e8..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,11 +20,11 @@
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" };
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
index f81e1444cc..ccdbfda312 100644
--- 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
@@ -1,13 +1,6 @@
package org.openecomp.sdc.be.components.impl;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-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.Test;
@@ -37,7 +30,13 @@ 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 fj.data.Either;
+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.
@@ -132,7 +131,7 @@ public class ElementBLTest {
.thenReturn(Either.left(notDeletedService));
Either<List<Object>, StorageOperationStatus> elementsByCategoryEither =
- elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(),
+ elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory,
NodeTypeEnum.Service, false, ServiceMetadataData.class, null);
List<Object> elementsByCategory = elementsByCategoryEither.left().value();
@@ -158,7 +157,7 @@ public class ElementBLTest {
.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);
+ 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/ElementBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java
deleted file mode 100644
index bcde49295e..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java
+++ /dev/null
@@ -1,332 +0,0 @@
-package org.openecomp.sdc.be.components.impl;
-
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Test;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.PropertyScope;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.ui.model.UiCategories;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import fj.data.Either;
-
-
-public class ElementBusinessLogicTest {
-
- private ElementBusinessLogic createTestSubject() {
- return new ElementBusinessLogic();
- }
-
-
- @Test
- public void testGetFollowed() throws Exception {
- ElementBusinessLogic testSubject;
- User user = null;
- Either<Map<String, List<? extends Component>>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-
- @Test
- public void testGetAllResourceCategories() throws Exception {
- ElementBusinessLogic testSubject;
- Either<List<CategoryDefinition>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetAllServiceCategories() throws Exception {
- ElementBusinessLogic testSubject;
- Either<List<CategoryDefinition>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testCreateCategory() throws Exception {
- ElementBusinessLogic testSubject;
- CategoryDefinition category = null;
- String componentTypeParamName = "";
- String userId = "";
- Either<CategoryDefinition, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- category = null;
- }
-
-
- @Test
- public void testCreateSubCategory() throws Exception {
- ElementBusinessLogic testSubject;
- SubCategoryDefinition subCategory = null;
- String componentTypeParamName = "";
- String parentCategoryId = "";
- String userId = "";
- Either<SubCategoryDefinition, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- subCategory = null;
- }
-
-
- @Test
- public void testCreateGrouping() throws Exception {
- ElementBusinessLogic testSubject;
- GroupingDefinition grouping = null;
- String componentTypeParamName = "";
- String grandParentCategoryId = "";
- String parentSubCategoryId = "";
- String userId = "";
- Either<GroupingDefinition, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- grouping = null;
- }
-
-
- @Test
- public void testGetAllCategories() throws Exception {
- ElementBusinessLogic testSubject;
- String componentType = "";
- String userId = "";
- Either<List<CategoryDefinition>, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- userId = null;
-
- // test 2
- testSubject = createTestSubject();
- userId = "";
- }
-
-
- @Test
- public void testGetAllCategories_1() throws Exception {
- ElementBusinessLogic testSubject;
- String userId = "";
- Either<UiCategories, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testDeleteCategory() throws Exception {
- ElementBusinessLogic testSubject;
- String categoryId = "";
- String componentTypeParamName = "";
- String userId = "";
- Either<CategoryDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testDeleteSubCategory() throws Exception {
- ElementBusinessLogic testSubject;
- String grandParentCategoryId = "";
- String parentSubCategoryId = "";
- String componentTypeParamName = "";
- String userId = "";
- Either<SubCategoryDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testDeleteGrouping() throws Exception {
- ElementBusinessLogic testSubject;
- String grandParentCategoryId = "";
- String parentSubCategoryId = "";
- String groupingId = "";
- String componentTypeParamName = "";
- String userId = "";
- Either<GroupingDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-
- @Test
- public void testGetAllPropertyScopes() throws Exception {
- ElementBusinessLogic testSubject;
- String userId = "";
- Either<List<PropertyScope>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetAllArtifactTypes() throws Exception {
- ElementBusinessLogic testSubject;
- String userId = "";
- Either<List<ArtifactType>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetAllDeploymentArtifactTypes() throws Exception {
- ElementBusinessLogic testSubject;
- Either<Map<String, Object>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetDefaultHeatTimeout() throws Exception {
- ElementBusinessLogic testSubject;
- Either<Integer, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetCatalogComponents() throws Exception {
- ElementBusinessLogic testSubject;
- String userId = "";
- List<OriginTypeEnum> excludeTypes = null;
- Either<Map<String, List<? extends Component>>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetFilteredCatalogComponents() throws Exception {
- ElementBusinessLogic testSubject;
- String assetType = "";
- Map<FilterKeyEnum, String> filters = null;
- String query = "";
- Either<List<? extends Component>, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- query = null;
-
- // test 2
- testSubject = createTestSubject();
- query = "";
-
- // test 3
- testSubject = createTestSubject();
- filters = null;
- }
-
-
-
-
- @Test
- public void testGetCatalogComponentsByUuidAndAssetType() throws Exception {
- ElementBusinessLogic testSubject;
- String assetType = "";
- String uuid = "";
- Either<List<? extends Component>, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- assetType = null;
-
- // test 2
- testSubject = createTestSubject();
- assetType = "";
-
- // test 3
- testSubject = createTestSubject();
- assetType = null;
-
- // test 4
- testSubject = createTestSubject();
- assetType = "";
- }
-
-
- @Test
- public void testGetAllComponentTypesParamNames() throws Exception {
- ElementBusinessLogic testSubject;
- List<String> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAllComponentTypesParamNames();
- }
-
-
- @Test
- public void testGetAllSupportedRoles() throws Exception {
- ElementBusinessLogic testSubject;
- List<String> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAllSupportedRoles();
- }
-
-
- @Test
- public void testGetResourceTypesMap() throws Exception {
- ElementBusinessLogic testSubject;
- Either<Map<String, String>, ActionStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-
-
- @Test
- public void testGetFilteredResouces() throws Exception {
- ElementBusinessLogic testSubject;
- Map<FilterKeyEnum, String> filters = null;
- boolean inTransaction = false;
- Either<List<Component>, StorageOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
-} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java
deleted file mode 100644
index d9ca7b06c2..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java
+++ /dev/null
@@ -1,767 +0,0 @@
-package org.openecomp.sdc.be.components.impl;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Test;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
-import org.openecomp.sdc.be.info.GroupDefinitionInfo;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import com.google.common.base.Function;
-
-import fj.data.Either;
-
-
-public class GroupBusinessLogicTest {
-
- private GroupBusinessLogic createTestSubject() {
- return new GroupBusinessLogic();
- }
-
-
- @Test
- public void testGetComponentTypeForResponse() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- String result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testVerifyArtifactsBelongsToComponent() throws Exception {
- GroupBusinessLogic testSubject;Component component = null;
- List<String> artifacts = null;
- String context = "";
- Either<Boolean,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();artifacts = null;
-
-
- }
-
-
- @Test
- public void testVerifyComponentInstancesAreValidMembers() throws Exception {
- GroupBusinessLogic testSubject;Component component = null;
- ComponentTypeEnum componentType = null;
- String groupName = "";
- String groupType = "";
- Map<String,String> groupMembers = null;
- List<String> memberToscaTypes = null;
- Either<Boolean,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();groupMembers = null;
-
-
-
- // test 2
- testSubject=createTestSubject();memberToscaTypes = null;
-
-
- }
-
-
- @Test
- public void testValidateAndUpdateGroupMetadata() throws Exception {
- GroupBusinessLogic testSubject;
- String componentId = "";
- User user = null;
- ComponentTypeEnum componentType = null;
- GroupDefinition updatedGroup = null;
- boolean inTransaction = false;
- boolean shouldLock = false;
- Either<GroupDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testUpdateGroupMetadata() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- GroupDefinition currentGroup = null;
- GroupDefinition updatedGroup = null;
- Either<GroupDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testUpdateGroup() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- GroupDefinition updatedGroup = null;
- String currentGroupName = "";
- Either<GroupDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateGroupProperties() throws Exception {
- GroupBusinessLogic testSubject;
- String componentId = "";
- String groupUniqueId = "";
- User user = null;
- ComponentTypeEnum componentType = null;
- List<GroupProperty> groupPropertiesToUpdate = null;
- boolean inTransaction = false;
- Either<List<GroupProperty>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testResetEmptyValueWithDefaults() throws Exception {
- GroupBusinessLogic testSubject;List<GroupProperty> groupPropertiesToUpdate = null;
- GroupDefinition originalGroup = null;
-
-
- // default test
- }
-
-
- @Test
- public void testValidateGroupPropertyAndResetEmptyValue() throws Exception {
- GroupBusinessLogic testSubject;GroupDefinition originalGroup = null;
- List<GroupProperty> groupPropertiesToUpdate = null;
- Either<List<GroupProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidatePropertyBusinessLogic() throws Exception {
- GroupBusinessLogic testSubject;List<GroupProperty> groupPropertiesToUpdate = null;
- GroupDefinition originalGroup = null;
- Either<List<GroupProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testPrepareMapWithOriginalProperties() throws Exception {
- GroupBusinessLogic testSubject;
- GroupDefinition originalGroup = null;
- Map<PropertyNames, String> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateOnlyValueChanged() throws Exception {
- GroupBusinessLogic testSubject;List<GroupProperty> groupPropertiesToUpdate = null;
- GroupDefinition originalGroup = null;
- Either<List<GroupProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testIsOnlyGroupPropertyValueChanged() throws Exception {
- GroupBusinessLogic testSubject;
- GroupProperty groupProperty = null;
- GroupProperty groupProperty2 = null;
- boolean result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateGroupMetadata_1() throws Exception {
- GroupBusinessLogic testSubject;
- GroupDefinition currentGroup = null;
- GroupDefinition groupUpdate = null;
- Either<GroupDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateGroupName() throws Exception {
- GroupBusinessLogic testSubject;
- GroupDefinition currentGroup = null;
- GroupDefinition groupUpdate = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateGroupName() throws Exception {
- GroupBusinessLogic testSubject;
- String currentGroupName = "";
- String groupUpdateName = "";
- boolean isforceNameModification = false;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetGroupWithArtifactsById() throws Exception {
- GroupBusinessLogic testSubject;
- ComponentTypeEnum componentType = null;
- String componentId = "";
- String groupId = "";
- String userId = "";
- boolean inTransaction = false;
- Either<GroupDefinitionInfo, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testFindGroupOnComponent() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- String groupId = "";
- Either<GroupDefinition, StorageOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateGroupsBeforeUpdate() throws Exception {
- GroupBusinessLogic testSubject;String componentId = "";
- String userId = "";
- ComponentTypeEnum componentType = null;
- List<GroupDefinition> groups = null;
- boolean inTransaction = false;
- Either<org.openecomp.sdc.be.model.Component,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidateGroupsInComponentByFunc() throws Exception {
- GroupBusinessLogic testSubject;List<GroupDefinition> groups = null;
- Component component = null;
- Function<GroupDefinition,String> getByParam = null;
- ResponseFormat result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testGetAsString() throws Exception {
- GroupBusinessLogic testSubject;
- List<String> list = null;
- String result;
-
- // test 1
- testSubject = createTestSubject();
- list = null;
-
-
- }
-
-
- @Test
- public void testUpdateGroupPropertiesValue() throws Exception {
- GroupBusinessLogic testSubject;String componentId = "";
- GroupDefinition currentGroup = null;
- List<GroupProperty> groupPropertyToUpdate = null;
- boolean inTransaction = false;
- Either<List<GroupProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidateGenerateVfModuleGroupNames() throws Exception {
- GroupBusinessLogic testSubject;
- List<ArtifactTemplateInfo> allGroups = null;
- String resourceSystemName = "";
- int startGroupCounter = 0;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateGenerateVfModuleGroupName() throws Exception {
- GroupBusinessLogic testSubject;
- String resourceSystemName = "";
- String description = "";
- int groupCounter = 0;
- Either<String, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- resourceSystemName = null;
- description = null;
-
-
-
- // test 2
- testSubject = createTestSubject();
- resourceSystemName = "";
- description = null;
-
-
-
- // test 3
- testSubject = createTestSubject();
- description = null;
- resourceSystemName = null;
-
-
-
- // test 4
- testSubject = createTestSubject();
- description = "";
- resourceSystemName = null;
-
-
- }
-
-
- @Test
- public void testValidateUpdateVfGroupNames() throws Exception {
- GroupBusinessLogic testSubject;
- Map<String, GroupDefinition> groups = null;
- String resourceSystemName = "";
- Either<Map<String, GroupDefinition>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetNextVfModuleNameCounter() throws Exception {
- GroupBusinessLogic testSubject;
- Map<String, GroupDefinition> groups = null;
- int result;
-
- // test 1
- testSubject = createTestSubject();
- groups = null;
-
-
- }
-
-
- @Test
- public void testGetNextVfModuleNameCounter_1() throws Exception {
- GroupBusinessLogic testSubject;
- Collection<GroupDefinition> groups = null;
- int result;
-
- // test 1
- testSubject = createTestSubject();
- groups = null;
-
-
- }
-
-
- @Test
- public void testValidateUpdateVfGroupNamesOnGraph() throws Exception {
- GroupBusinessLogic testSubject;
- List<GroupDefinition> groups = null;
- Component component = null;
- boolean inTransaction = false;
- Either<List<GroupDefinition>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetGroupInstWithArtifactsById() throws Exception {
- GroupBusinessLogic testSubject;
- ComponentTypeEnum componentType = null;
- String componentId = "";
- String componentInstanceId = "";
- String groupInstId = "";
- String userId = "";
- boolean inTransaction = false;
- Either<GroupDefinitionInfo, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testFindComponentInstanceAndGroupInstanceOnComponent() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- String componentInstanceId = "";
- String groupInstId = "";
- Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetLatestIntProperty() throws Exception {
- GroupBusinessLogic testSubject;Map<PropertyNames,String> newValues = null;
- Map<PropertyNames,String> parentValues = null;
- PropertyNames propertyKey = null;
- int result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testIsPropertyChanged() throws Exception {
- GroupBusinessLogic testSubject;Map<PropertyNames,String> newValues = null;
- Map<PropertyNames,String> parentValues = null;
- PropertyNames minInstances = null;
- boolean result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidateMinMaxAndInitialCountPropertyLogicVF() throws Exception {
- GroupBusinessLogic testSubject;Map<PropertyNames,String> newValues = null;
- Map<PropertyNames,String> parentValues = null;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidateMinMaxAndInitialCountPropertyLogic() throws Exception {
- GroupBusinessLogic testSubject;Map<PropertyNames,String> newValues = null;
- Map<PropertyNames,String> currValues = null;
- Map<PropertyNames,String> parentValues = null;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testValidateValueInRange() throws Exception {
- GroupBusinessLogic testSubject;ImmutablePair<PropertyNames,String> newValue = null;
- ImmutablePair<PropertyNames,String> min = null;
- ImmutablePair<PropertyNames,String> max = null;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testParseIntValue() throws Exception {
- GroupBusinessLogic testSubject;
- String value = "";
- PropertyNames propertyName = null;
- int result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateGroupInstancePropertyValues() throws Exception {
- GroupBusinessLogic testSubject;
- String componentId = "";
- String instanceId = "";
- GroupInstance oldGroupInstance = null;
- List<GroupInstanceProperty> newProperties = null;
- boolean inTransaction = false;
- Either<GroupInstance, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateReduceGroupInstancePropertiesBeforeUpdate() throws Exception {
- GroupBusinessLogic testSubject;GroupInstance oldGroupInstance = null;
- List<GroupInstanceProperty> newProperties = null;
- Either<List<GroupInstanceProperty>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testFillValuesAndParentValuesFromExistingProperties() throws Exception {
- GroupBusinessLogic testSubject;Map<String,GroupInstanceProperty> existingProperties = null;
- Map<PropertyNames,String> propertyValues = null;
- Map<PropertyNames,String> parentPropertyValues = null;
-
-
- // default test
- }
-
-
- @Test
- public void testHandleAndAddProperty() throws Exception {
- GroupBusinessLogic testSubject;List<GroupInstanceProperty> reducedProperties = null;
- Map<PropertyNames,String> newPropertyValues = null;
- GroupInstanceProperty currNewProperty = null;
- GroupInstanceProperty currExistingProperty = null;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- }
-
-
- @Test
- public void testIsUpdatable() throws Exception {
- GroupBusinessLogic testSubject;
- PropertyNames updatablePropertyName = null;
- boolean result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testAddPropertyUpdatedValues() throws Exception {
- GroupBusinessLogic testSubject;List<GroupInstanceProperty> reducedProperties = null;
- PropertyNames propertyName = null;
- Map<PropertyNames,String> newPropertyValues = null;
- GroupInstanceProperty newProperty = null;
- GroupInstanceProperty existingProperty = null;
-
-
- // default test
- }
-
-
- @Test
- public void testIsEmptyMinInitialCountValue() throws Exception {
- GroupBusinessLogic testSubject;
- PropertyNames propertyName = null;
- String newValue = "";
- boolean result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testConvertIfUnboundMax() throws Exception {
- GroupBusinessLogic testSubject;
- String value = "";
- int result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdatePropertyValue() throws Exception {
- GroupBusinessLogic testSubject;
- GroupInstanceProperty newProperty = null;
- GroupInstanceProperty existingProperty = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateImmutableProperty() throws Exception {
- GroupBusinessLogic testSubject;
- GroupProperty oldProperty = null;
- GroupProperty newProperty = null;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testCreateGroups() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- User user = null;
- ComponentTypeEnum componentType = null;
- List<GroupDefinition> groupDefinitions = null;
- Either<List<GroupDefinition>, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- groupDefinitions = null;
-
-
- }
-
-
- @Test
- public void testAddGroups() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- User user = null;
- ComponentTypeEnum componentType = null;
- List<GroupDefinition> groupDefinitions = null;
- Either<List<GroupDefinition>, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- groupDefinitions = null;
-
-
- }
-
-
- @Test
- public void testDeleteGroups() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- User user = null;
- ComponentTypeEnum componentType = null;
- List<GroupDefinition> groupDefinitions = null;
- Either<List<GroupDefinition>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testUpdateGroups() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- ComponentTypeEnum componentType = null;
- List<GroupDefinition> groupDefinitions = null;
- Either<List<GroupDefinition>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testHandleGroup() throws Exception {
- GroupBusinessLogic testSubject;
- Component component = null;
- User user = null;
- ComponentTypeEnum componentType = null;
- GroupDefinition groupDefinition = null;
- Map<String, DataTypeDefinition> allDAtaTypes = null;
- Either<GroupDefinition, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testHandleProperty() throws Exception {
- GroupBusinessLogic testSubject;
- GroupProperty groupProperty = null;
- PropertyDefinition prop = null;
- Integer index = 0;
- Map<String, DataTypeDefinition> allDataTypes = null;
- Either<GroupProperty, TitanOperationStatus> result;
-
- // test 1
- testSubject = createTestSubject();
- prop = null;
-
-
- }
-} \ No newline at end of file
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 9b6b5c00df..f5357e735f 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
@@ -24,21 +24,21 @@ 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;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.yaml.snakeyaml.Yaml;
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.*;
+import java.util.Map.Entry;
+
+import static org.junit.Assert.*;
import java.util.Map;
import java.util.Map.Entry;
@@ -53,12 +53,12 @@ public class ImportUtilsTest {
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);
+ assertEquals(4, list.size());
int count = 1;
for (Object element : list) {
assertTrue(element instanceof String);
String value = (String) element;
- assertTrue(value.equals("stringVal" + count));
+ assertEquals(value, "stringVal" + count);
count++;
}
}
@@ -68,7 +68,7 @@ public class ImportUtilsTest {
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);
+ assertEquals(3, list.size());
int count = 1;
for (Object element : list) {
assertTrue(element instanceof Boolean);
@@ -88,7 +88,7 @@ public class ImportUtilsTest {
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);
+ assertEquals(3, list.size());
int count = 1;
for (Object element : list) {
assertTrue(element instanceof List);
@@ -111,50 +111,50 @@ public class ImportUtilsTest {
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);
+ assertEquals(5, list.size());
int count = 1;
for (Object element : list) {
if (count == 1) {
assertTrue(element instanceof String);
- assertTrue(element.equals("tosca.nodes.Root"));
+ assertEquals("tosca.nodes.Root", element);
} else if (count == 2) {
assertTrue(element instanceof Map);
Map<String, Object> mapElement = (Map<String, Object>) element;
- assertTrue(mapElement.size() == 2);
+ assertEquals(2, mapElement.size());
Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator();
Entry<String, Object> elementEntry = elementEntries.next();
- assertTrue(elementEntry.getKey().equals("mapTestTag"));
- assertTrue(elementEntry.getValue().equals("string"));
+ assertEquals("mapTestTag", elementEntry.getKey());
+ assertEquals("string", elementEntry.getValue());
elementEntry = elementEntries.next();
- assertTrue(elementEntry.getKey().equals("required"));
+ assertEquals("required", elementEntry.getKey());
assertTrue(elementEntry.getValue() instanceof Boolean);
assertTrue((Boolean) elementEntry.getValue());
}
else if (count == 3) {
assertTrue(element instanceof String);
- assertTrue(element.equals("1 MB"));
+ assertEquals("1 MB", element);
}
else if (count == 4) {
assertTrue(element instanceof List);
List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
+ assertEquals(2, listElement.size());
assertTrue(listElement.get(0) instanceof Map);
Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("greater_or_equal"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
+ assertEquals("greater_or_equal", innerEntry.getKey());
+ assertEquals("1 MB", innerEntry.getValue());
assertTrue(listElement.get(1) instanceof Map);
innerElement = (Map<String, Object>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("stringTestTag"));
- assertTrue(innerEntry.getValue().equals("stringVal3"));
+ assertEquals("stringTestTag", innerEntry.getKey());
+ assertEquals("stringVal3", innerEntry.getValue());
} else if (count == 5) {
assertTrue(element instanceof Boolean);
assertFalse((Boolean) element);
@@ -168,35 +168,35 @@ public class ImportUtilsTest {
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);
+ assertEquals(2, list.size());
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);
+ assertEquals(2, mapElement.size());
Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator();
Entry<String, Object> inerElementEntry = iterator.next();
- assertTrue(inerElementEntry.getKey().equals("stringTestTag"));
- assertTrue(inerElementEntry.getValue().equals("stringVal1"));
+ assertEquals("stringTestTag", inerElementEntry.getKey());
+ assertEquals("stringVal1", inerElementEntry.getValue());
inerElementEntry = iterator.next();
- assertTrue(inerElementEntry.getKey().equals("listTestTag"));
+ assertEquals("listTestTag", inerElementEntry.getKey());
assertTrue(inerElementEntry.getValue() instanceof List);
List<Object> innerValue = (List<Object>) inerElementEntry.getValue();
- assertTrue(innerValue.size() == 3);
+ assertEquals(3, innerValue.size());
} else if (count == 2) {
Map<String, Object> mapElement = (Map<String, Object>) element;
- assertTrue(mapElement.size() == 2);
+ assertEquals(2, mapElement.size());
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"));
+ assertEquals("type", inerElementEntry.getKey());
+ assertEquals("tosca.capabilities.Attachment", inerElementEntry.getValue());
inerElementEntry = entryItr.next();
- assertTrue(inerElementEntry.getKey().equals("allTestTag"));
+ assertEquals("allTestTag", inerElementEntry.getKey());
assertTrue(inerElementEntry.getValue() instanceof Boolean);
}
@@ -241,9 +241,9 @@ public class ImportUtilsTest {
String name = "fullParameter";
String description = "description_text";
- Map<String, Object> parametersMap = new HashMap<String, Object>();
+ Map<String, Object> parametersMap = new HashMap<>();
Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description);
- parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
+ parametersMap.put(TypeUtils.ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
assertTrue(heatParameters.isRight());
@@ -256,12 +256,12 @@ public class ImportUtilsTest {
String name = "fullParameter";
- Map<String, Object> parametersMap = new HashMap<String, Object>();
+ Map<String, Object> parametersMap = new HashMap<>();
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);
+ parametersMap.put(TypeUtils.ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
assertTrue(heatParameters.isLeft());
@@ -279,7 +279,7 @@ public class ImportUtilsTest {
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);
+ Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.ATTRIBUTES);
compareAttributes(expectedAttributes, actualAttributes.left().value());
}
@@ -290,7 +290,7 @@ public class ImportUtilsTest {
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);
+ Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.PROPERTIES);
compareProperties(expectedProperties, actualProperties.left().value());
}
@@ -363,7 +363,7 @@ public class ImportUtilsTest {
}
- private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) {
+ private <T> Map<String, T> getElements(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementType) {
Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType);
assertTrue(toscaExpectedElements.isLeft());
@@ -377,9 +377,9 @@ public class ImportUtilsTest {
String name = "fullParameter";
String description = "description_text";
- Map<String, Object> parametersMap = new HashMap<String, Object>();
+ Map<String, Object> parametersMap = new HashMap<>();
Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description);
- parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
+ parametersMap.put(TypeUtils.ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
assertTrue(heatParameters.isLeft());
@@ -392,12 +392,12 @@ public class ImportUtilsTest {
}
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>();
+ Map<String, Object> firstParam = new HashMap<>();
+ Map<String, Object> valuesMap = new HashMap<>();
- valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type);
- valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description);
- valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal);
+ valuesMap.put(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName(), type);
+ valuesMap.put(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), description);
+ valuesMap.put(TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal);
firstParam.put(name, valuesMap);
return firstParam;
@@ -413,74 +413,72 @@ public class ImportUtilsTest {
private void verifyListElement3(Object element) {
List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
+ assertEquals(2, listElement.size());
Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("testTag1"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
+ assertEquals("testTag1", innerEntry.getKey());
+ assertEquals("1 MB", innerEntry.getValue());
innerElement = (Map<String, String>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("type"));
- assertTrue(innerEntry.getValue().equals("stringVal2"));
+ assertEquals("type", innerEntry.getKey());
+ assertEquals("stringVal2", innerEntry.getValue());
}
private void verifyListElement2(Object element) {
List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
+ assertEquals(2, listElement.size());
Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("testTag1"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
+ assertEquals("testTag1", innerEntry.getKey());
+ assertEquals("1 MB", innerEntry.getValue());
assertTrue(listElement.get(1) instanceof Map);
innerElement = (Map<String, Object>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
+ assertEquals("listTestTag", innerEntry.getKey());
assertTrue(innerEntry.getValue() instanceof List);
}
private void verifyListElement1(Object element) {
List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 3);
+ assertEquals(3, listElement.size());
Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
+ assertEquals("listTestTag", innerEntry.getKey());
+ assertEquals("1 MB", innerEntry.getValue());
innerElement = (Map<String, String>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
- assertTrue(innerEntry.getValue().equals("2 MB"));
+ assertEquals("listTestTag", innerEntry.getKey());
+ assertEquals("2 MB", innerEntry.getValue());
innerElement = (Map<String, String>) listElement.get(2);
- assertTrue(innerElement.size() == 1);
+ assertEquals(1, innerElement.size());
innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("stringTestTag"));
- assertTrue(innerEntry.getValue().equals("stringVal2"));
+ assertEquals("stringTestTag", innerEntry.getKey());
+ assertEquals("stringVal2", innerEntry.getValue());
}
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;
+ return new String(fileContent);
}
private static Object loadJsonFromFile(String fileName) throws IOException {
String content = loadFileNameToJsonString(fileName);
- Object load = new Yaml().load(content);
- return load;
+ return new Yaml().load(content);
}
}
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 f2c53f47c7..34b017778e 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,18 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-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;
@@ -41,16 +30,18 @@ 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;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
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.*;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
public class InputsBusinessLogicTest {
@@ -90,7 +81,7 @@ public class InputsBusinessLogicTest {
instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput));
instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput()));
service.setComponentInstancesInputs(instanceInputMap);
- when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(new User());
when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User()));
}
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 97eeef99c4..454f534cfa 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;
@@ -43,7 +35,14 @@ 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 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;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class InterfaceLifecycleTypeImportManagerTest {
@@ -58,8 +57,7 @@ public class InterfaceLifecycleTypeImportManagerTest {
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;
+ return Either.left((InterfaceDefinition) args[0]);
}
});
@@ -82,7 +80,6 @@ public class InterfaceLifecycleTypeImportManagerTest {
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;
+ return new String(fileContent);
}
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java
index 5a7d8af394..aa71d7616c 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java
@@ -16,25 +16,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyCollection;
-import static org.mockito.ArgumentMatchers.anyObject;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-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.stream.Collectors;
-import java.util.stream.Stream;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -58,20 +40,9 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
-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.operations.*;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -85,7 +56,13 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTestUtils{
@@ -153,8 +130,8 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
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));
+ when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(user);
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
@@ -183,7 +160,8 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
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);
+ //TODO Remove if passes
+ /*when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate);*/
Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
@@ -223,8 +201,10 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
@Test
public void createInterfaceOperationTest() {
+ Resource resource = createResourceForInterfaceOperation();
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
validateUserRoles(Role.ADMIN, Role.DESIGNER);
- when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(createMockResourceForAddInterface()));
+ when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
resourceUpdate = setUpResourceMock();
Either<Resource, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, resourceUpdate, user, true);
Assert.assertTrue(interfaceOperation.isLeft());
@@ -235,7 +215,9 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
public void updateInterfaceOperationTest() {
validateUserRoles(Role.ADMIN, Role.DESIGNER);
resourceUpdate = setUpResourceMock();
- when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(createResourceForInterfaceOperation()));
+ Resource resource = createResourceForInterfaceOperation();
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
+ when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
Either<Resource, ResponseFormat> interfaceOperation = bl.updateInterfaceOperation(resourceId, resourceUpdate, user, true);
Assert.assertTrue(interfaceOperation.isLeft());
}
@@ -243,8 +225,10 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
@Test
public void deleteInterfaceOperationTest() {
+ Resource resource = createResourceForInterfaceOperation();
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
validateUserRoles(Role.ADMIN, Role.DESIGNER);
- when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(createResourceForInterfaceOperation()));
+ when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK);
Set<String> idsToDelete = new HashSet<>();
idsToDelete.add(operationId);
@@ -257,7 +241,9 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
public void deleteInterfaceOperationTestShouldFailWrongId() {
validateUserRoles(Role.ADMIN, Role.DESIGNER);
Set<String> idsToDelete = new HashSet<>();
- when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(createResourceForInterfaceOperation()));
+ Resource resource = createResourceForInterfaceOperation();
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
+ when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
idsToDelete.add(resourceId);
Either<Resource, ResponseFormat> deleteResourceResponseFormatEither = bl.deleteInterfaceOperation(resourceId, idsToDelete, user, true);
Assert.assertFalse(deleteResourceResponseFormatEither.isLeft());
@@ -266,7 +252,9 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
@Test
public void deleteInterfaceOperationFailToDeleteArtifactTest() {
- when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(createResourceForInterfaceOperation()));
+ Resource resource = createResourceForInterfaceOperation();
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
+ when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.GENERAL_ERROR);
validateUserRoles(Role.ADMIN, Role.DESIGNER);
Set<String> idsToDelete = new HashSet<>();
@@ -288,8 +276,7 @@ public class InterfaceOperationBusinessLogicTest implements InterfaceOperationTe
private void validateUserRoles(Role... roles) {
List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
- when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
- }
+ }
private Resource createMockResourceForAddInterface () {
Resource resource = new Resource();
resource.setUniqueId(resourceId);
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
index f9c0a2fc3d..0817cbc6e4 100644
--- 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
@@ -1,21 +1,7 @@
package org.openecomp.sdc.be.components.impl;
-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;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -23,6 +9,7 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
@@ -37,16 +24,7 @@ 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.*;
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;
@@ -58,7 +36,13 @@ 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.*;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PolicyBusinessLogicTest {
@@ -92,22 +76,13 @@ public class PolicyBusinessLogicTest {
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 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;
@@ -124,7 +99,6 @@ public class PolicyBusinessLogicTest {
}
private static void createResponses() {
- userSuccessEither = Either.left(user);
componentSuccessEither = Either.left(resource);
getPolicyTypeSuccessEither = Either.left(policyType);
policySuccessEither = Either.left(policy);
@@ -148,11 +122,14 @@ public class PolicyBusinessLogicTest {
@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);
+ ComponentException userNotFoundException = new ComponentException(ActionStatus.USER_NOT_FOUND);
+ when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenThrow(userNotFoundException);
stubRollback();
- Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
- assertNotFound(response);
+ try{
+ businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ } catch(ComponentException e){
+ assertEquals(e.getActionStatus(), userNotFoundException.getActionStatus());
+ }
}
private void assertNotFound(Either<PolicyDefinition, ResponseFormat> response) {
@@ -161,7 +138,7 @@ public class PolicyBusinessLogicTest {
@Test
public void createPolicyComponentFailureTest(){
- when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither);
+ when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(user);
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);
@@ -190,6 +167,7 @@ public class PolicyBusinessLogicTest {
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));
@@ -266,6 +244,8 @@ public class PolicyBusinessLogicTest {
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());
+ List<PropertyDataDefinition> updatedProperties = response.left().value();
+ assertThat(updatedProperties.size()).isEqualTo(2);
}
@Test
@@ -274,10 +254,7 @@ public class PolicyBusinessLogicTest {
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();
@@ -285,9 +262,6 @@ public class PolicyBusinessLogicTest {
}
- private void stubGetTargetType() {
- }
-
@Test
public void updatePolicyTargetsTargetIDFailureTest(){
stubValidateAndLockSuccess(CREATE_POLICY);
@@ -322,7 +296,7 @@ public class PolicyBusinessLogicTest {
Assert.assertTrue(result.isRight());
ResponseFormat responseResult = result.right().value();
- Assert.assertTrue(responseResult.getStatus().equals(400));
+ Assert.assertEquals(400, (int) responseResult.getStatus());
}
@@ -348,8 +322,7 @@ public class PolicyBusinessLogicTest {
PropertyDataDefinition property2 = new PropertyDataDefinition();
property2.setName(prop2);
property2.setValue(prop2);
- PropertyDataDefinition[] properties = {property1, property2};
- return properties;
+ return new PropertyDataDefinition[]{property1, property2};
}
@@ -374,10 +347,10 @@ public class PolicyBusinessLogicTest {
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(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(user);
when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither);
}
@@ -394,7 +367,7 @@ public class PolicyBusinessLogicTest {
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());
+ return Either.left(builder.addGroup(groupDefinition).addComponentInstance(componentInstance).build());
}
private Map<PolicyTargetType, List<String>> getTargets() {
@@ -430,7 +403,8 @@ public class PolicyBusinessLogicTest {
resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setIsDeleted(false);
resource.setResourceType(ResourceTypeEnum.VF);
- resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue());
+ resource.setToscaType(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
Map<String, PolicyDefinition> policies = new HashMap<>();
policies.put(POLICY_ID, policy);
resource.setPolicies(policies);
@@ -442,45 +416,10 @@ public class PolicyBusinessLogicTest {
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;
}
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
index dd92a0c495..9be3fa00ee 100644
--- 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
@@ -1,15 +1,6 @@
package org.openecomp.sdc.be.components.impl;
-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;
-
-import java.util.List;
-
-import javax.ws.rs.core.Response;
-
+import fj.data.Either;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -18,6 +9,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
@@ -27,17 +19,19 @@ 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.*;
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 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 {
@@ -61,6 +55,8 @@ public class PolicyPropertiesBusinessLogicTest {
@Mock
private ComponentsUtils componentsUtils;
+ private final ComponentTypeEnum COMPONENT_TYPE = ComponentTypeEnum.RESOURCE;
+
private ComponentParametersView componentFilter;
private Resource resource;
private PropertyDefinition prop1, prop2;
@@ -84,6 +80,7 @@ public class PolicyPropertiesBusinessLogicTest {
.build();
resource = new ResourceBuilder()
.setUniqueId(RESOURCE_ID)
+ .setComponentType(COMPONENT_TYPE)
.setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)
.setLastUpdaterUserId(USER_ID)
.addPolicy(policy1)
@@ -99,15 +96,18 @@ public class PolicyPropertiesBusinessLogicTest {
@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);
+ ComponentException forbiddenException = new ComponentException(ActionStatus.AUTH_FAILED);
+ when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenThrow(forbiddenException);
+ try{
+ testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null);
+ } catch(ComponentException e){
+ assertThat(e.getActionStatus()).isEqualTo(ActionStatus.AUTH_FAILED);
+ }
}
@Test
public void getPolicyProperties_componentNotFound() {
- when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(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();
@@ -143,7 +143,7 @@ public class PolicyPropertiesBusinessLogicTest {
}
private void doPolicyValidations() {
- when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(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
index 009876ec31..811d0b900c 100644
--- 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
@@ -1,18 +1,6 @@
package org.openecomp.sdc.be.components.impl;
-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;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
+import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -21,6 +9,7 @@ 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.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -28,13 +17,20 @@ 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.StorageException;
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 com.google.common.collect.ImmutableMap;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
-import fj.data.Either;
+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.*;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PolicyTypeBusinessLogicTest {
@@ -56,8 +52,7 @@ public class PolicyTypeBusinessLogicTest {
@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(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(new User());
when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES));
}
@@ -69,17 +64,20 @@ public class PolicyTypeBusinessLogicTest {
@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);
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenThrow(new ComponentException(userNotExistResponse));
+ try{
+ testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ }catch(ComponentException e){
+ assertThat(e.getResponseFormat()).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();
+ when(policyTypeOperation.getAllPolicyTypes(anySet())).thenReturn(emptyList());
+ List<PolicyTypeDefinition> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes).isEmpty();
}
@Test
@@ -87,26 +85,19 @@ public class PolicyTypeBusinessLogicTest {
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);
+ when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(policyTypes);
+ List<PolicyTypeDefinition> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes).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();
+ when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenThrow(new StorageException(StorageOperationStatus.NOT_FOUND));
+ try {
+ testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ }catch(StorageException e){
+ assertThat(e.getStorageOperationStatus()).isSameAs(StorageOperationStatus.NOT_FOUND);
+ }
}
- @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/ProductBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java
deleted file mode 100644
index cbb5f7b719..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java
+++ /dev/null
@@ -1,384 +0,0 @@
-package org.openecomp.sdc.be.components.impl;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.math3.stat.descriptive.summary.Product;
-import org.junit.Test;
-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.User;
-import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import fj.data.Either;
-
-
-public class ProductBusinessLogicTest {
-
- private ProductBusinessLogic createTestSubject() {
- return new ProductBusinessLogic();
- }
-
- @Test
- public void testValidateProductNameExists() throws Exception {
- ProductBusinessLogic testSubject;
- String productName = "";
- String userId = "";
- Either<Map<String, Boolean>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
- @Test
- public void testSetDeploymentArtifactsPlaceHolder() throws Exception {
- ProductBusinessLogic testSubject;
- Component component = null;
- User user = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setDeploymentArtifactsPlaceHolder(component, user);
- }
-
- @Test
- public void testDeleteMarkedComponents() throws Exception {
- ProductBusinessLogic testSubject;
- Either<List<String>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
- @Test
- public void testGetComponentInstanceBL() throws Exception {
- ProductBusinessLogic testSubject;
- ComponentInstanceBusinessLogic result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
- @Test
- public void testGetComponentInstancesFilteredByPropertiesAndInputs() throws Exception {
- ProductBusinessLogic testSubject;
- String componentId = "";
- ComponentTypeEnum componentTypeEnum = null;
- String userId = "";
- String searchText = "";
- Either<List<ComponentInstance>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
- @Test
- public void testGetCacheManagerOperation() throws Exception {
- ProductBusinessLogic testSubject;
- ICacheMangerOperation result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
- @Test
- public void testSetCacheManagerOperation() throws Exception {
- ProductBusinessLogic testSubject;
- ICacheMangerOperation cacheManagerOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setCacheManagerOperation(cacheManagerOperation);
- }
-
- @Test
- public void testGetUiComponentDataTransferByComponentId() throws Exception {
- ProductBusinessLogic testSubject;
- String componentId = "";
- List<String> dataParamsToReturn = null;
- Either<UiComponentDataTransfer, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testCreateProduct() throws Exception {
- ProductBusinessLogic testSubject;
- Product product = null;
- User user = null;
- Either<Product, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- product = null;
-
- }
-
-
- @Test
- public void testCheckUnupdatableProductFields() throws Exception {
- ProductBusinessLogic testSubject;
- Product product = null;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testValidateProductBeforeCreate() throws Exception {
- ProductBusinessLogic testSubject;
- Product product = null;
- User user = null;
- AuditingActionEnum actionEnum = null;
- Either<Product, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateProductFieldsBeforeCreate() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateProductContactsList() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateGrouping() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetProduct() throws Exception {
- ProductBusinessLogic testSubject;
- String productId = "";
- User user = null;
- Either<Product, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testDeleteProduct() throws Exception {
- ProductBusinessLogic testSubject;
- String productId = "";
- User user = null;
- Either<Product, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateProductFullNameAndCleanup() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateProductNameAndCleanup() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testValidateTagsListAndRemoveDuplicates() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product product = null;
- String oldProductName = "";
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUpdateProductMetadata() throws Exception {
- ProductBusinessLogic testSubject;
- String productId = "";
- Product updatedProduct = null;
- User user = null;
- Either<Product, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- updatedProduct = null;
- }
-
-
- @Test
- public void testValidateAndUpdateProductMetadata() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Product, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateProductName() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateFullName() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateCategory() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateContactList() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateAndUpdateTags() throws Exception {
- ProductBusinessLogic testSubject;
- User user = null;
- Product currentProduct = null;
- Product updatedProduct = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testValidateTagPattern() throws Exception {
- ProductBusinessLogic testSubject;
- String tag = "";
- boolean result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-
-
- @Test
- public void testGetProductByNameAndVersion() throws Exception {
- ProductBusinessLogic testSubject;
- String productName = "";
- String productVersion = "";
- String userId = "";
- Either<Product, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
-
- }
-} \ 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 70cae9bfce..f8ece0ba76 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
@@ -21,9 +21,7 @@
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
-import mockit.Deencapsulation;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -32,76 +30,53 @@ import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.ElementOperationMock;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
-import org.openecomp.sdc.be.components.InterfaceOperationTestUtils;
+import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
+import org.openecomp.sdc.be.components.csar.CsarInfo;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ImportUtilsTest;
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;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
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.CsarInfo;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.NodeTypeInfo;
import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.UploadCapInfo;
-import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
-import org.openecomp.sdc.be.model.UploadPropInfo;
-import org.openecomp.sdc.be.model.UploadReqInfo;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
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.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
-import org.openecomp.sdc.be.user.IUserBusinessLogic;
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.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.ConfigurationSource;
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.common.impl.FSConfigurationSource;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -112,15 +87,15 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContext;
+import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -135,3740 +110,1742 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
-public class ResourceBusinessLogicTest implements InterfaceOperationTestUtils {
-
- 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";
-
- private String resourceId = "resourceId1";
- private String operationId = "uniqueId1";
- Resource resourceUpdate;
-
- 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);
- 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);
- IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
- InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.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(interfaceOperation.updateInterface(anyString(), anyObject()))
- .thenReturn(Either.left(mockInterfaceDefinitionToReturn(RESOURCE_NAME)));
- 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));
- when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK);
-
- // 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);
- bl.setInterfaceTypeOperation(interfaceTypeOperation);
- bl.setInterfaceOperation(interfaceOperation);
-
- 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 testCsarUUIDnotEmpty() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createResourceObject(false);
- resource.setCsarUUID("asasaas");
- Either<Integer, StorageOperationStatus> eitherUpdate = Either.left(2);
- when(toscaOperationFacade.validateCsarUuidUniqueness("asasaas")).thenReturn(eitherUpdate);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource,
- AuditingActionEnum.CREATE_RESOURCE, user, null, null);
-
- }
-
- @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<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- 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());
- }
-
-
- @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 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.setInterfaces(createMockInterfaceDefinition(RESOURCE_NAME));
- 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.setInterfaces(createMockInterfaceDefinition(RESOURCE_NAME));
- 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.setInterfaces(createMockInterfaceDefinition(RESOURCE_NAME));
-
- 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());
- }
-
-
- @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);
- 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));
- }
-
- private ResourceBusinessLogic createTestSubject() {
- return bl;
- }
-
- @Test
- public void testGetAllCertifiedResources() throws Exception {
- ResourceBusinessLogic testSubject;
- boolean getAbstract = false;
- HighestFilterEnum highestFilter = HighestFilterEnum.HIGHEST_ONLY;
- String userId = user.getUserId();
- Either<List<Resource>, ResponseFormat> result;
- Resource resource = createResourceObject(true);
-
- // default test
-
- Either<List<Resource>, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.OK);
-
- when(toscaOperationFacade.getAllCertifiedResources(false, true)).thenReturn(getLatestResult);
- testSubject = createTestSubject();
- result = testSubject.getAllCertifiedResources(getAbstract, highestFilter, userId);
- }
-
- @Test
- public void testGetApplicationDataTypeCache() throws Exception {
- ResourceBusinessLogic testSubject;
- ApplicationDataTypeCache result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getApplicationDataTypeCache();
- }
-
- @Test
- public void testGetArtifactsManager() throws Exception {
- ResourceBusinessLogic testSubject;
- ArtifactsBusinessLogic result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getArtifactsManager();
- }
-
- @Test
- public void testGetCacheManagerOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- ICacheMangerOperation result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getCacheManagerOperation();
- }
-
- @Test
- public void testGetCapabilityTypeOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- ICapabilityTypeOperation result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getCapabilityTypeOperation();
- }
-
- @Test
- public void testGetComponentInstanceBL() throws Exception {
- ResourceBusinessLogic testSubject;
- ComponentInstanceBusinessLogic result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getComponentInstanceBL();
- }
-
- @Test
- public void testGetComponentInstancesFilteredByPropertiesAndInputs() throws Exception {
- ResourceBusinessLogic testSubject;
- String componentId = "";
- ComponentTypeEnum componentTypeEnum = null;
- String userId = "";
- String searchText = "";
- Either<List<ComponentInstance>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId,
- searchText);
- }
-
- @Test
- public void testGetComponentsUtils() throws Exception {
- ResourceBusinessLogic testSubject;
- ComponentsUtils result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getComponentsUtils();
- }
-
- @Test
- public void testGetElementDao() throws Exception {
- ResourceBusinessLogic testSubject;
- IElementOperation result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getElementDao();
- }
-
- @Test
- public void testGetCsarOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- CsarOperation result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getCsarOperation();
- }
-
- @Test
- public void testGetLatestResourceFromCsarUuid() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String csarUuid = "";
- Either<Resource, ResponseFormat> result;
-
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""))
- .thenReturn(eitherUpdate);
-
- // test 1
- testSubject = createTestSubject();
- result = testSubject.getLatestResourceFromCsarUuid(csarUuid, user);
- }
-
- @Test
- public void testGetLifecycleBusinessLogic() throws Exception {
- ResourceBusinessLogic testSubject;
- LifecycleBusinessLogic result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getLifecycleBusinessLogic();
- }
-
- @Test
- public void testGetResource() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
- Either<Resource, ResponseFormat> result;
-
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // test 1
- testSubject = createTestSubject();
- result = testSubject.getResource(resourceId, user);
- }
-
- @Test
- public void testGetResourceByNameAndVersion() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceName = resource.getName();
- String resourceVersion = resource.getVersion();
- String userId = user.getUserId();
- Either<Resource, ResponseFormat> result;
-
- when(toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName,
- resourceVersion)).thenReturn(Either.left(resource));
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
- }
-
- @Test
- public void testGetUserAdmin() throws Exception {
- ResourceBusinessLogic testSubject;
- IUserBusinessLogic result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getUserAdmin();
- }
-
- @Test
- public void testHandleNodeTypeArtifacts() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource nodeTypeResource = null;
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
- List<ArtifactDefinition> createdArtifacts = null;
- User user = null;
- boolean inTransaction = false;
- boolean ignoreLifecycleState = false;
- Either<List<ArtifactDefinition>, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.handleNodeTypeArtifacts(nodeTypeResource, nodeTypeArtifactsToHandle, createdArtifacts,
- user, inTransaction, ignoreLifecycleState);
- }
-
-
- @Test
- public void testIsResourceExist() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceName = resource.getName();
- boolean result;
-
- // default test
- Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(toscaOperationFacade.getLatestByName(resource.getName())).thenReturn(getLatestResult);
- testSubject = createTestSubject();
- result = testSubject.isResourceExist(resourceName);
- }
-
- @Test
- public void testPropagateStateToCertified() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- ;
- LifecycleChangeInfoWithAction lifecycleChangeInfo = null;
- boolean inTransaction = false;
- boolean needLock = false;
- boolean forceCertificationAllowed = false;
- Either<Resource, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.propagateStateToCertified(user, resource, lifecycleChangeInfo, inTransaction, needLock,
- forceCertificationAllowed);
- }
-
- @Test
- public void testSetApplicationDataTypeCache() throws Exception {
- ResourceBusinessLogic testSubject;
- ApplicationDataTypeCache applicationDataTypeCache = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setApplicationDataTypeCache(applicationDataTypeCache);
- }
-
- @Test
- public void testSetArtifactsManager() throws Exception {
- ResourceBusinessLogic testSubject;
- ArtifactsBusinessLogic artifactsManager = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setArtifactsManager(artifactsManager);
- }
-
- @Test
- public void testSetCacheManagerOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- ICacheMangerOperation cacheManagerOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setCacheManagerOperation(cacheManagerOperation);
- }
-
- @Test
- public void testSetCapabilityTypeOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- ICapabilityTypeOperation capabilityTypeOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setCapabilityTypeOperation(capabilityTypeOperation);
- }
-
- @Test
- public void testSetComponentsUtils() throws Exception {
- ResourceBusinessLogic testSubject;
- ComponentsUtils componentsUtils = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setComponentsUtils(componentsUtils);
- }
-
- @Test
- public void testSetDeploymentArtifactsPlaceHolder() throws Exception {
- ResourceBusinessLogic testSubject;
- Component component = createResourceObject(true);
- ;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setDeploymentArtifactsPlaceHolder(component, user);
- }
-
- @Test
- public void testSetCsarOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- CsarOperation csarOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setCsarOperation(csarOperation);
- }
-
- @Test
- public void testSetElementDao() throws Exception {
- ResourceBusinessLogic testSubject;
- IElementOperation elementDao = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setElementDao(elementDao);
- }
-
- @Test
- public void testSetInterfaceOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- InterfaceOperation interfaceOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setInterfaceOperation(interfaceOperation);
- }
-
- @Test
- public void testSetInterfaceTypeOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- IInterfaceLifecycleOperation interfaceTypeOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setInterfaceTypeOperation(interfaceTypeOperation);
- }
-
- @Test
- public void testSetLifecycleManager() throws Exception {
- ResourceBusinessLogic testSubject;
- LifecycleBusinessLogic lifecycleBusinessLogic = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setLifecycleManager(lifecycleBusinessLogic);
- }
-
- @Test
- public void testSetPropertyOperation() throws Exception {
- ResourceBusinessLogic testSubject;
- IPropertyOperation propertyOperation = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setPropertyOperation(propertyOperation);
- }
-
- @Test
- public void testSetUserAdmin() throws Exception {
- ResourceBusinessLogic testSubject;
- UserBusinessLogic userAdmin = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setUserAdmin(userAdmin);
- }
-
- @Test
- public void testShouldUpgradeToLatestDerived() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource clonedComponent = createResourceObject(true);
- ;
- Either<Component, ActionStatus> result;
-
- Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.OK);
- when(toscaOperationFacade.shouldUpgradeToLatestDerived(clonedComponent)).thenReturn(getLatestResult);
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.shouldUpgradeToLatestDerived(clonedComponent);
- }
-
- @Test
- public void testUpdateResourceMetadata() throws Exception {
- ResourceBusinessLogic testSubject;
- String resourceIdToUpdate = "";
- Resource newResource = createResourceObject(true);
- Resource currentResource = createResourceObject(true);
- boolean inTransaction = false;
- Either<Resource, ResponseFormat> result;
-
- // default test
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(newResource));
- when(toscaOperationFacade.getToscaElement(newResource.getUniqueId())).thenReturn(eitherUpdate);
- testSubject = createTestSubject();
- result = testSubject.updateResourceMetadata(resourceIdToUpdate, newResource, currentResource, user,
- inTransaction);
- }
-
- @Test
- public void testValidateAndUpdateResourceFromCsar() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- ;
- Map<String, byte[]> csarUIPayload = null;
- String payloadName = "";
- String resourceUniqueId = "";
- Either<Resource, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- payloadName = null;
- result = testSubject.validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName,
- resourceUniqueId);
-
- // test 2
- testSubject = createTestSubject();
- payloadName = "";
- result = testSubject.validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName,
- resourceUniqueId);
- }
-
- @Test
- public void testValidateDerivedFromNotEmpty() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.validateDerivedFromNotEmpty(user, resource, actionEnum);
- }
-
- @Test
- public void testValidateResourceBeforeCreate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- ;
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_CATEGORY;
- boolean inTransaction = false;
- CsarInfo csarInfo = null;
- Either<Resource, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.validateResourceBeforeCreate(resource, user, actionEnum, inTransaction, csarInfo);
- }
-
- @Test
- public void testValidateResourceCreationFromNodeType() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- ;
- User creator = user;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.validateResourceCreationFromNodeType(resource, creator);
- }
-
- @Test
- public void testValidatePropertiesDefaultValues() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.validatePropertiesDefaultValues(resource);
- }
-
- @Test
- public void testValidateResourceNameExists() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource recource = createResourceObject(true);
- String resourceName = recource.getName();
- ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.VF;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
- String userId = user.getUserId();
- Either<Map<String, Boolean>, ResponseFormat> result;
-
- // default test
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = Either.left(true);
- when(toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, componentTypeEnum))
- .thenReturn(dataModelResponse);
- testSubject = createTestSubject();
- result = testSubject.validateResourceNameExists(resourceName, resourceTypeEnum, userId);
- }
-
- @Test
- public void testValidateVendorReleaseName() throws Exception {
- ResourceBusinessLogic testSubject;
- String vendorRelease = "";
- Either<Boolean, ResponseFormat> result;
-
- // test 1
- testSubject = createTestSubject();
- vendorRelease = null;
- result = testSubject.validateVendorReleaseName(vendorRelease);
-
- // test 2
- testSubject = createTestSubject();
- vendorRelease = "";
- result = testSubject.validateVendorReleaseName(vendorRelease);
- }
-
- @Test
- public void testValidateVendorReleaseName_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = null;
- Either<Boolean, ResponseFormat> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.validateVendorReleaseName(user, resource, actionEnum);
- }
-
- @Test
- public void testIsResourceNameEquals() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- updateInfoResource.setName("name");
- boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = Deencapsulation.invoke(testSubject, "isResourceNameEquals",
- new Object[] { currentResource, updateInfoResource });
- }
-
- @Test
- public void testAddCvfcSuffixToResourceName() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- String resourceName = currentResource.getName();
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = Deencapsulation.invoke(testSubject, "addCvfcSuffixToResourceName", new Object[] { resourceName });
- }
-
-
- @Test
- public void testCreateResource() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum auditingAction = null;
- Map<String,byte[]> csarUIPayload = null;
- String payloadName = "";
- Either<Resource,ResponseFormat> result;
-
- // test 1 1
- testSubject=createTestSubject();
-
- List<Role> listOfRoles = new ArrayList<>();
- listOfRoles.add(Role.ADMIN);
- listOfRoles.add(Role.DESIGNER);
- Either<Boolean, ResponseFormat> validationResult = Either.left(true);
- when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(validationResult);
-
-
-
- result=testSubject.createResource(resource, auditingAction, user, csarUIPayload, payloadName);
-
- // test 2 2
- testSubject=createTestSubject();payloadName = "";
- result=testSubject.createResource(resource, auditingAction, user, csarUIPayload, payloadName);
-
- // test 3
- testSubject=createTestSubject();payloadName = null;
- result=testSubject.createResource(resource, auditingAction, user, csarUIPayload, payloadName);
-
- // test 4
- testSubject=createTestSubject();payloadName = "";
- result=testSubject.createResource(resource, auditingAction, user, csarUIPayload, payloadName);
- }
-
-
- @Test
- public void testGetElementDao_1() throws Exception {
- ResourceBusinessLogic testSubject;IElementOperation result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.getElementDao();
- }
-
- @Test(expected=UnsupportedOperationException.class)
- public void testCreateResource_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);;
- AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY;
- Map<String,byte[]> csarUIPayload = new HashMap<>();
- String payloadName = "";
- Either<Resource,ResponseFormat> result;
-
- List<Role> listOfRoles = new ArrayList<>();
- listOfRoles.add(Role.ADMIN);
- listOfRoles.add(Role.DESIGNER);
- Either<Boolean, ResponseFormat> validationResult = Either.left(true);
- when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(validationResult);
-
- // test 1 1
- testSubject=createTestSubject();
- result=testSubject.createResource(resource, auditingAction, user, csarUIPayload, payloadName);
-
- }
-
-
- @Test
- public void testValidateCsarIsNotAlreadyUsed() throws Exception {
- ResourceBusinessLogic testSubject;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
- Resource oldResource = createResourceObject(true);
- Resource resource = createResourceObject(true);
- String csarUUID = "";
-
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()))
- .thenReturn(resourceLinkedToCsarRes);
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "validateCsarIsNotAlreadyUsed", new Object[]{responseWrapper, resource, oldResource, csarUUID, user});
- }
-
-
- @Test
- public void testValidateCsarUuidMatching() throws Exception {
- ResourceBusinessLogic testSubject;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
- Resource resource = createResourceObject(true);
- Resource oldResource = createResourceObject(true);
- String csarUUID = "";
- String resourceUniqueId = "";
-
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "validateCsarUuidMatching", new Object[]{responseWrapper, resource, oldResource, csarUUID, resourceUniqueId, user});
- }
-
-
- @Test
- public void testGetResourceByUniqueId() throws Exception {
- ResourceBusinessLogic testSubject;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
- Resource resource = createResourceObject(true);
- String resourceUniqueId = resource.getUniqueId();
- Resource result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getResourceByUniqueId", new Object[]{responseWrapper, resourceUniqueId});
- }
-
-
- @Test
- public void testOverrideImmutableMetadata() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource oldRresource = createResourceObject(true);
- Resource resource = createResourceObject(true);
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "overrideImmutableMetadata", new Object[]{oldRresource, resource});
- }
-
-
- @Test
- public void testFindNodeTypesArtifactsToHandle() throws Exception {
- ResourceBusinessLogic testSubject;
- NodeTypeInfo nodeTypeInfos = new NodeTypeInfo();
- Map<String,NodeTypeInfo> nodeTypesInfo = new HashMap<>();
- nodeTypesInfo.put("key", nodeTypeInfos);
-
- CsarInfo csarInfo = new CsarInfo("", new User(), "", null, "", false);
- Resource oldResource = createResourceObject(true);
- Either<Map<String,EnumMap<ArtifactOperationEnum,List<ArtifactDefinition>>>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findNodeTypesArtifactsToHandle", new Object[]{nodeTypesInfo, csarInfo, oldResource});
- }
-
-
- @Test(expected=IllegalArgumentException.class)
- public void testFindNodeTypeArtifactsToHandle() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource curNodeType = createResourceObject(true);
- ArtifactDefinition artifactDefinition = new ArtifactDefinition();
- List<ArtifactDefinition> extractedArtifacts = new ArrayList<>();
- extractedArtifacts.add(artifactDefinition);
- Either<EnumMap<ArtifactOperationEnum,List<ArtifactDefinition>>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findNodeTypeArtifactsToHandle", new Object[]{curNodeType, artifactDefinition});
- }
-
-
- @Test
- public void testCheckoutResource() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
- boolean inTransaction = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "checkoutResource", new Object[]{resource, user, inTransaction});
- }
-
-
-
-
-
-
-
- @Test
- public void testExtractNodeTypes() throws Exception {
- ResourceBusinessLogic testSubject;
- Map<String,Object> nodes = new HashMap<>();
-
- Map<String,Object> mappedToscaTemplate = new HashMap<>();
- mappedToscaTemplate.put("node_types", new Object());
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "extractNodeTypes", new Object[]{nodes, mappedToscaTemplate});
- }
-
- @Test
- public void testMarkNestedVfc() throws Exception {
- ResourceBusinessLogic testSubject;
- Map<String,Object> mappedToscaTemplate = new HashMap<>();
- Map<String,NodeTypeInfo> nodeTypesInfo = new HashMap<>();
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "markNestedVfc", new Object[]{mappedToscaTemplate, nodeTypesInfo});
- }
-
-
- @Test
- public void testIsGlobalSubstitute() throws Exception {
- ResourceBusinessLogic testSubject;String fileName = "";
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isGlobalSubstitute", new Object[]{fileName});
- }
-
-
- @Test
- public void testValidateAndParseCsar() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
- String csarUUID = "";
- Either<Map<String,byte[]>,StorageOperationStatus> csar = Either.right(StorageOperationStatus.BAD_REQUEST);
- Either<ImmutablePair<String,String>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateAndParseCsar", new Object[]{resource, user, csarUUID, csar});
- }
-
-
- @Test
- public void testValidateResourceBeforeCreate_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
- boolean inTransaction = false;
- Either<Resource,ResponseFormat> result;
-
- List<Role> listOfRoles = new ArrayList<>();
- listOfRoles.add(Role.ADMIN);
- listOfRoles.add(Role.DESIGNER);
- Either<Boolean, ResponseFormat> validationResult = Either.left(true);
- when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(validationResult);
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceBeforeCreate", new Object[]{resource, user, inTransaction});
- }
-
-
-
-
- @Test
- public void testCreateResourcesFromYamlNodeTypesList() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlName = "";
- Resource resource = createResourceObject(true);
- Map<String,Object> mappedToscaTemplate = new HashMap<>();
- boolean needLock = false;
- Map<String,EnumMap<ArtifactOperationEnum,List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
- Map<String,NodeTypeInfo> nodeTypesInfo = new HashMap<>();
- CsarInfo csarInfo = new CsarInfo("", new User(), "", null, "", false);
- Either<Map<String,Resource>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
- }
-
-
-
- @Test
- public void testFillResourceMetadata() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlName = "";
- Resource resourceVf = createResourceObject(true);;
- String nodeName = "";
-
- Either<UploadResourceInfo,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "fillResourceMetadata", new Object[]{yamlName, resourceVf, nodeName, user});
- }
-
-
-
-
- @Test
- public void testBuildCvfcName() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceVfName = "ResourceResource12";
- String nodeName ="org.openecomp.resource.VF.ResourceResource12";
- String result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "buildCvfcName", new Object[]{resourceVfName, nodeName});
- }
-
- @Test
- public void testUpdateGroupMembersUsingResource() throws Exception {
- ResourceBusinessLogic testSubject;
- GroupDefinition groupDefinition = new GroupDefinition();
- Map<String,GroupDefinition> groups = new HashMap<>();
- groups.put("key", groupDefinition);
- Resource component = createResourceObject(true);
- Either<List<GroupDefinition>,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "updateGroupMembersUsingResource", new Object[]{groups, component});
- }
-
-
- @Test
- public void testValidateCyclicGroupsDependencies() throws Exception {
- ResourceBusinessLogic testSubject;
- GroupDefinition groupDefinition = new GroupDefinition();
- Map<String,GroupDefinition> groups = new HashMap<>();
- groups.put("key", groupDefinition);
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateCyclicGroupsDependencies", new Object[]{groups});
- }
-
-
- @Test
- public void testFillAllGroupMemebersRecursivly() throws Exception {
- ResourceBusinessLogic testSubject;
- String groupName = "";
- GroupDefinition groupDefinition = new GroupDefinition();
- Map<String,GroupDefinition> groups = new HashMap<>();
- groups.put("key", groupDefinition);
- Set<String> allGroupMembers = new HashSet<String>();
- allGroupMembers.add("aaa");
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "fillAllGroupMemebersRecursivly", new Object[]{groupName, groups, allGroupMembers});
- }
-
-
- @Test
- public void testIsfillGroupMemebersRecursivlyStopCondition() throws Exception {
- ResourceBusinessLogic testSubject;
- String groupName = "";
- GroupDefinition groupDefinition = new GroupDefinition();
- Map<String,GroupDefinition> groups = new HashMap<>();
- groups.put("key", groupDefinition);
- Set<String> allGroupMembers = new HashSet<String>();
- allGroupMembers.add("aaa");
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isfillGroupMemebersRecursivlyStopCondition", new Object[]{groupName, groups, allGroupMembers});
- }
-
-
-
-
-
- @Test
- public void testHandleAndAddExtractedVfcsArtifacts() throws Exception {
- ResourceBusinessLogic testSubject;
- ArtifactDefinition artifactDefinition = new ArtifactDefinition();
-
- List<ArtifactDefinition> vfcArtifacts = new ArrayList<>();
- vfcArtifacts.add(artifactDefinition);
- List<ArtifactDefinition> artifactsToAdd = new ArrayList<>();
- artifactsToAdd.add(artifactDefinition);
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "handleAndAddExtractedVfcsArtifacts", new Object[]{vfcArtifacts, artifactsToAdd});
- }
-
-
-
-
- @Test
- public void testHandleVfCsarArtifacts() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- CsarInfo csarInfo = new CsarInfo("", new User(), "", null, "", false);
- ArtifactOperationEnum download = ArtifactOperationEnum.CREATE;
- ArtifactsBusinessLogic artb = new ArtifactsBusinessLogic();
-
- ArtifactOperationInfo operation = artb.new ArtifactOperationInfo(false, false, download);
- List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
- boolean shouldLock = false;
- boolean inTransaction = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "handleVfCsarArtifacts", new Object[]{resource, csarInfo, createdArtifacts, operation, shouldLock, inTransaction});
- }
-
-
-
- @Test
- public void testIsArtifactDeletionRequired() throws Exception {
- ResourceBusinessLogic testSubject;
- String artifactId = "";
- byte[] artifactFileBytes = new byte[]{' '};
- boolean isFromCsar = false;
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isArtifactDeletionRequired", new Object[]{artifactId, artifactFileBytes, isFromCsar});
- }
-
-
-
-
- @Test
- public void testValidateArtifactNames() throws Exception {
- ResourceBusinessLogic testSubject;
- NonMetaArtifactInfo nonMetaArtifactInfo = new NonMetaArtifactInfo(operationId, operationId, null, null, null, operationId, false);
- List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
- artifactPathAndNameList.add(nonMetaArtifactInfo);
- Either<Boolean,String> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateArtifactNames", new Object[]{artifactPathAndNameList});
- }
-
-
- @Test
- public void testIsNonMetaArtifact() throws Exception {
- ResourceBusinessLogic testSubject;
- ArtifactDefinition artifact = new ArtifactDefinition();
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isNonMetaArtifact", new Object[]{artifact});
- }
-
-
- @Test
- public void testIsValidArtifactType() throws Exception {
- ResourceBusinessLogic testSubject;
- ArtifactDefinition artifact = new ArtifactDefinition();
- boolean result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "isValidArtifactType", new Object[]{artifact});
- }
-
-
- @Test
- public void testCreateResourceInstancesRelations() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlName = "";
- Resource resource = createResourceObject(true);
- UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
-
- Map<String,UploadComponentInstanceInfo> uploadResInstancesMap = new HashMap<>();
- uploadResInstancesMap.put("key", uploadComponentInstanceInfo);
- Either<Resource,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "createResourceInstancesRelations", new Object[]{user, yamlName, resource, uploadResInstancesMap});
- }
-
-
- @Test
- public void testUpdatePropertyValues() throws Exception {
- ResourceBusinessLogic testSubject;
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- Map<String,UploadPropInfo> newProperties = new HashMap<>();
- Map<String,DataTypeDefinition> allDataTypes = new HashMap<>();;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updatePropertyValues", new Object[]{properties, newProperties, allDataTypes});
- }
-
-
- @Test
- public void testUpdatePropertyValue() throws Exception {
- ResourceBusinessLogic testSubject;
- ComponentInstanceProperty property = new ComponentInstanceProperty();
- UploadPropInfo propertyInfo = new UploadPropInfo();
- Map<String,DataTypeDefinition> allDataTypes = new HashMap<>();
- Either<String,StorageOperationStatus> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "updatePropertyValue", new Object[]{property, propertyInfo, allDataTypes});
- }
-
-
- @Test
- public void testUpdateCalculatedCapReqWithSubstitutionMappings() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
- Map<String,UploadComponentInstanceInfo> uploadResInstancesMap = new HashMap<>();
- uploadResInstancesMap.put("key", uploadComponentInstanceInfo);
-
- Either<Resource,StorageOperationStatus> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updateCalculatedCapReqWithSubstitutionMappings", new Object[]{resource, uploadResInstancesMap});
- }
-
-
- @Test
- public void testFillUpdatedInstCapabilitiesRequirements() throws Exception {
- ResourceBusinessLogic testSubject;
- List<ComponentInstance> componentInstances = new ArrayList<>();
- Map<String,UploadComponentInstanceInfo> uploadResInstancesMap = new HashMap<>();
- Map<ComponentInstance,Map<String,List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
- Map<ComponentInstance,Map<String,List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "fillUpdatedInstCapabilitiesRequirements", new Object[]{componentInstances, uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements});
- }
-
- @Test
- public void testAddInputsValuesToRi() throws Exception {
- ResourceBusinessLogic testSubject;
- UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
- Resource resource = createResourceObject(true);
- Resource originResource = createResourceObject(true);;
- ComponentInstance currentCompInstance = new ComponentInstance();
- String yamlName = "aaa";
- Map<String,List<ComponentInstanceInput>> instInputs = new HashMap<>();
- Map<String,DataTypeDefinition> allDataTypes = new HashMap<>();
- ResponseFormat result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "addInputsValuesToRi", new Object[]{uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes});
- }
-
-
-
-
-
- @Test
- public void testFindAvailableCapabilityByTypeOrName() throws Exception {
- ResourceBusinessLogic testSubject;
- RequirementDefinition validReq = new RequirementDefinition();
- validReq.setCapability(RESOURCE_NAME);
- validReq.setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, null);
- ComponentInstance currentCapCompInstance = new ComponentInstance();
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- currentCapCompInstance.setCapabilities(capabilities);
- UploadReqInfo uploadReqInfo = new UploadReqInfo();
- CapabilityDefinition result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findAvailableCapabilityByTypeOrName", new Object[]{validReq, currentCapCompInstance, uploadReqInfo});
- }
-
-
- @Test
- public void testFindAvailableCapability() throws Exception {
- ResourceBusinessLogic testSubject;
- RequirementDefinition validReq = new RequirementDefinition();
- validReq.setCapability(RESOURCE_NAME);
- validReq.setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, null);
- ComponentInstance currentCapCompInstance = new ComponentInstance();
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- currentCapCompInstance.setCapabilities(capabilities);
- UploadReqInfo uploadReqInfo = new UploadReqInfo();
- CapabilityDefinition result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findAvailableCapability", new Object[]{validReq, currentCapCompInstance, uploadReqInfo});
- }
-
-
- @Test
- public void testFindAviableCapability() throws Exception {
- ResourceBusinessLogic testSubject;
- RequirementDefinition validReq = new RequirementDefinition();
- validReq.setCapability(RESOURCE_NAME);
- validReq.setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, null);
- ComponentInstance currentCapCompInstance = new ComponentInstance();
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- currentCapCompInstance.setCapabilities(capabilities);
- CapabilityDefinition result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "findAviableCapability", new Object[]{validReq, currentCapCompInstance});
- }
-
-
-
-
-
-
-
-
- @Test
- public void testCreateResourceInstances() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlName = "aa";
- Resource resource = createResourceObject(true);
- Map<String,UploadComponentInstanceInfo> uploadResInstancesMap = new HashMap<>();
- boolean inTransaction = false;
- boolean needLock = false;
- Map<String,Resource> nodeNamespaceMap = new HashMap<>();
- Either<Resource,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "createResourceInstances", new Object[]{user, yamlName, resource,uploadResInstancesMap, inTransaction, needLock, nodeNamespaceMap});
- }
-
-
- @Test
- public void testGetNamesToUpdate() throws Exception {
- ResourceBusinessLogic testSubject;
- UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
- Map<String,List<String>> elements = new HashMap<>();
- Either<Map<String,String>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getNamesToUpdate", new Object[]{nodeTemplateInfo, elements});
- }
-
-
- @Test
- public void testCreateInputPropList() throws Exception {
- ResourceBusinessLogic testSubject;
- UploadPropInfo propertyDef = new UploadPropInfo();
- List<Object> propValueList = new ArrayList<>();
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "createInputPropList", new Object[]{propertyDef, propValueList});
- }
-
-
- @Test
- public void testCreateGetInputModuleFromMap() throws Exception {
- ResourceBusinessLogic testSubject;
- String propName = "aaa";
- Map<String,Object> propValue = new HashMap<>();;
- UploadPropInfo propertyDef = new UploadPropInfo();
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "createGetInputModuleFromMap", new Object[]{propName, propValue, propertyDef});
- }
-
-
- @Test
- public void testValueContainsPattern() throws Exception {
- ResourceBusinessLogic testSubject;
- Pattern pattern = null;
- Object propValue = null;
- boolean result;
-
- // test 1
- testSubject=createTestSubject();propValue = null;
- result=Deencapsulation.invoke(testSubject, "valueContainsPattern", new Object[]{Pattern.class, Object.class});
- Assert.assertEquals(false, result);
- }
-
-
-
- @Test
- public void testCreateCapModuleFromYaml() throws Exception {
- ResourceBusinessLogic testSubject;
- UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
- Map<String,Object> nodeTemplateJsonMap = new HashMap<>();
- Either<Map<String,List<UploadCapInfo>>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createCapModuleFromYaml", new Object[]{nodeTemplateInfo, nodeTemplateJsonMap});
- }
-
-
-
-
-
- @Test
- public void testCreateModuleNodeTemplateCap() throws Exception {
- ResourceBusinessLogic testSubject;Object capObject = null;
- Either<UploadCapInfo,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createModuleNodeTemplateCap", new Object[]{Object.class});
- }
-
-
- @Test
- public void testCreateModuleNodeTemplateReg() throws Exception {
- ResourceBusinessLogic testSubject;Object regObject = null;
- Either<UploadReqInfo,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createModuleNodeTemplateReg", new Object[]{Object.class});
- }
-
-
-
- @Test
- public void testNodeForceCertification() throws Exception {
- ResourceBusinessLogic testSubject;Resource resource = createResourceObject(true);
-
- LifecycleChangeInfoWithAction lifecycleChangeInfo = null;
- boolean inTransaction = false;
- boolean needLock = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "nodeForceCertification", new Object[]{Resource.class, user, LifecycleChangeInfoWithAction.class, inTransaction, needLock});
- }
-
-
- @Test
- public void testCreateResourceByImport() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
- boolean isNormative = false;
- boolean isInTransaction = false;
- CsarInfo csarInfo = null;
- Either<ImmutablePair<Resource,ActionStatus>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createResourceByImport", new Object[]{resource, user, isNormative, isInTransaction, CsarInfo.class});
- }
-
-
-
- @Test
- public void testMergeOldResourceMetadataWithNew() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource oldResource = createResourceObject(true);
- Resource newResource = createResourceObject(true);;
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "mergeOldResourceMetadataWithNew", new Object[]{oldResource, newResource});
- }
-
-
- @Test
- public void testPrepareResourceForUpdate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource latestResource = createResourceObject(true);;
-
- boolean inTransaction = false;
- boolean needLock = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "prepareResourceForUpdate", new Object[]{latestResource, user, inTransaction, needLock});
- }
-
-
- @Test
- public void testValidateResourceBeforeCreate_2() throws Exception {
- ResourceBusinessLogic testSubject;Resource resource = createResourceObject(true);
-
- AuditingActionEnum actionEnum = null;
- boolean inTransaction = false;
- CsarInfo csarInfo = null;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.validateResourceBeforeCreate(resource, user, actionEnum, inTransaction, csarInfo);
- }
-
-
- @Test
- public void testValidateResourceType() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ARTIFACT_DOWNLOAD;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceType", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test
- public void testValidateLifecycleTypesCreate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ARTIFACT_METADATA_UPDATE;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateLifecycleTypesCreate", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test
- public void testValidateCapabilityTypesCreate() throws Exception {
- ResourceBusinessLogic testSubject;
- ICapabilityTypeOperation capabilityTypeOperation = new ICapabilityTypeOperation() {
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId,
- boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition) {
- // TODO Auto-generated method stub
- return null;
- }
- };
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ARTIFACT_UPLOAD;
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "validateCapabilityTypesCreate", new Object[]{user, capabilityTypeOperation, resource, actionEnum, inTransaction});
- }
-
-
- @Test(expected=UnsupportedOperationException.class)
- public void testValidateCapabilityTypeExists() throws Exception {
- ResourceBusinessLogic testSubject;
- ICapabilityTypeOperation capabilityTypeOperation = new ICapabilityTypeOperation() {
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId,
- boolean inTransaction) {
- // TODO Auto-generated method stub
- return Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId) {
- // TODO Auto-generated method stub
- return Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) {
- // TODO Auto-generated method stub
- return Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- }
-
- @Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition) {
- // TODO Auto-generated method stub
- return null;
- }
- };
- Resource resource = createResourceObject(true);
- List<?> validationObjects = new ArrayList<>();
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_CATEGORY;
- Either<Boolean,ResponseFormat> eitherResult = Either.left(true);
- String type = "";
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateCapabilityTypeExists", new Object[]{user, capabilityTypeOperation, resource, validationObjects, actionEnum,eitherResult, type, inTransaction});
- }
-
- @Test
- public void testCreateResourceTransaction() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
- boolean isNormative = false;
- boolean inTransaction = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createResourceTransaction", new Object[]{resource, user, isNormative, inTransaction});
- }
-
-
- @Test
- public void testCreateArtifactsPlaceHolderData() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "createArtifactsPlaceHolderData", new Object[]{resource, user});
- }
-
-
- @Test
- public void testSetInformationalArtifactsPlaceHolder() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
-
-
-
- // default test
- testSubject=createTestSubject();Deencapsulation.invoke(testSubject, "setInformationalArtifactsPlaceHolder", new Object[]{resource, user});
- }
-
-
- @Test
- public void testDeleteResource() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
- ResponseFormat result;
-
-
- Either<Component, StorageOperationStatus> resourceStatus = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getToscaElement(resourceId))
- .thenReturn(resourceStatus);
-
- // default test
- testSubject=createTestSubject();result=testSubject.deleteResource(resourceId, user);
- }
-
-
- @Test
- public void testDeleteResourceByNameAndVersion() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceName = resource.getName();
- String version = resource.getVersion();
-
- ResponseFormat result;
-
- Either<Component, StorageOperationStatus> resourceStatus = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version))
- .thenReturn(resourceStatus);
- // default test
- testSubject=createTestSubject();result=testSubject.deleteResourceByNameAndVersion(resourceName, version, user);
- }
-
-
- @Test
- public void testUpdateResourceMetadata_1() throws Exception {
- ResourceBusinessLogic testSubject;String resourceIdToUpdate = "";
- Resource newResource = createResourceObject(true);;
- Resource currentResource = createResourceObject(true);;
-
- boolean inTransaction = false;
- Either<Resource,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.updateResourceMetadata(resourceIdToUpdate, newResource, currentResource, user, inTransaction);
- }
-
-
- @Test
- public void testUpdateComponentGroupName() throws Exception {
- ResourceBusinessLogic testSubject;
- String replacePattern = "";
- String with = "";
- List<GroupDefinition> oldGroup = new ArrayList<>();
- Either<List<GroupDefinition>,Boolean> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "updateComponentGroupName", new Object[]{replacePattern, with, oldGroup});
-
- }
-
-
- @Test
- public void testIsComponentNameChanged() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource newResource = createResourceObject(true);
- Resource oldResource = createResourceObject(true);
- boolean result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "isComponentNameChanged", new Object[]{oldResource, newResource});
- }
-
-
- @Test
- public void testValidateResourceFieldsBeforeCreate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ACTIVATE_SERVICE_BY_API;
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceFieldsBeforeCreate", new Object[]{user, resource, actionEnum, inTransaction});
- }
-
-
- @Test
- public void testValidateResourceFieldsBeforeUpdate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- boolean inTransaction = false;
- boolean isNested = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceFieldsBeforeUpdate", new Object[]{updateInfoResource, currentResource, inTransaction, isNested});
- }
-
-
- @Test
- public void testValidateResourceName() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);;
- Resource updateInfoResource = createResourceObject(true);;
- boolean hasBeenCertified = false;
- boolean isNested = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceName", new Object[]{currentResource, updateInfoResource, hasBeenCertified, isNested});
- }
-
-
- @Test
- public void testValidateIcon() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);;
- Resource updateInfoResource = createResourceObject(true);;
- boolean hasBeenCertified = false;
- Either<Boolean,ResponseFormat> result;
-
- Either<Component, StorageOperationStatus> resourceStatus = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getToscaElement(currentResource.getUniqueId()))
- .thenReturn(resourceStatus);
-
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateIcon", new Object[]{currentResource, updateInfoResource, hasBeenCertified});
- }
-
-
- @Test
- public void testValidateVendorName() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- boolean hasBeenCertified = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateVendorName", new Object[]{currentResource, updateInfoResource, hasBeenCertified});
- }
-
-
- @Test
- public void testValidateResourceVendorModelNumber() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);;
- Resource updateInfoResource = createResourceObject(true);;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceVendorModelNumber", new Object[]{currentResource, updateInfoResource});
- }
-
-
- @Test
- public void testValidateCategory() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);;
- Resource updateInfoResource = createResourceObject(true);;
- boolean hasBeenCertified = false;
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateCategory", new Object[]{currentResource, updateInfoResource, hasBeenCertified, inTransaction});
- }
-
-
- @Test
- public void testValidateDerivedFromDuringUpdate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- boolean hasBeenCertified = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateDerivedFromDuringUpdate", new Object[]{currentResource, updateInfoResource, hasBeenCertified});
- }
-
-
- @Test
- public void testValidateNestedDerivedFromDuringUpdate() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- boolean hasBeenCertified = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateNestedDerivedFromDuringUpdate", new Object[]{currentResource, updateInfoResource, hasBeenCertified});
- }
-
-
- @Test
- public void testValidateDerivedFromExist() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ACTIVATE_SERVICE_BY_API;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateDerivedFromExist", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test(expected=UnsupportedOperationException.class)
- public void testValidateDerivedFromExtending() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource currentResource = createResourceObject(true);
- Resource updateInfoResource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_CATEGORY;
- Either<Boolean,ResponseFormat> result;
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.validateToscaResourceNameExtends(currentResource.getDerivedFrom().get(0), updateInfoResource.getDerivedFrom().get(0))).thenReturn(dataModelResponse);
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateDerivedFromExtending", new Object[]{user, currentResource, updateInfoResource, actionEnum});
- }
-
-
- @Test
- public void testValidateResourceNameExists_2() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceNameExists", new Object[]{resource});
- }
-
-
- @Test
- public void testValidateCategory_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS;
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateCategory", new Object[]{user, resource, actionEnum, inTransaction});
- }
-
-
- @Test
- public void testValidateCategoryListed() throws Exception {
- ResourceBusinessLogic testSubject;
- CategoryDefinition category = null;
- SubCategoryDefinition subcategory = null;
- boolean inTransaction = false;
- Either<Boolean,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "validateCategoryListed", new Object[]{CategoryDefinition.class, SubCategoryDefinition.class, inTransaction});
-
- }
-
-
- @Test
- public void testValidateVendorReleaseName_2() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = null;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=testSubject.validateVendorReleaseName(user, resource, actionEnum);
- }
-
-
- @Test
- public void testValidateVendorReleaseName_3() throws Exception {
- ResourceBusinessLogic testSubject;
- String vendorRelease = "";
- Either<Boolean,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();vendorRelease = null;
- result=testSubject.validateVendorReleaseName(vendorRelease);
- }
-
-
- @Test
- public void testValidateVendorName_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ARTIFACT_DELETE;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateVendorName", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test
- public void testValidateResourceVendorModelNumber_1() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ARTIFACT_DELETE;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceVendorModelNumber", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test
- public void testValidateVendorName_2() throws Exception {
- ResourceBusinessLogic testSubject;
- String vendorName = "";
- Either<Boolean,ResponseFormat> result;
-
- // test 1
- testSubject=createTestSubject();
- result=Deencapsulation.invoke(testSubject, "validateVendorName", new Object[]{vendorName});
- }
-
-
- @Test
- public void testValidateResourceVendorModelNumber_2() throws Exception {
- ResourceBusinessLogic testSubject;
- String resourceVendorModelNumber = "";
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateResourceVendorModelNumber", new Object[]{resourceVendorModelNumber});
- }
-
-
- @Test
- public void testValidateCost() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_GROUPING;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateCost", new Object[]{user, resource, AuditingActionEnum.class});
- }
-
-
- @Test
- public void testValidateLicenseType() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- AuditingActionEnum actionEnum = AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL;
- Either<Boolean,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateLicenseType", new Object[]{user, resource, actionEnum});
- }
-
-
- @Test
- public void testDeleteMarkedComponents() throws Exception {
- ResourceBusinessLogic testSubject;
- Either<List<String>,ResponseFormat> result;
-
- Either<List<String>, StorageOperationStatus> deleteMarkedElements = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(deleteMarkedElements);
-
-
- // default test
- testSubject=createTestSubject();result=testSubject.deleteMarkedComponents();
- }
-
-
- @Test
- public void testGetComponentTypeForResponse() throws Exception {
- ResourceBusinessLogic testSubject;Component component = null;
- String result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getComponentTypeForResponse", new Object[]{Component.class});
- }
-
-
- @Test
- public void testCreateGroupsFromYaml() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlFileName = "";
- Map<String,Object> toscaJson = new HashMap<>();;
- Resource resource = createResourceObject(true);
- Either<Map<String,GroupDefinition>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createGroupsFromYaml", new Object[]{yamlFileName, toscaJson, resource});
- }
-
-
- @Test
- public void testCreateInputsFromYaml() throws Exception {
- ResourceBusinessLogic testSubject;
- String yamlFileName = "";
- Map<String,Object> toscaJson = new HashMap<>();;
- Resource resource = createResourceObject(true);
- Either<Map<String,InputDefinition>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createInputsFromYaml", new Object[]{yamlFileName, toscaJson, resource});
- }
-
-
- @Test
- public void testCreateGroupInfo() throws Exception {
- ResourceBusinessLogic testSubject;String groupName = "";
- Object groupTemplateJson = null;
- Either<GroupDefinition,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "createGroupInfo", new Object[]{groupName, Object.class});
- }
-
- @Test
- public void testGetValidComponentInstanceCapabilities() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
- Map<String,List<CapabilityDefinition>> defaultCapabilities = new HashMap<>();
- Map<String,List<UploadCapInfo>> uploadedCapabilities = new HashMap<>();
- Either<Map<String,List<CapabilityDefinition>>,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "getValidComponentInstanceCapabilities", new Object[]{resourceId, defaultCapabilities, uploadedCapabilities});
- }
-
-
- @Test
- public void testBuildNestedToscaResourceName() throws Exception {
- ResourceBusinessLogic testSubject;
- String nodeResourceType = "VF";
- String vfResourceName = "Resource12";
- String nodeTypeFullName = "org.openecomp.resource.VF.Resource12";
- ImmutablePair<String,String> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "buildNestedToscaResourceName", new Object[]{nodeResourceType, vfResourceName, nodeTypeFullName});
- }
-
-
- @Test
- public void testValidateAndUpdateInterfaces() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resourceUpdate = createResourceObject(true);;
- String resourceId = resourceUpdate.getUniqueId();
- Either<Boolean,ResponseFormat> result;
-
-
- Either<Component, StorageOperationStatus> resourceStorageOperationStatusEither = Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getToscaElement(resourceUpdate.getUniqueId())).thenReturn(resourceStorageOperationStatusEither);
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "validateAndUpdateInterfaces", new Object[]{resourceId, resourceUpdate});
- }
-
-
- @Test
- public void testUpdateInterfaceDefinition() throws Exception {
- ResourceBusinessLogic testSubject;
- Resource resourceUpdate = createResourceObject(true);
- InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
- Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName = new ArrayList<>();
- Either<InterfaceDefinition,ResponseFormat> result;
-
- // default test
- testSubject=createTestSubject();result=Deencapsulation.invoke(testSubject, "updateInterfaceDefinition", new Object[]{resourceUpdate, interfaceDefinition, interfaceDefinitionListFromToscaName});
- }
-
-
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.when;
+
+public class ResourceBusinessLogicTest {
+
+ private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class);
+ private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
+ private static final String RESOURCE_SUBCATEGORY = "Router";
+
+ private static final String UPDATED_SUBCATEGORY = "Gateway";
+
+ private static final String RESOURCE_NAME = "My-Resource_Name with space";
+ private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
+ 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_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
+
+ 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 PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.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);
+ @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);
+ @InjectMocks
+ CsarBusinessLogic csarBusinessLogic = new CsarBusinessLogic();
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
+ 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(user);
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(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);
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
+ 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.setCacheManagerOperation(cacheManager);
+ bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
+ toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
+ toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setUserValidations(userValidations);
+ csarBusinessLogic.setCsarOperation(csarOperation);
+ 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.setToscaResourceName(RESOURCE_TOSCA_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<>();
+ 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<>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<>();
+ 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);
+ Resource createdResource = null;
+ try{
+ createdResource= bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createResourceObject(true)).isEqualTo(createdResource);
+ } catch(ComponentException e){
+ assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
+ }
+ }
+
+ @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);
+ Resource createdResource = null;
+ try{
+ createdResource= bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
+ assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
+ } catch(ComponentException e){
+ assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
+ }
+ }
+
+
+ @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);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
+ }
+ }
+
+ private void testResourceNameEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setName(null);
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+
+ try {
+ bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceDescriptionEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription("");
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceDescriptionMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription(null);
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+ // Resource description - end
+ // Resource icon start
+
+ private void testResourceIconMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon(null);
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceIconInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("kjk3453^&");
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceIconExceedsLimit() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+ }
+
+ private void testResourceTagEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setTags(new ArrayList<>());
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ 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);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+
+ resourceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+ }
+ }
+
+ private void testInvalidTag() {
+ Resource serviceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb%#%";
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+
+ try {
+ bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceContactIdEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId("");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceContactIdMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testVendorNameExceedsLimit() {
+ Resource resourceExccedsVendorNameLimit = createResourceObject(false);
+ String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
+ try {
+ bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceVendorModelNumberExceedsLimit() {
+ Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
+ String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
+ try {
+ bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME);
+ }
+ }
+
+ private void testVendorReleaseWrongFormat() {
+ Resource resource = createResourceObject(false);
+ // contains >
+ String nameWrongFormat = "1>2";
+ resource.setVendorRelease(nameWrongFormat);
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE);
+ }
+ }
+
+ private void testVendorReleaseExceedsLimitCreate() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceVendorNameMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorName(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
+ }
+ }
+
+ private void testResourceVendorReleaseMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorRelease(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
+ }
+ }
+
+ // Resource vendor name/release stop
+ // Category start
+ private void testResourceCategoryExist() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceBadCategoryCreate() {
+
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+ resourceExist.addCategory("koko", "koko");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ Resource createdResource;
+ try{
+ createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ createResourceObjectAfterCreate.setCost(cost);
+ createResourceObjectAfterCreate.setLicenseType(licenseType);
+ assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
+ }catch(ComponentException e){
+ assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
+ }
+ }
+
+ private void testCostWrongFormatCreate() {
+ Resource resourceCost = createResourceObject(false);
+ // Comma instead of fullstop
+ String cost = "12356,464";
+ resourceCost.setCost(cost);
+ try {
+ bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+ // Cost stop
+ // License type start
+ private void testLicenseTypeWrongFormatCreate() {
+ Resource resourceLicenseType = createResourceObject(false);
+ // lowcase
+ String licenseType = "cpu";
+ resourceLicenseType.setLicenseType(licenseType);
+ try {
+ bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+ // License type stop
+ // Derived from start
+ private void testResourceTemplateNotExist() {
+ Resource resourceExist = createResourceObject(false);
+ List<String> list = null;
+ resourceExist.setDerivedFrom(list);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ private void testResourceTemplateEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDerivedFrom(new ArrayList<>());
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ private void testResourceTemplateInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ ArrayList<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add("kuku");
+ resourceExist.setDerivedFrom(derivedFrom);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+ }
+ // Derived from stop
+ private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat actualResponse = e.getResponseFormat() != null ?
+ e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ assertResponse(actualResponse, expectedStatus, variables);
+ }
+
+ private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
+ assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
+ }
+
+ private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
+ assertResponse(createResponse.right().value(), expectedStatus, variables);
+ }
+
+ // 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
+ }
+ }
+
+ @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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+ }
+
+ @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);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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(updatedResource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>());
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ derivedFrom.add("kuku");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, 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<>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertThat(createdResource).isNotNull();
+ }
+
+ @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<>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>());
+ when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode);
+
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ }
+ }
+ // Derived from stop
+
+ @Test
+ public void createOrUpdateResourceAlreadyCheckout() {
+ Resource resourceExist = createResourceObject(false);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ createdResource.setLastUpdaterUserId(user.getUserId());
+ assertThat(createdResource).isNotNull();
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName())).thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult);
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertNotNull(createOrUpdateResource);
+
+ 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);
+ Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+
+ assertThat(createdResource).isNotNull();
+ createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ createdResource.setVersion("1.0");
+
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName())).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(Either.left(createdResource));
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertNotNull(createOrUpdateResource);
+
+ 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);
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertThat(createOrUpdateResource).isNotNull();
+
+ Mockito.verify(toscaOperationFacade, times(1)).createToscaComponent(eq(resourceToUpdtae));
+ 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 updateNestedResource_typeIsNew() throws IOException {
+ Resource resourceToUpdate = createResourceObject(false);
+ String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
+ CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(),
+ RESOURCE_NAME, "template name", jsonContent, true);
+ String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight();
+ when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo,
+ nodeName, false);
+ assertThat(createOrUpdateResource).isNotNull();
+
+ Mockito.verify(toscaOperationFacade, times(1)).createToscaComponent(eq(resourceToUpdate));
+ Mockito.verify(toscaOperationFacade, times(0)).overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+ }
+
+ @Test
+ public void updateNestedResource_typeExists() throws IOException {
+ Resource resourceToUpdate = createResourceObject(false);
+ setCanWorkOnResource(resourceResponse);
+ String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
+ CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(),
+ RESOURCE_NAME, "template name", jsonContent, true);
+ String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight();
+ when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName)).thenReturn(Either.left(resourceResponse));
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(Either.left(resourceResponse));
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo,
+ nodeName, false);
+ assertThat(createOrUpdateResource).isNotNull();
+ Mockito.verify(toscaOperationFacade, times(1)).overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, 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());
+ }
+
+
+ @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();
+ assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size());
+ assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size());
+ assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size());
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testVFGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createVF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(6, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
+ }
+
+ @Test
+ public void testCRGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createCR();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(3, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), 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
+ assertEquals(6, 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
+ assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
+ //verify inputs were not deleted
+ assertEquals(6, resource.getInputs().size());
+ //verify inputs ownerId fields were removed - user may delete/edit inputs
+ assertEquals(6, 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<>());
+ genericVF.getProperties().add(newProp);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod();
+ String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
+ assertEquals(6, 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
+ assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
+ //verify inputs were not removed
+ assertEquals(7, resource.getInputs().size());
+ //verify user defined input exists
+ assertEquals(1, resource.getInputs()
+ .stream()
+ .filter(p -> null == p.getOwnerId())
+ .collect(Collectors.toList())
+ .size());
+ assertEquals("integer", resource.getInputs()
+ .stream()
+ .filter(p -> null == p.getOwnerId())
+ .findAny()
+ .get()
+ .getType());
+ }
+
+ @Test
+ public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createPNF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(3, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
+ assertEquals(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();
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+
+ 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();
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+ 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();
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+
+ 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>() {{
+ put("cr_function", "string");
+ put("cr_role", "string");
+ put("cr_type", "string");
+ }};
+
+ 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);
+ 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());
+ }
+
}
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 ab042b4a7d..e54ac699db 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
@@ -28,38 +28,30 @@ import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-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.*;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
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.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ConfigurationSource;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
import 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.*;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -97,19 +89,19 @@ public class ResourceInstanceBusinessLogicTest {
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>();
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
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>();
+ Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<>();
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>();
+ Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<>();
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);
@@ -117,7 +109,7 @@ public class ResourceInstanceBusinessLogicTest {
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));
+ // Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKey, Object>(AuditingFieldsKey.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);
@@ -129,14 +121,14 @@ public class ResourceInstanceBusinessLogicTest {
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));
+ Mockito.any(ResourceCommonInfo.class), Mockito.any(ResourceVersionInfo.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);
+ Mockito.any(Component.class), Mockito.any())).thenReturn(heatEnvEither);
- Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>());
+ Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<>());
Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft);
bl.setToscaOperationFacade(toscaOperationFacade);
@@ -219,7 +211,7 @@ public class ResourceInstanceBusinessLogicTest {
Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
assertNotNull(deploymentArtifacts);
- assertTrue(deploymentArtifacts.size() == 0);
+ assertEquals(0, deploymentArtifacts.size());
Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString());
}
@@ -247,7 +239,7 @@ public class ResourceInstanceBusinessLogicTest {
artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz");
if (withHeatParams) {
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
+ List<HeatParameterDefinition> heatParams = new ArrayList<>();
HeatParameterDefinition heatParam = new HeatParameterDefinition();
heatParam.setCurrentValue("11");
heatParam.setDefaultValue("22");
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java
new file mode 100644
index 0000000000..bd7056ef89
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java
@@ -0,0 +1,920 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.sdc.ElementOperationMock;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+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;
+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.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.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.DistributionDeployEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.web.context.WebApplicationContext;
+
+import javax.servlet.ServletContext;
+import java.lang.reflect.Method;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+public class ServiceBusinessLogicTest {
+
+ private static final String SERVICE_CATEGORY = "Mobility";
+ private static final String INSTANTIATION_TYPE = "A-la-carte";
+ private final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ private WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ private ServiceBusinessLogic bl = new ServiceBusinessLogic();
+ private ResponseFormatManager responseManager = null;
+ private ComponentsUtils componentsUtils;
+ private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
+ private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
+ private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ private TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
+ private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ private CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
+ private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
+ private UserValidations userValidations = Mockito.mock(UserValidations.class);
+ private ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class);
+ private ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class);
+ private ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class);
+
+ private User user = null;
+ private 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";
+
+ 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
+ IElementOperation 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(user);
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
+ 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);
+ 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
+ Service 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());
+ assertEquals(3, componentAuditRecords.left().value().size());
+ }
+
+ @Test
+ public void testGetComponentAuditRecordsUnCertifiedVersion() {
+ Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
+ assertTrue(componentAuditRecords.isLeft());
+ assertEquals(4, componentAuditRecords.left().value().size());
+ }
+
+ @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());
+ }
+
+ 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) {
+ assertResponse(createResponse.right().value(), expectedStatus, variables);
+ }
+
+ private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat actualResponse = e.getResponseFormat() != null ?
+ e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ assertResponse(actualResponse, expectedStatus, variables);
+ }
+
+ private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
+ assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
+ }
+
+
+ @Test
+ public void testFailedServiceValidations() {
+ testServiceNameAlreadyExists();
+ testServiceNameEmpty();
+ testServiceNameWrongFormat();
+ testServiceDescriptionEmpty();
+ testServiceDescriptionMissing();
+ testServiceDescExceedsLimitCreate();
+ testServiceDescNotEnglish();
+ testServiceIconEmpty();
+ testServiceIconMissing();
+ testResourceIconInvalid();
+ testResourceIconExceedsLimit();
+ 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<>();
+ 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);
+ try{
+ bl.createService(serviceExccedsNameLimit, user);
+ } catch(ComponentException e){
+ assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testServiceNameWrongFormat() {
+ Service service = createServiceObject(false);
+ // contains :
+ String nameWrongFormat = "ljg\fd";
+ service.setName(nameWrongFormat);
+ try{
+ bl.createService(service, user);
+ } catch(ComponentException e){
+ assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testServiceDescriptionEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setDescription("");
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e){
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testServiceDescriptionMissing() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setDescription(null);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e){
+ assertComponentException(e, 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);
+ try{
+ bl.createService(serviceExccedsDescLimit, user);
+ } catch(ComponentException e){
+ assertComponentException(e, 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);
+ try{
+ bl.createService(notEnglish, user);
+ } catch(ComponentException e){
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ // Service description - stop
+ // Service icon - start
+ private void testServiceIconEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setIcon("");
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testServiceIconMissing() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setIcon(null);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testResourceIconInvalid() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setIcon("kjk3453^&");
+ try{
+ bl.createService(resourceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testResourceIconExceedsLimit() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
+ try{
+ bl.createService(resourceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
+ }
+ }
+
+ private void testTagsNoServiceName() {
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ String tag1 = "afzs2qLBb";
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try{
+ bl.createService(serviceExccedsNameLimit, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+ }
+ }
+
+ private void testInvalidTag() {
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ String tag1 = "afzs2qLBb%#%";
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try{
+ bl.createService(serviceExccedsNameLimit, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
+ }
+ }
+
+ private void testServiceTagNotExist() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setTags(null);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+ }
+
+ private void testServiceTagEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setTags(new ArrayList<>());
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, 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);
+ try{
+ bl.createService(serviceContactId, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, 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);
+ try{
+ bl.createService(serviceContactId, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ private void testResourceContactIdMissing() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setContactId(null);
+ try{
+ bl.createService(resourceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ // Service contactId - stop
+ // Service category - start
+ private void testServiceCategoryExist() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setCategories(null);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ @Test
+ public void markDistributionAsDeployedTestAlreadyDeployed() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String resultAction = "DResult";
+ String did = "123456";
+
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<DistributionDeployEvent> resultList = new ArrayList<>();
+ Map<String, Object> params = new HashMap<>();
+ DistributionDeployEvent event = new DistributionDeployEvent();
+
+ event.setAction(resultAction);
+ event.setDid(did);
+ event.setStatus("200");
+ // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
+ // deployEvent.setFields(params);
+ resultList.add(event);
+ Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
+
+ Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
+
+ Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isLeft());
+
+ Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
+
+ }
+
+ @Test
+ public void markDistributionAsDeployedTestSuccess() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String did = "123456";
+
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.OPS);
+ Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isLeft());
+ }
+
+ @Test
+ public void markDistributionAsDeployedTestNotDistributed() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String did = "123456";
+
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<ResourceAdminEvent> emptyList = new ArrayList<>();
+ 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<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isRight());
+ assertEquals(404, markDeployed.right().value().getStatus().intValue());
+
+ }
+
+ private void testServiceBadCategoryCreate() {
+
+ Service serviceExist = createServiceObject(false);
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName("koko");
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ serviceExist.setCategories(categories);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ }
+ }
+
+ // Service category - stop
+ // Service projectCode - start
+ private void testInvalidProjectCode() {
+
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode("koko!!");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
+
+ private void testProjectCodeTooLong() {
+
+ Service serviceExist = createServiceObject(false);
+ String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
+ serviceExist.setProjectCode(tooLongProjectCode);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
+
+ private void testProjectCodeTooShort() {
+
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode("333");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
+
+ private void testMissingProjectCode() {
+
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode(null);
+ try{
+ bl.createService(serviceExist, user);
+ } catch(ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
+ }
+ }
+
+ @Test
+ public void testDeleteMarkedServices() {
+ List<String> ids = new ArrayList<>();
+ List<String> responseIds = new ArrayList<>();
+ String resourceInUse = "123";
+ ids.add(resourceInUse);
+ String resourceFree = "456";
+ ids.add(resourceFree);
+ responseIds.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<>();
+ Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
+
+ Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
+ when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
+ when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
+ 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.setInstantiationType(INSTANTIATION_TYPE);
+
+ service.setDescription("description");
+ List<String> tgs = new ArrayList<>();
+ tgs.add(service.getName());
+ service.setTags(tgs);
+ service.setIcon("MyIcon");
+ 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() {
+ 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");
+ 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<>();
+ 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);
+
+ Either<List<ResourceAdminEvent>, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2));
+ when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList);
+
+ Either<List<ResourceAdminEvent>, ActionStatus> restoreAuditList = Either.left(Arrays.asList(auditRestore));
+ when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList);
+
+ }
+
+ 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");
+
+ List<DistributionNotificationEvent> notifyResults = Collections.singletonList(notifyEvent);
+ Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
+
+ Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
+
+ List<ResourceAdminEvent> requestResults = Collections.singletonList(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);
+
+ Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(Collections.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);
+ assertNotNull(findGroupInstanceRes);
+ assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
+ .getUniqueId());
+ assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), 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);
+ assertNotNull(findGroupInstanceRes);
+ assertTrue(findGroupInstanceRes.isRight());
+ assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
+
+ Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
+
+ findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
+ assertNotNull(findGroupInstanceRes);
+ assertTrue(findGroupInstanceRes.isRight());
+ assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
+ }
+ 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();
+ assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
+ assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
+ }
+
+ @Test
+ public void testUpdateMetadataNamingPolicy() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setEcompGeneratedNaming(false);
+ newService.setEcompGeneratedNaming(true);
+ newService.setNamingPolicy("policy");
+ Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
+ assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
+ }
+
+ @Test
+ public void testUpdateMetadataServiceType() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setServiceType("alice");
+ //valid English word
+ newService.setServiceType("bob");
+ Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
+ //empty string is invalid
+ newService.setServiceType("");
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ //null is invalid
+ newService.setServiceType(null);
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
+ assertThat(resultOfUpdate.isRight()).isTrue();
+ }
+
+ 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/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java
index 309689af45..6f23faa25b 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 {
@@ -42,6 +41,7 @@ public class GenericTypeBusinessLogicTest {
Resource cvfc = new Resource();
cvfc.setResourceType(ResourceTypeEnum.CVFC);
cvfc.setDerivedFrom(Arrays.asList("genericType", "someOtherType"));
+ cvfc.setDerivedFromGenericType("genericType");
Resource genericResource = new Resource();
when(toscaOperationFacadeMock.getLatestCertifiedNodeTypeByToscaResourceName("genericType")).thenReturn(Either.left(genericResource));
Either<Resource, ResponseFormat> fetchedGenericType = testInstance.fetchDerivedFromGenericType(cvfc);
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestratorTest.java
new file mode 100644
index 0000000000..cd925cb016
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestratorTest.java
@@ -0,0 +1,106 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+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 ComponentInstanceChangeOperationOrchestratorTest {
+
+ private static final Resource CONTAINER = new Resource();
+ private static final ComponentInstance NEW_VERSION = new ComponentInstance();
+ private static final ComponentInstance PREV_VERSION = new ComponentInstance();
+ private static final String DELETED_INS_ID = "id";
+ private ComponentInstanceChangeOperationOrchestrator testInstance;
+ @Mock
+ private OnComponentInstanceChangeOperation componentInstanceChangeOperation1;
+ @Mock
+ private OnComponentInstanceChangeOperation componentInstanceChangeOperation2;
+ @Mock
+ private OnComponentInstanceChangeOperation componentInstanceChangeOperation3;
+
+ @Before
+ public void setUp() throws Exception {
+ testInstance = new ComponentInstanceChangeOperationOrchestrator(asList(componentInstanceChangeOperation1, componentInstanceChangeOperation2, componentInstanceChangeOperation3));
+ }
+
+ @Test
+ public void doPostChangeVersionOperations_whenFirstPostOperationFails_doNotRunFollowingOperations() {
+ when(componentInstanceChangeOperation1.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(CONTAINER, PREV_VERSION, NEW_VERSION);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(componentInstanceChangeOperation2, componentInstanceChangeOperation3);
+ }
+
+ @Test
+ public void doPostChangeVersionOperations_whenAnyPostOperationFails_doNotRunFollowingOperations() {
+ when(componentInstanceChangeOperation1.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(CONTAINER, PREV_VERSION, NEW_VERSION);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(componentInstanceChangeOperation3);
+ }
+
+ @Test
+ public void doPostChangeVersionOperations_whenLastPostOperationFails_returnTheFailureResult() {
+ when(componentInstanceChangeOperation1.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation3.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(CONTAINER, PREV_VERSION, NEW_VERSION);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void doPostChangeVersionOperations_whenAllOperationsSucceeds_returnOk() {
+ when(componentInstanceChangeOperation1.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation3.onChangeVersion(CONTAINER, PREV_VERSION, NEW_VERSION)).thenReturn(ActionStatus.OK);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(CONTAINER, PREV_VERSION, NEW_VERSION);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void doOnDeleteInstanceOperations_whenFirstPostOperationFails_doNotRunFollowingOperations() {
+ when(componentInstanceChangeOperation1.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doOnDeleteInstanceOperations(CONTAINER, DELETED_INS_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(componentInstanceChangeOperation2, componentInstanceChangeOperation3);
+ }
+
+ @Test
+ public void doOnDeleteInstanceOperations_whenAnyPostOperationFails_doNotRunFollowingOperations() {
+ when(componentInstanceChangeOperation1.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doOnDeleteInstanceOperations(CONTAINER, DELETED_INS_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(componentInstanceChangeOperation3);
+ }
+
+ @Test
+ public void doOnDeleteInstanceOperations_whenLastPostOperationFails_returnTheFailureResult() {
+ when(componentInstanceChangeOperation1.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation3.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doOnDeleteInstanceOperations(CONTAINER, DELETED_INS_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void doOnDeleteInstanceOperations_whenAllOperationsSucceeds_returnOk() {
+ when(componentInstanceChangeOperation1.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation2.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ when(componentInstanceChangeOperation3.onDelete(CONTAINER, DELETED_INS_ID)).thenReturn(ActionStatus.OK);
+ ActionStatus actionStatus = testInstance.doOnDeleteInstanceOperations(CONTAINER, DELETED_INS_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+} \ No newline at end of file
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/instance/GroupMembersUpdateOperationTest.java
index 6d7ae39cc2..7cad89c2ec 100644
--- 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/instance/GroupMembersUpdateOperationTest.java
@@ -1,22 +1,15 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-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;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Stream;
+package org.openecomp.sdc.be.components.impl.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.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater;
import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
@@ -30,7 +23,16 @@ 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 fj.data.Either;
+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.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class GroupMembersUpdateOperationTest {
@@ -38,28 +40,26 @@ 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();
+ private static final ComponentInstance DONT_CARE_WHICH_INST = new ComponentInstance();
+ private static final String DONT_CARE_WHICH_ID = "someString";
@Before
public void setUp() throws Exception {
+ testInstance = new GroupMembersUpdateOperation(groupsOperation, new ComponentsUtils(mock(AuditingManager.class)), new GroupMembersUpdater());
group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE);
- group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3");
+ group2 = createGroupWithMembers("group2", "inst1", INSTANCE_ID_PRE_CHANGE, "inst3");
group3 = createGroupWithMembers("group3", "inst1", "inst3");
container = new ResourceBuilder()
- .addGroups(group1)
- .addGroups(group2)
+ .addGroup(group1)
+ .addGroup(group2)
.setUniqueId(CONTAINER_ID)
.setComponentType(ComponentTypeEnum.RESOURCE)
.build();
@@ -72,60 +72,114 @@ public class GroupMembersUpdateOperationTest {
}
@Test
- public void whenNoGroupsOnContainer_returnOk() {
- ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE);
+ public void onChangeVersion_whenNoGroupsOnContainer_returnOk() {
+ ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE_WHICH_INST, DONT_CARE_WHICH_INST);
assertThat(actionStatus).isEqualTo(ActionStatus.OK);
}
@Test
- public void whenEmptyListOfGroups_returnOk() {
+ public void onChangeVersion_whenEmptyListOfGroups_returnOk() {
Resource resource = new Resource();
resource.setGroups(new ArrayList<>());
- ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE);
+ ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE_WHICH_INST, DONT_CARE_WHICH_INST);
assertThat(actionStatus).isEqualTo(ActionStatus.OK);
}
@Test
- public void whenGroupsHasNoMembers_returnOk() {
+ public void onChangeVersion_whenGroupsHasNoMembers_returnOk() {
GroupDefinition group1 = new GroupDefinition();
group1.setMembers(emptyMap());
GroupDefinition group2 = new GroupDefinition();
group2.setMembers(emptyMap());
Resource container = new ResourceBuilder()
- .addGroups(group1)
- .addGroups(group2)
+ .addGroup(group1)
+ .addGroup(group2)
.build();
ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build();
- ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE);
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE_WHICH_INST);
assertThat(actionStatus).isEqualTo(ActionStatus.OK);
}
@Test
- public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() {
+ public void onChangeVersion_whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() {
ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build();
- ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE);
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE_WHICH_INST);
assertThat(actionStatus).isEqualTo(ActionStatus.OK);
}
@Test
- public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() {
+ public void onChangeVersion_whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() {
verifyAllGroupsHasPrevInstancesAsMembers();
- when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null));
+ when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture(), eq(false))).thenReturn(Either.left(null));
ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version);
assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ assertUpdatedGroups(updatedGroupsCaptor.getValue(), group1, group2);
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();
+ public void onChangeVersion_whenFailingToUpdateGroups_propagateError() {
+ when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture(), eq(false))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version);
assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
}
+ @Test
+ public void onDeleteInstance_whenNoGroupsOnContainer_returnOk() {
+ ActionStatus actionStatus = testInstance.onDelete(new Resource(), DONT_CARE_WHICH_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void onDeleteInstance_whenEmptyListOfGroups_returnOk() {
+ Resource resource = new Resource();
+ resource.setGroups(new ArrayList<>());
+ ActionStatus actionStatus = testInstance.onDelete(resource, DONT_CARE_WHICH_ID);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void onDeleteInstance_whenGroupsHasNoMembers_returnOk() {
+ GroupDefinition group1 = new GroupDefinition();
+ group1.setMembers(emptyMap());
+ GroupDefinition group2 = new GroupDefinition();
+ group2.setMembers(emptyMap());
+ Resource container = new ResourceBuilder()
+ .addGroup(group1)
+ .addGroup(group2)
+ .build();
+ ActionStatus actionStatus = testInstance.onDelete(container, "inst1");
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void onDeleteInstance_whenDeletedInstanceIsNotAMemberOfAnyGroup_returnOk() {
+ ActionStatus actionStatus = testInstance.onDelete(container, "nonMemberInst");
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void onDeleteInstance_removeInstanceIdFromGroupMember() {
+ when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture(), eq(false))).thenReturn(Either.left(null));
+ ActionStatus actionStatus = testInstance.onDelete(container, INSTANCE_ID_PRE_CHANGE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ assertUpdatedGroups(updatedGroupsCaptor.getValue(), group1, group2);
+ assertGroupMembersIds(group1, "inst1");
+ assertGroupMembersIds(group2, "inst1", "inst3");
+ }
+
+ @Test
+ public void onDeleteInstance_whenGroupsUpdateFails_propagateTheFailure() {
+ when(groupsOperation.updateGroups(eq(container), anyList(), eq(false))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ ActionStatus actionStatus = testInstance.onDelete(container, INSTANCE_ID_PRE_CHANGE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ private void assertUpdatedGroups(List<GroupDataDefinition> actual, GroupDataDefinition ... expected) {
+ assertThat(actual)
+ .containsExactlyInAnyOrder(expected);
+ }
+
private void verifyGroupWithPrevInstanceMemberWereReplaced() {
assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE);
assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3");
@@ -145,7 +199,7 @@ public class GroupMembersUpdateOperationTest {
private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) {
GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create();
- Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId));
+ Stream.of(membersIds).forEach(groupDefinitionBuilder::addMember);
groupDefinitionBuilder.setUniqueId(groupId);
return groupDefinitionBuilder.build();
}
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/instance/PolicyTargetsUpdateOperationTest.java
index 5da782e484..dbacd82e74 100644
--- 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/instance/PolicyTargetsUpdateOperationTest.java
@@ -1,14 +1,4 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-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;
-
-import java.util.List;
-import java.util.stream.Stream;
+package org.openecomp.sdc.be.components.impl.instance;
import org.junit.Before;
import org.junit.Test;
@@ -17,6 +7,8 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
+import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdater;
import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
@@ -28,6 +20,16 @@ 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 {
@@ -39,25 +41,26 @@ public class PolicyTargetsUpdateOperationTest {
@Captor
private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor;
- private PolicyDefinition policy1, policy2, policy3;
+ private PolicyDefinition policyWithInstanceTarget1, policyWithInstanceTarget2, policyWithInstanceTarget3;
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");
+ policyWithInstanceTarget1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2");
+ policyWithInstanceTarget2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3");
+ policyWithInstanceTarget3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3");
container = new ResourceBuilder()
- .addPolicy(policy1)
- .addPolicy(policy2)
- .addPolicy(policy3)
+ .addPolicy(policyWithInstanceTarget1)
+ .addPolicy(policyWithInstanceTarget2)
+ .addPolicy(policyWithInstanceTarget3)
.setUniqueId(CONTAINER_ID)
.build();
- policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils());
+ PolicyTargetsUpdateHandler policyTargetsUpdateHandler = new PolicyTargetsUpdateHandler(toscaOperationFacade, getComponentsUtils(), new PolicyTargetsUpdater());
+ policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(policyTargetsUpdateHandler);
}
@Test
- public void whenNoPolicies_returnActionOk() {
+ public void onChangeVersion_whenNoPolicies_returnActionOk() {
Component container = new Resource();
ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build();
@@ -67,7 +70,7 @@ public class PolicyTargetsUpdateOperationTest {
}
@Test
- public void whenNoCmptInstancePolicies_returnOk() {
+ public void onChangeVersion_whenNoCmptInstancePolicies_returnOk() {
PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build();
Component container = new ResourceBuilder().addPolicy(policy).build();
ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
@@ -78,7 +81,7 @@ public class PolicyTargetsUpdateOperationTest {
}
@Test
- public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() {
+ public void onChangeVersion_whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() {
ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build();
ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
@@ -87,20 +90,20 @@ public class PolicyTargetsUpdateOperationTest {
}
@Test
- public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() {
+ public void onChangeVersion_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");
+ verifyUpdatedPolicies(updatedPolicies, policyWithInstanceTarget1, policyWithInstanceTarget2);//policy3 does not have "inst2" as target, no update needed
+ verifyUpdatedPolicyTargets(policyWithInstanceTarget1, "inst1", "inst2New");
+ verifyUpdatedPolicyTargets(policyWithInstanceTarget2, "inst1", "inst2New", "inst3");
}
@Test
- public void whenUpdateOfPoliciesFails_propagateTheFailure() {
+ public void onChangeVersion_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);
@@ -108,6 +111,48 @@ public class PolicyTargetsUpdateOperationTest {
assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR);
}
+ @Test
+ public void onDeleteInstance_whenNoPolicies_returnActionOk() {
+ Component container = new Resource();
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onDelete(container, "instToDel");
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_whenNoCmptInstancePolicies_returnOk() {
+ PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build();
+ Component container = new ResourceBuilder().addPolicy(policy).build();
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onDelete(container, "instToDel");
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_whenNoPoliciesWithInstanceAsTarget_returnActionOk() {
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onDelete(container, "instToDel");
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_removeDeletedTargetFromPolicies() {
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK);
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onDelete(container, "inst2");
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue();
+ verifyUpdatedPolicies(updatedPolicies, policyWithInstanceTarget1, policyWithInstanceTarget2);
+ verifyUpdatedPolicyTargets(policyWithInstanceTarget1, "inst1");
+ verifyUpdatedPolicyTargets(policyWithInstanceTarget2, "inst1", "inst3");
+ }
+
+ @Test
+ public void onDeleteInstance_whenFailingToUpdatePolicies_propagateTheError() {
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onDelete(container, "inst2");
+ assertThat(operationStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) {
assertThat(updatedPolicy.resolveComponentInstanceTargets())
.containsExactlyInAnyOrder(expectedCmptInstanceTargetIds);
@@ -124,4 +169,5 @@ public class PolicyTargetsUpdateOperationTest {
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/policy/PolicyTargetsUpdateHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java
new file mode 100644
index 0000000000..40dc3dbeb1
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java
@@ -0,0 +1,117 @@
+package org.openecomp.sdc.be.components.impl.policy;
+
+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.impl.exceptions.ComponentException;
+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.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.model.Component;
+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)
+//note that this class only tests group targets, the tests for instance targets are under PolicyTargetsUpdateOperationTest
+public class PolicyTargetsUpdateHandlerTest {
+
+ private static final String CONTAINER_ID = "containerId";
+
+ private PolicyTargetsUpdateHandler testInstance;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Captor
+ private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor;
+ private PolicyDefinition policyWithGroupTarget1, policyWithGroupTarget2, policyWithGroupTarget3;
+ private Resource container;
+
+ @Before
+ public void setUp() throws Exception {
+ policyWithGroupTarget1 = createPolicyWithGroupsAsTargets("policy1", "group1", "group2");
+ policyWithGroupTarget2 = createPolicyWithGroupsAsTargets("policy2", "group1", "group2", "group3");
+ policyWithGroupTarget3 = createPolicyWithGroupsAsTargets("policy3", "group1", "group3");
+ container = new ResourceBuilder()
+ .addPolicy(policyWithGroupTarget1)
+ .addPolicy(policyWithGroupTarget2)
+ .addPolicy(policyWithGroupTarget3)
+ .setUniqueId(CONTAINER_ID)
+ .build();
+ testInstance = new PolicyTargetsUpdateHandler(toscaOperationFacade, getComponentsUtils(), new PolicyTargetsUpdater());
+ }
+
+
+ @Test
+ public void onDeleteInstance_whenNoPolicies_returnActionOk() {
+ Component container = new Resource();
+ testInstance.removePoliciesTargets(container, "groupToDel", PolicyTargetType.GROUPS);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_whenNoPoliciesWithGroupsAsTargets_returnOk() {
+ PolicyDefinition policy = PolicyDefinitionBuilder.create().addComponentInstanceTarget("someInst").build();
+ Component container = new ResourceBuilder().addPolicy(policy).build();
+ testInstance.removePoliciesTargets(container, "groupToDel", PolicyTargetType.GROUPS);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_whenNoPoliciesWithGivenGroupAsTarget_returnActionOk() {
+ testInstance.removePoliciesTargets(container, "groupToDel", PolicyTargetType.GROUPS);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void onDeleteInstance_removeDeletedTargetFromPolicies() {
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK);
+ testInstance.removePoliciesTargets(container, "group2", PolicyTargetType.GROUPS);
+ List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue();
+ verifyUpdatedPolicies(updatedPolicies, policyWithGroupTarget1, policyWithGroupTarget2);
+ verifyUpdatedPolicyTargets(policyWithGroupTarget1, "group1");
+ verifyUpdatedPolicyTargets(policyWithGroupTarget2, "group1", "group3");
+ }
+
+ @Test
+ public void onDeleteInstance_whenFailingToUpdatePolicies_throwException() {
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ try {
+ testInstance.removePoliciesTargets(container, "group2", PolicyTargetType.GROUPS);
+ } catch (ComponentException e) {
+ assertThat(e.getActionStatus()).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) {
+ assertThat(updatedPolicy.resolveGroupTargets())
+ .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds);
+ }
+
+ private void verifyUpdatedPolicies(List<PolicyDefinition> updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) {
+ assertThat(updatedPolicies)
+ .usingElementComparatorOnFields("targets")
+ .containsExactlyInAnyOrder(expectedUpdatedPolicies);
+ }
+
+ private PolicyDefinition createPolicyWithGroupsAsTargets(String uniqueId, String ... groupId) {
+ PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create();
+ Stream.of(groupId).forEach(policyDefinitionBuilder::addGroupTarget);
+ 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/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java
index 8fd262d1f2..7e475b528a 100644
--- 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
@@ -1,12 +1,6 @@
package org.openecomp.sdc.be.components.impl.utils;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
+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;
@@ -15,7 +9,12 @@ 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 com.google.common.collect.ImmutableMap;
+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 {
@@ -64,6 +63,22 @@ public class PolicyTypeImportUtilsTest {
}
@Test
+ public void whenNameIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setName("newName");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void whenIconIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setIcon("newIcon");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() {
PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
@@ -104,6 +119,19 @@ public class PolicyTypeImportUtilsTest {
}
@Test
+ public void whenBothPropertiesListNull_returnTrue() {
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals( new PolicyTypeDefinition(), new PolicyTypeDefinition())).isTrue();
+ }
+
+ @Test
+ public void whenOnePropertiesListIsNullAndSecondOneIsEmpty_returnTrue() {
+ PolicyTypeDefinition noProperties = new PolicyTypeDefinition();
+ PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, emptyProperties)).isTrue();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, noProperties)).isTrue();
+ }
+
+ @Test
public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() {
PolicyTypeDefinition noProperties = new PolicyTypeDefinition();
PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build();
@@ -231,6 +259,8 @@ public class PolicyTypeImportUtilsTest {
.setCreationTime(System.currentTimeMillis())
.setTargets(getTargets())
.setOwner("owner")
+ .setName("name")
+ .setIcon("icon")
.setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2"))
.build();
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java
new file mode 100644
index 0000000000..055276b243
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java
@@ -0,0 +1,194 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import org.assertj.core.util.Lists;
+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.components.csar.YamlTemplateParsingHandler;
+import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
+import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
+import org.openecomp.sdc.be.components.validation.AnnotationValidator;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
+import org.openecomp.sdc.common.util.ZipUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.stream.Collectors;
+
+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 YamlTemplateParsingHandlerTest {
+
+ private final static String VFC_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup";
+ private final static String HEAT_GROUP_TYPE = "org.openecomp.groups.heat.HeatStack";
+ private final static String ROOT_GROUP_TYPE = "tosca.groups.Root";
+ private final static GroupTypeDefinition VfcInstanceGroupType = buildVfcInstanceGroupType();
+ private final static GroupTypeDefinition heatGroupType = buildHeatStackGroupType();
+ private final static GroupTypeDefinition rootGroupType = buildRootGroupType();
+ private final static String CAPABILITY_TYPE = "org.openecomp.capabilities.VLANAssignment";
+ private final static String CAPABILITY_NAME = "vlan_assignment";
+ public static final String csarsFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "csars" ;
+
+ private YamlTemplateParsingHandler handler;
+ private AnnotationBusinessLogic annotationBusinessLogic;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private GroupTypeBusinessLogic groupTypeBusinessLogic;
+ @Mock
+ private AnnotationTypeOperations annotationTypeOperations;
+ @Mock
+ private AnnotationValidator annotationValidator;
+ @Mock
+ private TitanDao titanDao;
+
+ @Before
+ public void init(){
+ annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations, annotationValidator);
+ handler = new YamlTemplateParsingHandler(titanDao, groupTypeBusinessLogic, annotationBusinessLogic);
+ }
+
+ @Test
+ public void parseResourceInfoFromYAMLTest(){
+ Path path = Paths.get(csarsFilePath + File.separator + "with_groups.csar");
+ try {
+ Map<String, byte[]> csar = ZipUtil.readZip(Files.readAllBytes(path));
+ String fileName = "MainServiceTemplate.yaml";
+ Optional<String> keyOp = csar.keySet().stream().filter(k -> k.endsWith(fileName)).findAny();
+ byte[] mainTemplateService = csar.get(keyOp.get());
+ Properties props = new Properties();
+ String resourceYml = new String(mainTemplateService);
+ props.load(new StringReader(resourceYml.replace("\\","\\\\")));
+ Resource resource = new Resource();
+
+ stubGetGroupType();
+
+ ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(fileName, resourceYml, new HashMap<>(), new HashMap<>(), "");
+
+ validateParsedYaml(parsedYaml);
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+
+ private void validateParsedYaml(ParsedToscaYamlInfo parsedYaml) {
+ assertThat(parsedYaml).isNotNull();
+ assertThat(parsedYaml.getGroups()).isNotNull().containsKey("x_group");
+ assertThat(parsedYaml.getGroups().get("x_group")).isNotNull();
+ assertThat(parsedYaml.getGroups().get("x_group").getProperties()).isNotNull();
+ assertThat(parsedYaml.getGroups().get("x_group").getProperties()
+ .stream()
+ .map(PropertyDataDefinition::getName)
+ .collect(Collectors.toList()))
+ .containsAll(Lists.newArrayList("vfc_parent_port_role", "network_collection_function", "vfc_instance_group_function", "subinterface_role"));
+ assertThat(parsedYaml.getGroups().get("x_group").getCapabilities()
+ .get(CAPABILITY_TYPE)
+ .get(0).getProperties().get(0).getValue()).isEqualTo("success");
+ assertThat(parsedYaml.getGroups().get("x_group").getProperties()
+ .stream()
+ .map(PropertyDataDefinition::getName)
+ .collect(Collectors.toList()))
+ .containsAll(Lists.newArrayList("vfc_parent_port_role", "network_collection_function", "vfc_instance_group_function", "subinterface_role"));
+ assertThat(parsedYaml.getGroups().get("x_group").getCapabilities()).isNotNull();
+ assertThat(parsedYaml.getGroups().get("x_group").getMembers()).isNotNull();
+ }
+
+ private void stubGetGroupType() {
+ when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE))).thenReturn(VfcInstanceGroupType);
+ when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE))).thenReturn(heatGroupType);
+ when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(ROOT_GROUP_TYPE))).thenReturn(rootGroupType);
+// when(annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(any(Map.class))).thenReturn(null);
+ }
+
+ private static GroupTypeDefinition buildRootGroupType() {
+ GroupTypeDefinition groupType = new GroupTypeDefinition();
+ groupType.setType(ROOT_GROUP_TYPE);
+ groupType.setDescription("The TOSCA Group Type all other TOSCA Group Types derive from");
+ return groupType;
+ }
+
+ private static GroupTypeDefinition buildHeatStackGroupType() {
+ GroupTypeDefinition groupType = new GroupTypeDefinition();
+ groupType.setType(HEAT_GROUP_TYPE);
+ groupType.setDerivedFrom("tosca.groups.Root");
+ groupType.setDescription("Grouped all heat resources which are in the same heat stack");
+
+ GroupProperty property1 = new GroupProperty();
+ property1.setName("heat_file");
+ property1.setType("string");
+ property1.setRequired(true);
+ property1.setDescription("Heat file which associate to this group/heat stack");
+ property1.setStatus("SUPPORTED");
+
+ GroupProperty property2 = new GroupProperty();
+ property2.setName("description");
+ property2.setType("string");
+ property2.setRequired(true);
+ property2.setDescription("group description");
+ property2.setStatus("SUPPORTED");
+ groupType.setProperties(Lists.newArrayList(property1, property2));
+ return groupType;
+ }
+
+ private static GroupTypeDefinition buildVfcInstanceGroupType() {
+ GroupTypeDefinition groupType = new GroupTypeDefinition();
+ groupType.setType(VFC_GROUP_TYPE);
+ groupType.setDerivedFrom("tosca.groups.Root");
+ groupType.setDescription("groups VFCs with same parent port role");
+ GroupProperty property1 = new GroupProperty();
+ property1.setName("vfc_instance_group_function");
+ property1.setType("string");
+ property1.setRequired(true);
+ property1.setDescription("function of this VFC group");
+
+ GroupProperty property2 = new GroupProperty();
+ property2.setName("vfc_parent_port_role");
+ property2.setType("string");
+ property2.setRequired(true);
+ property2.setDescription("common role of parent ports of VFCs in this group");
+
+ GroupProperty property3 = new GroupProperty();
+ property3.setName("network_collection_function");
+ property3.setType("string");
+ property3.setRequired(true);
+ property3.setDescription("network collection function assigned to this group");
+
+ GroupProperty property4 = new GroupProperty();
+ property4.setName("subinterface_role");
+ property4.setType("string");
+ property4.setRequired(true);
+ property4.setDescription("common role of subinterfaces of VFCs in this group, criteria the group is created");
+
+ groupType.setProperties(Lists.newArrayList(property1, property2, property3, property4));
+
+ CapabilityDefinition capability = new CapabilityDefinition();
+ capability.setType(CAPABILITY_TYPE);
+ capability.setName(CAPABILITY_NAME);
+ ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty();
+ capabilityProperty.setName("vfc_instance_group_reference");
+ capabilityProperty.setType("string");
+ capability.setProperties(Arrays.asList(capabilityProperty));
+
+ Map<String, CapabilityDefinition> capabilityMap = new HashMap<>();
+ capabilityMap.put(CAPABILITY_NAME, capability);
+ groupType.setCapabilities(capabilityMap);
+ return groupType;
+ }
+
+}
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
deleted file mode 100644
index c6fea4af6f..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-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;
-
-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;
-
-@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