re base code
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / ServiceBusinessLogicTest.java
  * ============LICENSE_END=========================================================
  */
 
-package org.openecomp.sdc.be.components;
+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.Ignore;
 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.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+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;
@@ -41,13 +38,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
 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;
@@ -62,63 +53,58 @@ import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
 import org.openecomp.sdc.common.api.ConfigurationSource;
 import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
 import org.openecomp.sdc.common.impl.ExternalConfiguration;
 import org.openecomp.sdc.common.impl.FSConfigurationSource;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.web.context.WebApplicationContext;
 
 import javax.servlet.ServletContext;
 import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+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 Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class);
     private static final String SERVICE_CATEGORY = "Mobility";
-    final ServletContext servletContext = Mockito.mock(ServletContext.class);
-    UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
-    WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
-    WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
-    ServiceBusinessLogic bl = new ServiceBusinessLogic();
-    ResponseFormatManager responseManager = null;
-    IElementOperation mockElementDao;
-    ComponentsUtils componentsUtils;
-    AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
-    ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
-    GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
-    TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
-    ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
-    CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
-    GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
-    UserValidations userValidations = Mockito.mock(UserValidations.class);
-
-    User user = null;
-    Service serviceResponse = null;
-    Resource genericService = null;
+    private static final String 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";
-    private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>();
-    private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>();
-    private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>();
 
     public ServiceBusinessLogicTest() {
 
@@ -135,7 +121,7 @@ public class ServiceBusinessLogicTest {
         componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
 
         // Elements
-        mockElementDao = new ElementOperationMock();
+        IElementOperation mockElementDao = new ElementOperationMock();
 
         // User data and management
         user = new User();
@@ -146,8 +132,8 @@ public class ServiceBusinessLogicTest {
 
         Either<User, ActionStatus> eitherGetUser = Either.left(user);
         when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
-        when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user));
-        when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user));
+        when(userValidations.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);
@@ -160,7 +146,7 @@ public class ServiceBusinessLogicTest {
         when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
 
         // createService
-        serviceResponse = createServiceObject(true);
+        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);
@@ -196,16 +182,14 @@ public class ServiceBusinessLogicTest {
     public void testGetComponentAuditRecordsCertifiedVersion() {
         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
         assertTrue(componentAuditRecords.isLeft());
-        int size = componentAuditRecords.left().value().size();
-        assertTrue(size == 3);
+        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());
-        int size = componentAuditRecords.left().value().size();
-        assertTrue(size == 1);
+        assertEquals(4, componentAuditRecords.left().value().size());
     }
 
     @Test
@@ -223,7 +207,6 @@ public class ServiceBusinessLogicTest {
 
     private void validateUserRoles(Role ... roles) {
         List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
-        when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
     }
 
     private void assertEqualsServiceObject(Service origService, Service newService) {
@@ -247,8 +230,17 @@ public class ServiceBusinessLogicTest {
     }
 
     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);
-        ResponseFormat actualResponse = createResponse.right().value();
         assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
         assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
     }
