* 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=========================================================
- * Modifications copyright (c) 2019 Nokia
- * ================================================================================
*/
package org.openecomp.sdc.be.components.impl;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
import fj.data.Either;
+import java.lang.reflect.Method;
+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.Optional;
+import java.util.Set;
+import java.util.UUID;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Before;
-import org.junit.Test;
+import org.hamcrest.MatcherAssert;
+import org.junit.Assert;
+import org.junit.jupiter.api.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.ByActionStatusComponentException;
-import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
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.JanusGraphDao;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
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.datatypes.enums.ModelTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
+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.ComponentInstanceInterface;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.Model;
+import org.openecomp.sdc.be.model.Operation;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
+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.GraphLockOperation;
+import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
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.types.ServiceConsumptionData;
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 org.springframework.http.HttpStatus;
-import javax.servlet.ServletContext;
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+class ServiceBusinessLogicTest extends ServiceBusinessLogicBaseTestSetup {
-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.eq;
-
-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 JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
- private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.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.setJanusGraphGenericDao(mockJanusGraphDao);
- bl.setToscaOperationFacade(toscaOperationFacade);
- bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
- bl.setComponentsUtils(componentsUtils);
- bl.setCassandraAuditingDao(auditingDao);
- 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());
+ private final static String DEFAULT_ICON = "defaulticon";
+ private static final String ALREADY_EXIST = "alreadyExist";
+ private static final boolean MULTITENANCY_ENABLED = true;
+ private static final String TEST_TENANT = "test_tenant";
+
+ @Test
+ 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());
+ 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() {
+ void testHappyScenario() {
Service service = createServiceObject(false);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
if (createResponse.isRight()) {
assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
}
- private void validateUserRoles(Role ... roles) {
- List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
+ @Test
+ void testServiceCreationPluginCall() {
+ final Service service = createServiceObject(false);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
+ final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
+ serviceCreationPlugins.add(new ServiceCreationPlugin() {
+ @Override
+ public void beforeCreate(Service service) {
+ //do nothing
+ }
+
+ @Override
+ public int getOrder() {
+ return 0;
+ }
+ });
+ serviceCreationPlugins.add(new ServiceCreationPlugin() {
+ @Override
+ public void beforeCreate(Service service) {
+ throw new RuntimeException();
+ }
+
+ @Override
+ public int getOrder() {
+ return 0;
+ }
+ });
+ bl.setServiceCreationPluginList(serviceCreationPlugins);
+ final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+ assertTrue(createResponse.isLeft());
}
- 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());
+ @Test
+ void testCreateServiceWhenGenericTypeHasProperties() {
+ final Service service = createServiceObject(false);
+
+ final Resource genericTypeResource = mockGenericTypeResource();
+
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
+ final Service expectedService = createServiceObject(true);
+ expectedService.setProperties(mockPropertyList());
+ when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+
+ org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
+ createResponse.isLeft(), is(true));
+ final Service actualService = createResponse.left().value();
+ org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
+
+ assertEqualsServiceObject(expectedService, actualService);
}
- private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- assertResponse(createResponse.right().value(), expectedStatus, variables);
+ @Test
+ void testCreateServiceWhenGenericTypeAndServiceHasProperties() {
+ final Service service = createServiceObject(false);
+ service.setProperties(mockPropertyList());
+ service.getProperties().remove(0);
+ final PropertyDefinition serviceProperty = new PropertyDefinition();
+ serviceProperty.setName("aServiceProperty");
+ service.getProperties().add(serviceProperty);
+
+ final Resource genericTypeResource = mockGenericTypeResource();
+
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
+ final Service expectedService = createServiceObject(true);
+ expectedService.setProperties(mockPropertyList());
+ expectedService.getProperties().add(serviceProperty);
+ when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+
+ org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
+ createResponse.isLeft(), is(true));
+ final Service actualService = createResponse.left().value();
+ org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
+
+
+ assertEqualsServiceObject(expectedService, actualService);
}
- private void assertComponentException(ByActionStatusComponentException e, ActionStatus expectedStatus, String... variables) {
- ResponseFormat actualResponse = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
- assertResponse(actualResponse, expectedStatus, variables);
+ @Test
+ void testHappyScenarioCRNullProjectCode() {
+ Service service = createServiceObject(false);
+ service.setProjectCode(null);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).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 assertComponentException(ByResponseFormatComponentException e, ActionStatus expectedStatus, String... variables) {
- ResponseFormat actualResponse = e.getResponseFormat();
- assertResponse(actualResponse, expectedStatus, variables);
+ @Test
+ void testHappyScenarioCREmptyStringProjectCode() {
+ createServiceValidator();
+ Service service = createServiceObject(false);
+ service.setProjectCode("");
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).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 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());
+ private void assertEqualsServiceObject(final Service expectedService, final Service actualService) {
+ assertEquals(expectedService.getContactId(), actualService.getContactId());
+ assertEquals(expectedService.getCategories(), actualService.getCategories());
+ assertEquals(expectedService.getCreatorUserId(), actualService.getCreatorUserId());
+ assertEquals(expectedService.getCreatorFullName(), actualService.getCreatorFullName());
+ assertEquals(expectedService.getDescription(), actualService.getDescription());
+ assertEquals(expectedService.getIcon(), actualService.getIcon());
+ assertEquals(expectedService.getLastUpdaterUserId(), actualService.getLastUpdaterUserId());
+ assertEquals(expectedService.getLastUpdaterFullName(), actualService.getLastUpdaterFullName());
+ assertEquals(expectedService.getName(), actualService.getName());
+ assertEquals(expectedService.getUniqueId(), actualService.getUniqueId());
+ assertEquals(expectedService.getVersion(), actualService.getVersion());
+ assertEquals(expectedService.getArtifacts(), actualService.getArtifacts());
+ assertEquals(expectedService.getCreationDate(), actualService.getCreationDate());
+ assertEquals(expectedService.getLastUpdateDate(), actualService.getLastUpdateDate());
+ assertEquals(expectedService.getLifecycleState(), actualService.getLifecycleState());
+ assertEquals(expectedService.getTags(), actualService.getTags());
+ if (expectedService.getProperties() == null) {
+ org.hamcrest.MatcherAssert.assertThat("Service properties should be null",
+ actualService.getProperties(), is(nullValue()));
+ return;
+ }
+ org.hamcrest.MatcherAssert.assertThat("Service properties should be as expected",
+ actualService.getProperties(), is(expectedService.getProperties()));
}
+ /* CREATE validations - start ***********************/
+ // Service name - start
@Test
- public void testFailedServiceValidations() {
+ void testFailedServiceValidations() {
+
testServiceNameAlreadyExists();
testServiceNameEmpty();
testServiceNameWrongFormat();
testServiceIconEmpty();
testServiceIconMissing();
testResourceIconInvalid();
- testResourceIconExceedsLimit();
testTagsNoServiceName();
testInvalidTag();
testServiceTagNotExist();
testResourceContactIdMissing();
testServiceCategoryExist();
testServiceBadCategoryCreate();
- testMissingProjectCode();
}
private void testServiceNameAlreadyExists() {
- String serviceName = "alreadyExist";
+ String serviceName = ALREADY_EXIST;
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);
+ try {
+ bl.createService(serviceExccedsNameLimit, user);
+ } catch (ComponentException exp) {
+ assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
+ return;
+ }
+ fail();
}
private void testServiceNameEmpty() {
Service serviceExccedsNameLimit = createServiceObject(false);
serviceExccedsNameLimit.setName(null);
- try{
+ try {
bl.createService(serviceExccedsNameLimit, user);
- } catch(ByActionStatusComponentException e){
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
private void testServiceNameWrongFormat() {
Service service = createServiceObject(false);
// contains :
- String nameWrongFormat = "ljg\fd";
+ String nameWrongFormat = "ljg\\fd";
service.setName(nameWrongFormat);
- try{
+ try {
bl.createService(service, user);
- } catch(ByActionStatusComponentException e){
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
+ // Service name - end
+ // Service description - start
+
private void testServiceDescriptionEmpty() {
Service serviceExist = createServiceObject(false);
serviceExist.setDescription("");
- try{
+ try {
bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e){
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
private void testServiceDescriptionMissing() {
Service serviceExist = createServiceObject(false);
serviceExist.setDescription(null);
- try{
+ try {
bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e){
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
private void testServiceDescExceedsLimitCreate() {
Service serviceExccedsDescLimit = createServiceObject(false);
// 1025 chars, the limit is 1024
String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ +
+ "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ +
+ "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ +
+ "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
- try{
+ try {
bl.createService(serviceExccedsDescLimit, user);
- } catch(ByActionStatusComponentException e){
- assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(),
+ "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ return;
}
+ fail();
}
private void testServiceDescNotEnglish() {
// Not english
String tooLongServiceDesc = "\uC2B5";
notEnglish.setDescription(tooLongServiceDesc);
- try{
+ try {
bl.createService(notEnglish, user);
- } catch(ByActionStatusComponentException e){
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
// Service description - stop
// Service icon - start
+
private void testServiceIconEmpty() {
Service serviceExist = createServiceObject(false);
serviceExist.setIcon("");
- try{
- bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
- }
+ Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
+ assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
+
}
private void testServiceIconMissing() {
Service serviceExist = createServiceObject(false);
serviceExist.setIcon(null);
- try{
- bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
- }
+ Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
+ assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
}
private void testResourceIconInvalid() {
Service resourceExist = createServiceObject(false);
resourceExist.setIcon("kjk3453^&");
- try{
- bl.createService(resourceExist, user);
- } catch(ByActionStatusComponentException 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(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
- }
+ Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
+ assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
+
}
private void testTagsNoServiceName() {
List<String> tagsList = new ArrayList<>();
tagsList.add(tag1);
serviceExccedsNameLimit.setTags(tagsList);
- try{
+ try {
bl.createService(serviceExccedsNameLimit, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+ return;
}
+ fail();
}
private void testInvalidTag() {
List<String> tagsList = new ArrayList<>();
tagsList.add(tag1);
serviceExccedsNameLimit.setTags(tagsList);
- try{
+ try {
bl.createService(serviceExccedsNameLimit, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
+ return;
}
+ fail();
}
private void testServiceTagNotExist() {
Service serviceExist = createServiceObject(false);
serviceExist.setTags(null);
- try{
- bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
- }
+
+ Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
+ assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
}
private void testServiceTagEmpty() {
Service serviceExist = createServiceObject(false);
serviceExist.setTags(new ArrayList<>());
- try{
- bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
- }
+
+ Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
+ assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
}
// 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{
+ try {
bl.createService(serviceContactId, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
private void testContactIdWrongFormatCreate() {
// 3 letters and 3 digits and special characters
String contactIdTooLong = "yrt134!!!";
serviceContactId.setContactId(contactIdTooLong);
- try{
+ try {
bl.createService(serviceContactId, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
private void testResourceContactIdMissing() {
Service resourceExist = createServiceObject(false);
resourceExist.setContactId(null);
- try{
+ try {
bl.createService(resourceExist, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
// Service contactId - stop
// Service category - start
+
private void testServiceCategoryExist() {
Service serviceExist = createServiceObject(false);
serviceExist.setCategories(null);
- try{
+ try {
bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
@Test
- public void markDistributionAsDeployedTestAlreadyDeployed() {
+ void markDistributionAsDeployedTestAlreadyDeployed() {
String notifyAction = "DNotify";
String requestAction = "DRequest";
String resultAction = "DResult";
resultList.add(event);
Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
- Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
+ Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString()))
+ .thenReturn(eventList);
Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
assertTrue(markDeployed.isLeft());
}
@Test
- public void markDistributionAsDeployedTestSuccess() {
+ 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);
+ roles.add(Role.DESIGNER);
Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
assertTrue(markDeployed.isLeft());
}
@Test
- public void markDistributionAsDeployedTestNotDistributed() {
+ void markDistributionAsDeployedTestNotDistributed() {
String notifyAction = "DNotify";
String requestAction = "DRequest";
String did = "123456";
Service serviceExist = createServiceObject(false);
CategoryDefinition category = new CategoryDefinition();
category.setName("koko");
+ category.setIcons(Arrays.asList(DEFAULT_ICON));
List<CategoryDefinition> categories = new ArrayList<>();
categories.add(category);
serviceExist.setCategories(categories);
- try{
+ try {
bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
+ } catch (ComponentException e) {
assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ return;
}
+ fail();
}
// 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);
+ try {
+ bl.createService(serviceExist, user);
+ } catch (ComponentException exp) {
+ assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
+ return;
+ }
+ fail();
}
private void testProjectCodeTooLong() {
String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
serviceExist.setProjectCode(tooLongProjectCode);
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ try {
+ bl.createService(serviceExist, user);
+ } catch (ComponentException exp) {
+ assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
+ return;
+ }
+ fail();
}
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{
+ try {
bl.createService(serviceExist, user);
- } catch(ByActionStatusComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
+ } catch (ComponentException exp) {
+ assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
+ return;
}
+ fail();
}
@Test
- public void testDeleteMarkedServices() {
+ void testDeleteMarkedServices() {
List<String> ids = new ArrayList<>();
List<String> responseIds = new ArrayList<>();
String resourceInUse = "123";
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;
+ @Test
+ void testDeleteArchivedService_NotFound() {
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ assertThrows(StorageException.class, () -> bl.deleteServiceAllVersions("1", user));
}
- 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);
-
+ @Test
+ void testDeleteArchivedService_NotArchived() {
+ String serviceId = "12345";
+ Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
+ eitherService.left().value().setArchived(false);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+ final ComponentException actualException = assertThrows(ComponentException.class, () -> bl.deleteServiceAllVersions(serviceId, user));
+ assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualException.getActionStatus());
+ assertEquals(actualException.getParams()[0], serviceId);
}
- 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));
+ @Test
+ void testDeleteArchivedService_DeleteServiceSpecificModel() throws ToscaOperationException {
+ String serviceId = "12345";
+ String model = "serviceSpecificModel";
+ List<String> deletedServcies = new ArrayList<>();
+ deletedServcies.add("54321");
+ Model normativeExtensionModel = new Model("normativeExtensionModel", ModelTypeEnum.NORMATIVE_EXTENSION);
+ Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
+ eitherService.left().value().setArchived(true);
+ eitherService.left().value().setModel(model);
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);
+ Mockito.when(toscaOperationFacade.deleteService(Mockito.anyString(), Mockito.eq(true))).thenReturn(deletedServcies);
+ Mockito.when(modelOperation.findModelByName(model)).thenReturn(Optional.of(normativeExtensionModel));
+ bl.deleteServiceAllVersions(serviceId, user);
+ Mockito.verify(modelOperation, Mockito.times(1)).deleteModel(normativeExtensionModel, false);
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings({"unchecked", "rawtypes"})
@Test
- public void testFindGroupInstanceOnRelatedComponentInstance() {
+ void testFindGroupInstanceOnRelatedComponentInstance() {
Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
String methodName = "findGroupInstanceOnRelatedComponentInstance";
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};
+ 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());
+ .getUniqueId());
assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
- .getGroupInstances()
- .get(1)
- .getUniqueId());
+ .getGroupInstances()
+ .get(1)
+ .getUniqueId());
- Object[] argObjectsInvalidCiId = {service, invalidId , 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);
+ 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};
+ Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId(), invalidId};
- findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
+ findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
assertNotNull(findGroupInstanceRes);
assertTrue(findGroupInstanceRes.isRight());
assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
- private Component createNewService() {
+ private Component createNewComponent() {
Service service = new Service();
int listSize = 3;
service.setUniqueId("serviceUniqueId");
List<ComponentInstance> componentInstances = new ArrayList<>();
ComponentInstance ci;
- for(int i= 0; i<listSize; ++i){
+ for (int i = 0; i < listSize; ++i) {
ci = new ComponentInstance();
ci.setName("ciName" + i);
ci.setUniqueId("ciId" + i);
- List<GroupInstance> groupInstances= new ArrayList<>();
+ List<GroupInstance> groupInstances = new ArrayList<>();
GroupInstance gi;
- for(int j = 0; j<listSize; ++j){
+ for (int j = 0; j < listSize; ++j) {
gi = new GroupInstance();
- gi.setName(ci.getName( )+ "giName" + j);
+ gi.setName(ci.getName() + "giName" + j);
gi.setUniqueId(ci.getName() + "giId" + j);
groupInstances.add(gi);
}
return service;
}
+ protected Service createNewService() {
+ return (Service) createNewComponent();
+ }
@Test
- public void testDerivedFromGeneric() {
+ void testDerivedFromGeneric() {
Service service = createServiceObject(true);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ service.setDerivedFromGenericInfo(genericService);
when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).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());
+ assertEquals(genericService.getToscaResourceName(), service.getDerivedFromGenericType());
+ assertEquals(genericService.getVersion(), service.getDerivedFromGenericVersion());
+ }
+
+ @Test
+ void testServiceWithoutDerivedFromGeneric() {
+ final Service service = createServiceObject(true);
+ when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
+ final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+ assertTrue(createResponse.isLeft());
+ final Service actualService = createResponse.left().value();
+ assertNull(actualService.getDerivedFromGenericType());
+ assertNull(actualService.getDerivedFromGenericVersion());
}
@Test
- public void testUpdateMetadataNamingPolicy() {
+ 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);
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
assertThat(resultOfUpdate.isLeft()).isTrue();
Service updatedService = resultOfUpdate.left().value();
assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
}
@Test
- public void testUpdateMetadataServiceType() {
+ void testUpdateMetadataToEmptyProjectCode() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setProjectCode("12345");
+ newService.setProjectCode("");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.getProjectCode()).isEmpty();
+ }
+
+ @Test
+ void testUpdateMetadataFromEmptyProjectCode() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setProjectCode("");
+ newService.setProjectCode("12345");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.getProjectCode()).isEqualTo("12345");
+ }
+
+ @Test
+ void testUpdateMetadataProjectCode() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setProjectCode("33333");
+ newService.setProjectCode("12345");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.getProjectCode()).isEqualTo("12345");
+ }
+
+ @Test
+ 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);
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
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);
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
assertThat(resultOfUpdate.isLeft()).isTrue();
- //null is invalid
+ //null is valid
newService.setServiceType(null);
- resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ }
+
+ @Test
+ void testCreateDefaultMetadataServiceFunction() {
+ Service currentService = createServiceObject(true);
+ assertThat(currentService.getServiceFunction()).isEmpty();
+ }
+
+ @Test
+ void testCreateCustomMetadataServiceFunction() {
+ String customServiceFunctionName = "customName";
+ Service currentService = createServiceObject(true);
+ currentService.setServiceFunction(customServiceFunctionName);
+ assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
+ }
+
+ @Test
+ void testUpdateMetadataServiceFunction() {
+ Service currentService = createServiceObject(true);
+ Service newService = createServiceObject(false);
+ currentService.setServiceFunction("alice");
+ //valid English word
+ newService.setServiceFunction("bob");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
+ //empty string is valid
+ newService.setServiceFunction("");
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ //null is valid and assigner to ""
+ newService.setServiceFunction(null);
+ resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ assertThat(updatedService.getServiceFunction()).isEmpty();
+ }
+
+ @Test
+ void testServiceFunctionExceedLength() {
+ String serviceName = "Service";
+ String serviceFunction =
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ Service serviceFunctionExceedLength = createServiceObject(false);
+ serviceFunctionExceedLength.setName(serviceName);
+ serviceFunctionExceedLength.setServiceFunction(serviceFunction);
+ List<String> tgs = new ArrayList<>();
+ tgs.add(serviceName);
+ serviceFunctionExceedLength.setTags(tgs);
+ try {
+ serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
+ } catch (ComponentException exp) {
+ assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
+ }
+ }
+
+ @Test
+ void testServiceFunctionInvalidCharacter() {
+ String serviceName = "Service";
+ String serviceFunction = "a?";
+ Service serviceFunctionExceedLength = createServiceObject(false);
+ serviceFunctionExceedLength.setName(serviceName);
+ serviceFunctionExceedLength.setServiceFunction(serviceFunction);
+ List<String> tgs = new ArrayList<>();
+ tgs.add(serviceName);
+ serviceFunctionExceedLength.setTags(tgs);
+ try {
+ serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
+ } catch (ComponentException exp) {
+ assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
+ }
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionServiceNotFound() {
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", "2", "3",
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
+ Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", "2", "3",
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionNoMatchingComponent() {
+ Service aService = createNewService();
+ Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
+ Service aService = createNewService();
+ aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
+ Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
+ Service aService = createNewService();
+ aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
+ Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
+ Maps.newHashMap();
+ componentInstancesInterfacesMap.put(aService.getUniqueId(),
+ Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
+
+ aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ @Test
+ void testAddPropertyServiceConsumptionNoInputsCandidate() {
+ Service aService = createNewService();
+ aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
+ Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ String operationId = "operationId";
+ ComponentInstanceInterface componentInstanceInterface =
+ new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
+ Map<String, Operation> operationsMap = Maps.newHashMap();
+ operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
+ new ListDataDefinition<>(), new ListDataDefinition<>()));
+ componentInstanceInterface.setOperationsMap(operationsMap);
+
+ Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
+ componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
+ aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
+
+ Either<Operation, ResponseFormat> operationEither =
+ bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
+ user.getUserId(), new ServiceConsumptionData());
+ assertTrue(operationEither.isRight());
+ assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
+ }
+
+ private Resource mockGenericTypeResource() {
+ final Resource genericTypeResource = new Resource();
+ genericTypeResource.setProperties(mockPropertyList());
+ return genericTypeResource;
+ }
+
+ private List<PropertyDefinition> mockPropertyList() {
+ final List<PropertyDefinition> propertyList = new ArrayList<>();
+ final PropertyDefinition propertyDefinition1 = new PropertyDefinition();
+ propertyDefinition1.setName("property1");
+ propertyDefinition1.setType("string");
+ propertyList.add(propertyDefinition1);
+
+ final PropertyDefinition propertyDefinition2 = new PropertyDefinition();
+ propertyDefinition2.setName("property2");
+ propertyDefinition2.setType("boolean");
+ propertyList.add(propertyDefinition2);
+
+ final PropertyDefinition propertyDefinition3 = new PropertyDefinition();
+ propertyDefinition3.setName("property3");
+ propertyDefinition3.setType("string");
+ propertyList.add(propertyDefinition3);
+ return propertyList;
+ }
+
+ @Test
+ void testCreateService_withMultitenancyValidTenant_Success() {
+ Assert.assertTrue(MULTITENANCY_ENABLED);
+ Service service = createServiceObject(false);
+ service.setTenant(TEST_TENANT);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+
+ if (createResponse.isRight()) {
+ assertEquals(new Integer(200), createResponse.right().value().getStatus());
+ }
+ MatcherAssert.assertThat("Unauthorized Tenant", getTestRoles().contains(service.getTenant()));
+ assertEquals(TEST_TENANT, service.getTenant());
+ assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
+ }
+
+ @Test
+ void testCreateService_withMultitenancyInvalidTenant_Failure() {
+ Service service = createServiceObject(false);
+ service.setTenant("invalid_tenant");
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+ MatcherAssert.assertThat("Unauthorized Tenant", !getTestRoles().contains(service.getTenant()));
+ assertNotEquals(TEST_TENANT, service.getTenant());
+ assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
+ }
+
+ @Test
+ void testUpdateSubstitutionNodeTypeAndVersion() {
+ Service currentService = createServiceObject(true);
+ currentService.setDerivedFromGenericType("genericTypeOne");
+ currentService.setDerivedFromGenericVersion("1.0");
+ Service newService = createServiceObject(false);
+ newService.setDerivedFromGenericType("genericTypeTwo");
+ newService.setDerivedFromGenericVersion("2.0");
+ List<String> subNodePropsToBeRemoved = new ArrayList<>();
+ subNodePropsToBeRemoved.add("testProp");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
+ assertThat(resultOfUpdate.isLeft()).isTrue();
+ Service updatedService = resultOfUpdate.left().value();
+ assertEquals("genericTypeTwo", updatedService.getDerivedFromGenericType());
+ assertEquals("2.0", updatedService.getDerivedFromGenericVersion());
+ }
+
+ @Test
+ void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetProperty() {
+ Service currentService = createServiceObject(true);
+ setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_PROPERTY, "testProp");
+ Service newService = createServiceObject(false);
+ List<String> subNodePropsToBeRemoved = new ArrayList<>();
+ subNodePropsToBeRemoved.add("testProp");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
+ assertThat(resultOfUpdate.isRight()).isTrue();
+ ResponseFormat response = resultOfUpdate.right().value();
+ assertEquals(409, response.getStatus());
+ assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
+ }
+
+ @Test
+ void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetAttribute() {
+ Service currentService = createServiceObject(true);
+ setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_ATTRIBUTE, "testProp");
+ Service newService = createServiceObject(false);
+ List<String> subNodePropsToBeRemoved = new ArrayList<>();
+ subNodePropsToBeRemoved.add("testProp");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
+ assertThat(resultOfUpdate.isRight()).isTrue();
+ ResponseFormat response = resultOfUpdate.right().value();
+ assertEquals(409, response.getStatus());
+ assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
+ }
+
+ @Test
+ void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetInput() {
+ Service currentService = createServiceObject(true);
+ setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_INPUT, "testProp");
+ Service newService = createServiceObject(false);
+ List<String> subNodePropsToBeRemoved = new ArrayList<>();
+ subNodePropsToBeRemoved.add("testProp");
+ Either<Service, ResponseFormat> resultOfUpdate =
+ bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
assertThat(resultOfUpdate.isRight()).isTrue();
+ ResponseFormat response = resultOfUpdate.right().value();
+ assertEquals(409, response.getStatus());
+ assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
+ }
+
+ private void setComponentInstanceOnServiceWithPropWithToscaFunction(Service currentService, ToscaGetFunctionType toscaGetFunctionType,
+ String testPropName) {
+ ComponentInstance compInstance = new ComponentInstance();
+ compInstance.setUniqueId("resourceUid");
+
+ List<ComponentInstance> compInstances = new ArrayList<>();
+ compInstances.add(compInstance);
+ currentService.setComponentInstances(compInstances);
+
+ ToscaGetFunctionDataDefinition toscaFunc = new ToscaGetFunctionDataDefinition();
+ toscaFunc.setPropertyName(testPropName);
+ toscaFunc.setPropertyUniqueId(testPropName + "Uid");
+ toscaFunc.setFunctionType(toscaGetFunctionType);
+
+ if (ToscaGetFunctionType.GET_INPUT.equals(toscaGetFunctionType)) {
+ toscaFunc.setPropertyName(testPropName + "Input");
+ toscaFunc.setPropertyUniqueId(testPropName + "InputUid");
+ InputDefinition compInput = new InputDefinition();
+ compInput.setName(testPropName + "Input");
+ compInput.setUniqueId(testPropName + "InputUid");
+ compInput.setPropertyId(testPropName + "Uid");
+ List<InputDefinition> compInputs = new ArrayList<>();
+ compInputs.add(compInput);
+ currentService.setInputs(compInputs);
+ }
+
+ ComponentInstanceProperty compInstProp = new ComponentInstanceProperty();
+ compInstProp.setName("compInstProp");
+ compInstProp.setToscaFunction(toscaFunc);
+
+ List<ComponentInstanceProperty> compInstProps = new ArrayList<>();
+ compInstProps.add(compInstProp);
+
+ Map<String, List<ComponentInstanceProperty>> mapCompInstProps = new HashMap<>();
+ mapCompInstProps.put("resourceUid", compInstProps);
+
+ PropertyDefinition compProp = new PropertyDefinition();
+ compProp.setName(testPropName);
+ compProp.setUniqueId(testPropName + "Uid");
+ List<PropertyDefinition> compProps = new ArrayList<>();
+ compProps.add(compProp);
+ currentService.setProperties(compProps);
+
+ currentService.setComponentInstancesProperties(mapCompInstProps);
}
- private Resource setupGenericServiceMock(){
- Resource genericService = new Resource();
- genericService.setVersion("1.0");
- genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
- return genericService;
+ private Set<String> getTestRoles() {
+ Set<String> roles = new HashSet<>();
+ roles.add("test_admin");
+ roles.add("test_tenant");
+ return roles;
}
}