@@ -289,7 +281,7 @@ public class ServiceBusinessLogicTest {
         Service serviceExccedsNameLimit = createServiceObject(false);
         // 51 chars, the limit is 50
         serviceExccedsNameLimit.setName(serviceName);
-        List<String> tgs = new ArrayList<String>();
+        List<String> tgs = new ArrayList<>();
         tgs.add(serviceName);
         serviceExccedsNameLimit.setTags(tgs);
         validateUserRoles(Role.ADMIN, Role.DESIGNER);
@@ -301,10 +293,11 @@ public class ServiceBusinessLogicTest {
     private void testServiceNameEmpty() {
         Service serviceExccedsNameLimit = createServiceObject(false);
         serviceExccedsNameLimit.setName(null);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(serviceExccedsNameLimit, user);
+        } catch(ComponentException e){
+            assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     private void testServiceNameWrongFormat() {
@@ -312,30 +305,31 @@ public class ServiceBusinessLogicTest {
         // contains :
         String nameWrongFormat = "ljg\fd";
         service.setName(nameWrongFormat);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+        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("");
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+        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);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(serviceExist, user);
+        } catch(ComponentException e){
+            assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     private void testServiceDescExceedsLimitCreate() {
@@ -351,10 +345,11 @@ public class ServiceBusinessLogicTest {
                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
 
         serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+        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() {
@@ -362,10 +357,11 @@ public class ServiceBusinessLogicTest {
         // Not english
         String tooLongServiceDesc = "\uC2B5";
         notEnglish.setDescription(tooLongServiceDesc);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(notEnglish, user);
+        } catch(ComponentException e){
+            assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     // Service description - stop
@@ -373,87 +369,87 @@ public class ServiceBusinessLogicTest {
     private void testServiceIconEmpty() {
         Service serviceExist = createServiceObject(false);
         serviceExist.setIcon("");
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+        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);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+        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^&");
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
+        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");
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
+        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<String>();
+        List<String> tagsList = new ArrayList<>();
         tagsList.add(tag1);
         serviceExccedsNameLimit.setTags(tagsList);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
-
+        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<String>();
+        List<String> tagsList = new ArrayList<>();
         tagsList.add(tag1);
         serviceExccedsNameLimit.setTags(tagsList);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
-
+        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);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+        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<String>());
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+        serviceExist.setTags(new ArrayList<>());
+        try{
+            bl.createService(serviceExist, user);
+        } catch(ComponentException e) {
+            assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
+        }
     }
 
     // Service tags - stop
@@ -463,10 +459,11 @@ public class ServiceBusinessLogicTest {
         // 59 chars instead of 50
         String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
         serviceContactId.setContactId(contactIdTooLong);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(serviceContactId, user);
+        } catch(ComponentException e) {
+            assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     private void testContactIdWrongFormatCreate() {
@@ -474,19 +471,21 @@ public class ServiceBusinessLogicTest {
         // 3 letters and 3 digits and special characters
         String contactIdTooLong = "yrt134!!!";
         serviceContactId.setContactId(contactIdTooLong);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+        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);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
-        assertTrue(createResponse.isRight());
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(resourceExist, user);
+        } catch(ComponentException e) {
+            assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     // Service contactId - stop
@@ -494,11 +493,40 @@ public class ServiceBusinessLogicTest {
     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());
+        }
+    }
 
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
+    @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);
 
-        assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
     }
 
     @Test
@@ -511,11 +539,29 @@ public class ServiceBusinessLogicTest {
         List<Role> roles = new ArrayList<>();
         roles.add(Role.ADMIN);
         roles.add(Role.OPS);
-        when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true));
         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
         assertTrue(markDeployed.isLeft());
     }
 
+    @Test
+    public void markDistributionAsDeployedTestNotDistributed() {
+        String notifyAction = "DNotify";
+        String requestAction = "DRequest";
+        String did = "123456";
+
+        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() {
 
@@ -525,11 +571,11 @@ public class ServiceBusinessLogicTest {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         serviceExist.setCategories(categories);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+        try{
+            bl.createService(serviceExist, user);
+        } catch(ComponentException e) {
+            assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+        }
     }
 
     // Service category - stop
@@ -572,36 +618,34 @@ public class ServiceBusinessLogicTest {
 
         Service serviceExist = createServiceObject(false);
         serviceExist.setProjectCode(null);
-
-        Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
-        assertTrue(createResponse.isRight());
-
-        assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
+        try{
+            bl.createService(serviceExist, user);
+        } catch(ComponentException e) {
+            assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
+        }
     }
 
     @Test
-    @Ignore
     public void testDeleteMarkedServices() {
-        List<String> ids = new ArrayList<String>();
+        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<ArtifactDefinition>();
+        List<ArtifactDefinition> artifacts = new ArrayList<>();
         Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
 
-        when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
-        when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
-
         Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
         when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
-
+        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();
@@ -620,9 +664,10 @@ public class ServiceBusinessLogicTest {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         service.setCategories(categories);
+        service.setInstantiationType(INSTANTIATION_TYPE);
 
         service.setDescription("description");
-        List<String> tgs = new ArrayList<String>();
+        List<String> tgs = new ArrayList<>();
         tgs.add(service.getName());
         service.setTags(tgs);
         service.setIcon("MyIcon");
@@ -639,13 +684,6 @@ public class ServiceBusinessLogicTest {
     }
 
     private void mockAuditingDaoLogic() {
-        FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
-        FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
-        FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
-
-        FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
-        FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
-
         final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
         createResourceAudit.setModifier("Carlos Santana(cs0008)");
         createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
@@ -703,7 +741,7 @@ public class ServiceBusinessLogicTest {
         Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
         Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
 
-        List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
+        List<ResourceAdminEvent> listPrev = new ArrayList<>();
         Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
         Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
 
@@ -715,6 +753,12 @@ public class ServiceBusinessLogicTest {
         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) {
@@ -729,28 +773,24 @@ public class ServiceBusinessLogicTest {
         requestEvent.setDid(did);
         requestEvent.setStatus("200");
 
-        ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
-        List<DistributionNotificationEvent> notifyResults = arrayList;
-        notifyResults.add(notifyEvent);
+        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 = new ArrayList<ResourceAdminEvent>();
-        requestResults.add(requestEvent);
+        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);
 
-        List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
-        Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
+        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 @Ignore
+    @Test
     public void testFindGroupInstanceOnRelatedComponentInstance() {
 
         Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
@@ -768,23 +808,27 @@ public class ServiceBusinessLogicTest {
             method.setAccessible(true);
 
             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
-            assertTrue(findGroupInstanceRes != null);
-            assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
-            assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
+            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);
-            assertTrue(findGroupInstanceRes != null);
+            assertNotNull(findGroupInstanceRes);
             assertTrue(findGroupInstanceRes.isRight());
-            assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
+            assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
 
             Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
 
             findGroupInstanceRes =    (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
-            assertTrue(findGroupInstanceRes != null);
+            assertNotNull(findGroupInstanceRes);
             assertTrue(findGroupInstanceRes.isRight());
-            assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
+            assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
         }
         catch (Exception e) {
             e.printStackTrace();
@@ -828,10 +872,44 @@ public class ServiceBusinessLogicTest {
         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
         assertTrue(createResponse.isLeft());
         service = createResponse.left().value();
-        assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
-        assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
+        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();