Added JUnit Test for coverage 78/87478/1
authorbilal.iqbal <bilal.iqbal@est.tech>
Fri, 10 May 2019 17:45:07 +0000 (17:45 +0000)
committerbilal.iqbal <bilal.iqbal@est.tech>
Fri, 10 May 2019 17:45:07 +0000 (17:45 +0000)
Change-Id: I7bbd5fca6847f30f64cba6d9beb521c3ba61d1cb
Issue-ID: SDC-2279
Signed-off-by: bilal.iqbal <bilal.iqbal@est.tech>
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogicTest.java [new file with mode: 0644]
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java [new file with mode: 0644]

diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogicTest.java
new file mode 100644 (file)
index 0000000..9b84989
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * -
+ *  * ============LICENSE_START=======================================================
+ *  *  Copyright (C) 2019  Nordix Foundation.
+ *  * ================================================================================
+ *  * 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.
+ *  *
+ *  * SPDX-License-Identifier: Apache-2.0
+ *  * ============LICENSE_END=========================================================
+ *
+ */
+
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.info.DistributionStatusListResponse;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
+import org.openecomp.sdc.exception.ResponseFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+public class DistributionMonitoringBusinessLogicTest {
+
+    private String uId;
+    private User user;
+    private String ditributionId;
+    private String serviceId;
+
+    @InjectMocks
+    private DistributionMonitoringBusinessLogic businessLogic;
+
+    @Mock
+    private AuditCassandraDao cassandraDao;
+
+    @Mock
+    private UserValidations userValidations;
+
+    @Mock
+    private ComponentsUtils componentsUtils;
+
+    @Before
+    public void setUp() {
+        businessLogic = new DistributionMonitoringBusinessLogic();
+        MockitoAnnotations.initMocks(this);
+
+        user = new User();
+        uId = "userId";
+        ditributionId = "did";
+        serviceId = "serviceId";
+
+        when(userValidations.validateUserExists(Mockito.eq(uId), eq(ditributionId), anyBoolean()))
+                .thenReturn(user);
+    }
+
+    @Test
+    public void testGetListOfDistribution_givenInvalidDistributionId_thenReturnsError() {
+        when(cassandraDao.getListOfDistributionStatuses(ditributionId))
+                .thenReturn(Either.right(ActionStatus.DISTRIBUTION_NOT_FOUND));
+
+        assertTrue(businessLogic.getListOfDistributionStatus(ditributionId, uId).isRight());
+    }
+
+    @Test
+    public void testGetListOfDistribution_givenValidDistributionId_thenReturnsSuccessful() {
+
+        List<DistributionStatusEvent> distributionEvents = new ArrayList<>();
+        DistributionStatusEvent event = new DistributionStatusEvent();
+        distributionEvents.add(event);
+
+        when(cassandraDao.getListOfDistributionStatuses(ditributionId))
+                .thenReturn(Either.left(distributionEvents));
+
+        Either<DistributionStatusListResponse, ResponseFormat> result = businessLogic.getListOfDistributionStatus(ditributionId, uId);
+
+        assertTrue(result.isLeft());
+        assertEquals(1, result.left().value().getDistributionStatusList().size());
+    }
+
+    @Test
+    public void testGetDistributionServiceStatus_givenInvalidServiceIdId_thenReturnsError() {
+
+        when(cassandraDao.getServiceDistributionStatusesList(serviceId))
+                .thenReturn(Either.right(ActionStatus.DISTRIBUTION_NOT_FOUND));
+        assertTrue(businessLogic.getListOfDistributionServiceStatus(serviceId, uId).isRight());
+    }
+
+    @Test
+    public void testGetDistributionServiceStatus_givenValidServiceId_thenReturnsSuccessful() {
+
+        List<AuditingGenericEvent> serviceEvents = new ArrayList<>();
+        AuditingGenericEvent event1 = new AuditingGenericEvent();
+        AuditingGenericEvent event2 = new AuditingGenericEvent();
+
+        Map<String, Object> event1Fields = new HashMap<>();
+        Map<String, Object> event2Fields = new HashMap<>();
+
+        event1Fields.put("DID", "event1");
+        event1Fields.put("ACTION", "DRequest");
+        event1Fields.put("STATUS", "200");
+        event1Fields.put("MODIFIER", uId);
+
+        event2Fields.put("DID", "event2");
+        event2Fields.put("ACTION", "DNotify");
+        event2Fields.put("STATUS", "200");
+        event2Fields.put("MODIFIER", uId);
+
+        event1.setFields(event1Fields);
+        event2.setFields(event2Fields);
+
+        serviceEvents.add(event1);
+        serviceEvents.add(event2);
+
+        when(cassandraDao.getServiceDistributionStatusesList(serviceId))
+                .thenReturn(Either.left(serviceEvents));
+
+        assertTrue(businessLogic.getListOfDistributionServiceStatus(serviceId, uId).isLeft());
+    }
+}
\ No newline at end of file
index cb6f889..36f7084 100644 (file)
 package org.openecomp.sdc.be.components.impl;
 
+import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-
-import com.att.aft.dme2.internal.apache.commons.lang.ObjectUtils;
+import java.util.Set;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
 import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.validation.UserValidations;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactType;
 import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.PropertyScope;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.ui.model.UiCategories;
+import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.exception.ResponseFormat;
-
 import fj.data.Either;
 
-import javax.validation.constraints.Null;
-
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anySet;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class ElementBusinessLogicTest {
 
-       private ElementBusinessLogic createTestSubject() {
-               return new ElementBusinessLogic();
-       }
+       private User user;
+
+       @Mock
+       private ComponentsUtils componentsUtils;
+
+       @Mock
+       private UserBusinessLogic userAdminManager;
 
     @Mock
-    ComponentsUtils componentsUtils;
+       private TitanDao titanDao;
 
     @Mock
-    UserBusinessLogic userAdminManager;
+       private UserValidations userValidations;
+
+    @Mock
+       private ToscaOperationFacade toscaOperationFacade;
+
+    @Mock
+       private IElementOperation elementOperation;
 
     @InjectMocks
     ElementBusinessLogic elementBusinessLogic;
-       
-       @Test
-       public void testGetFollowed() throws Exception {
-               ElementBusinessLogic testSubject;
-               User user = null;
-               Either<Map<String, List<? extends Component>>, ResponseFormat> result;
 
-               // default test
-               testSubject = createTestSubject();
+    @Before
+       public void setUp() {
+
+       elementBusinessLogic = new ElementBusinessLogic();
+       MockitoAnnotations.initMocks(this);
+               user = new User();
+               user.setUserId("admin");
        }
 
-       
-       
-       
-       @Test
-       public void testGetAllResourceCategories() throws Exception {
-               ElementBusinessLogic testSubject;
-               Either<List<CategoryDefinition>, ActionStatus> result;
+    @Test
+       public void testGetFollowed_givenUserWithDesignerRole_thenReturnsSuccessful() {
+       user.setUserId("designer1");
+       user.setRole(Role.DESIGNER.name());
 
-               // default test
-               testSubject = createTestSubject();
-       }
+       Set<Component> resources = new HashSet<>();
+       Set<Component> services = new HashSet<>();
 
-       
-       @Test
-       public void testGetAllServiceCategories() throws Exception {
-               ElementBusinessLogic testSubject;
-               Either<List<CategoryDefinition>, ActionStatus> result;
+       Resource resource = new Resource();
+       Service service = new Service();
 
-               // default test
-               testSubject = createTestSubject();
-       }
+       resources.add(resource);
+       services.add(service);
 
-       
-       @Test
-       public void testCreateCategory() throws Exception {
-               ElementBusinessLogic testSubject;
-               CategoryDefinition category = null;
-               String componentTypeParamName = "";
-               String userId = "";
-               Either<CategoryDefinition, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               category = null;
-       }
+       Mockito.when(toscaOperationFacade.getFollowed(eq(user.getUserId()), Mockito.anySet(), Mockito.anySet(), Mockito.eq(ComponentTypeEnum.RESOURCE)))
+                               .thenReturn(Either.left(resources));
+       Mockito.when(toscaOperationFacade.getFollowed(eq(user.getUserId()), anySet(), anySet(), eq(ComponentTypeEnum.SERVICE)))
+                               .thenReturn(Either.left(services));
 
-       
-       @Test
-       public void testCreateSubCategory() throws Exception {
-               ElementBusinessLogic testSubject;
-               SubCategoryDefinition subCategory = null;
-               String componentTypeParamName = "";
-               String parentCategoryId = "";
-               String userId = "";
-               Either<SubCategoryDefinition, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               subCategory = null;
+       Map<String, List<? extends Component>> result = elementBusinessLogic.getFollowed(user).left().value();
+       Assert.assertTrue(result.get("services").size() == 1);
+       Assert.assertTrue(result.get("resources").size() == 1);
        }
 
-       
        @Test
-       public void testCreateGrouping() throws Exception {
-               ElementBusinessLogic testSubject;
-               GroupingDefinition grouping = null;
-               String componentTypeParamName = "";
-               String grandParentCategoryId = "";
-               String parentSubCategoryId = "";
-               String userId = "";
-               Either<GroupingDefinition, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               grouping = null;
-       }
+       public void testGetFollowed_givenUserWithTesterRoleErrorOccursGettingService_thenReturnsError () {
+               user.setUserId("tester1");
+               user.setRole(Role.TESTER.name());
 
-       
-       @Test
-       public void testGetAllCategories() throws Exception {
-               ElementBusinessLogic testSubject;
-               String componentType = "";
-               String userId = "";
-               Either<List<CategoryDefinition>, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               userId = null;
-
-               // test 2
-               testSubject = createTestSubject();
-               userId = "";
-       }
+               Set<Component> resources = new HashSet<>();
 
-       
-       @Test
-       public void testGetAllCategories_1() throws Exception {
-               ElementBusinessLogic testSubject;
-               String userId = "";
-               Either<UiCategories, ResponseFormat> result;
+               Resource resource = new Resource();
+               resources.add(resource);
 
-               // default test
-               testSubject = createTestSubject();
+               Mockito.when(toscaOperationFacade.getFollowed(any(), Mockito.anySet(), any(), Mockito.eq(ComponentTypeEnum.RESOURCE)))
+                               .thenReturn(Either.left(resources));
+               Mockito.when(toscaOperationFacade.getFollowed(any(), anySet(), any(), eq(ComponentTypeEnum.SERVICE)))
+                               .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+               Assert.assertTrue(elementBusinessLogic.getFollowed(user).isRight());
        }
 
-       
        @Test
-       public void testDeleteCategory() throws Exception {
-               ElementBusinessLogic testSubject;
-               String categoryId = "";
-               String componentTypeParamName = "";
-               String userId = "";
-               Either<CategoryDefinition, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-       }
+       public void testGetFollowed_givenUserWithGovernorRole_thenReturnsSuccessful(){
+               user.setUserId("governor1");
+       user.setRole(Role.GOVERNOR.name());
 
-       
-       @Test
-       public void testDeleteSubCategory() throws Exception {
-               ElementBusinessLogic testSubject;
-               String grandParentCategoryId = "";
-               String parentSubCategoryId = "";
-               String componentTypeParamName = "";
-               String userId = "";
-               Either<SubCategoryDefinition, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
+       List<Service> services = new ArrayList<>();
+       services.add(new Service());
+
+       when(toscaOperationFacade.getCertifiedServicesWithDistStatus(any()))
+                               .thenReturn(Either.left(services));
+               Assert.assertTrue(elementBusinessLogic.getFollowed(user).isLeft());
        }
 
-       
        @Test
-       public void testDeleteGrouping() throws Exception {
-               ElementBusinessLogic testSubject;
-               String grandParentCategoryId = "";
-               String parentSubCategoryId = "";
-               String groupingId = "";
-               String componentTypeParamName = "";
-               String userId = "";
-               Either<GroupingDefinition, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-       }
+       public void testGetFollowed_givenUserWithOPSRoleErrorOccursGettingServices_thenReturnsError(){
+               user.setUserId("ops1");
+       user.setRole(Role.OPS.name());
 
-       
+               when(toscaOperationFacade.getCertifiedServicesWithDistStatus(any()))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
 
-       
-       @Test
-       public void testGetAllPropertyScopes() throws Exception {
-               ElementBusinessLogic testSubject;
-               String userId = "";
-               Either<List<PropertyScope>, ActionStatus> result;
+               Assert.assertTrue(elementBusinessLogic.getFollowed(user).isRight());
 
-               // default test
-               testSubject = createTestSubject();
        }
 
-       
        @Test
-       public void testGetAllArtifactTypes() throws Exception {
-               ElementBusinessLogic testSubject;
-               String userId = "";
-               Either<List<ArtifactType>, ActionStatus> result;
+       public void testGetFollowed_givenUserWithProductStrategistRole_thenReturnsEmptyList(){
+               user.setUserId("pstra1");
+       user.setRole(Role.PRODUCT_STRATEGIST.name());
+
+       Map<String, List<? extends Component>> result = elementBusinessLogic.getFollowed(user).left().value();
+       Assert.assertEquals("products list should be empty", 0, result.get("products").size());
 
-               // default test
-               testSubject = createTestSubject();
        }
 
-       
        @Test
-       public void testGetAllDeploymentArtifactTypes() throws Exception {
-               ElementBusinessLogic testSubject;
-               Either<Map<String, Object>, ActionStatus> result;
+       public void testGetFollowed_givenUserWithProductManagerRole_thenReturnsProducts(){
+       user.setUserId("pmanager1");
+       user.setRole(Role.PRODUCT_MANAGER.name());
+
+       Set<Component> products = new HashSet<>();
+       products.add(new Product());
+
+       when(toscaOperationFacade.getFollowed(any(), anySet(), any(), eq(ComponentTypeEnum.PRODUCT)))
+                               .thenReturn(Either.left(products));
+
+       Map<String, List<? extends Component>> result = elementBusinessLogic.getFollowed(user).left().value();
+       Assert.assertEquals("1 product should exist", 1, result.get("products").size());
 
-               // default test
-               testSubject = createTestSubject();
        }
 
-       
        @Test
-       public void testGetDefaultHeatTimeout() throws Exception {
-               ElementBusinessLogic testSubject;
-               Either<Integer, ActionStatus> result;
+       public void testGetFollowed_givenUserWithRoleAdminErrorOccursGettingResources_thenReturnsError() {
+       user.setUserId("admin1");
+       user.setRole(Role.ADMIN.name());
+
+       when(toscaOperationFacade.getFollowed(any(), anySet(), any(), eq(ComponentTypeEnum.RESOURCE)))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
 
-               // default test
-               testSubject = createTestSubject();
+       Assert.assertTrue(elementBusinessLogic.getFollowed(user).isRight());
        }
 
-       
        @Test
-       public void testGetCatalogComponents() throws Exception {
-               ElementBusinessLogic testSubject;
-               String userId = "";
-               List<OriginTypeEnum> excludeTypes = null;
-               Either<Map<String, List<? extends Component>>, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
+       public void testGetAllCategories_givenUserIsNull_thenReturnsError() {
+       Assert.assertTrue(elementBusinessLogic.getAllCategories(null, null).isRight());
        }
 
-       
-       @Test
-       public void testGetFilteredCatalogComponents() throws Exception {
-               ElementBusinessLogic testSubject;
-               String assetType = "";
-               Map<FilterKeyEnum, String> filters = null;
-               String query = "";
-               Either<List<? extends Component>, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               query = null;
-
-               // test 2
-               testSubject = createTestSubject();
-               query = "";
-
-               // test 3
-               testSubject = createTestSubject();
-               filters = null;
+       @Test(expected = ComponentException.class)
+       public void testGetAllCategories_givenValidationOfUserFails_thenReturnsError() {
+       doThrow(new ComponentException(new ResponseFormat())).when(userValidations).validateUserExists(eq(user.getUserId()),
+                               anyString(), anyBoolean());
+               elementBusinessLogic.getAllCategories(null, user.getUserId());
        }
 
-       
-       
-       
        @Test
-       public void testGetCatalogComponentsByUuidAndAssetType() throws Exception {
-               ElementBusinessLogic testSubject;
-               String assetType = "";
-               String uuid = "";
-               Either<List<? extends Component>, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               assetType = null;
-
-               // test 2
-               testSubject = createTestSubject();
-               assetType = "";
-
-               // test 3
-               testSubject = createTestSubject();
-               assetType = null;
-
-               // test 4
-               testSubject = createTestSubject();
-               assetType = "";
+       public void testGetAllCategories_givenInvalidComponentType_thenReturnsError() {
+       when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), anyBoolean())).thenReturn(user);
+
+       Assert.assertTrue(elementBusinessLogic.getAllCategories("NONE", user.getUserId()).isRight());
+
        }
 
-       
        @Test
-       public void testGetAllComponentTypesParamNames() throws Exception {
-               ElementBusinessLogic testSubject;
-               List<String> result;
+       public void testGetAllCategories_givenValidUserAndComponentType_thenReturnsSuccessful() {
 
-               // default test
-               testSubject = createTestSubject();
-               result = testSubject.getAllComponentTypesParamNames();
+       List<CategoryDefinition> categoryDefinitionList = new ArrayList<>();
+       categoryDefinitionList.add(new CategoryDefinition());
+
+               when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), anyBoolean())).thenReturn(user);
+               when(elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false))
+                               .thenReturn(Either.left(categoryDefinitionList));
+               Assert.assertTrue(elementBusinessLogic.getAllCategories(ComponentTypeEnum.RESOURCE_PARAM_NAME, user.getUserId())
+               .isLeft());
        }
 
-       
        @Test
-       public void testGetAllSupportedRoles() throws Exception {
-               ElementBusinessLogic testSubject;
-               List<String> result;
+       public void testGetAllCategories_givenValidUserId_thenReturnsSuccessful() {
+
+       List<CategoryDefinition> dummyCategoryDefinitionList = new ArrayList<>();
+       dummyCategoryDefinitionList.add(new CategoryDefinition());
+
+       when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), anyBoolean()))
+                               .thenReturn(user);
+       when(elementOperation.getAllCategories(any(NodeTypeEnum.class), anyBoolean()))
+                               .thenReturn(Either.left(dummyCategoryDefinitionList));
 
-               // default test
-               testSubject = createTestSubject();
-               result = testSubject.getAllSupportedRoles();
+       Assert.assertTrue(elementBusinessLogic.getAllCategories(user.getUserId()).isLeft());
        }
 
-       
        @Test
-       public void testGetResourceTypesMap() throws Exception {
-               ElementBusinessLogic testSubject;
-               Either<Map<String, String>, ActionStatus> result;
+       public void testDeleteCategory_givenValidComponentTypeAndCategoryId_thenReturnsSuccessful() {
 
-               // default test
-               testSubject = createTestSubject();
+       when(elementOperation.deleteCategory(any(NodeTypeEnum.class), anyString()))
+                               .thenReturn(Either.left(new CategoryDefinition()));
+
+       Assert.assertTrue(elementBusinessLogic.deleteCategory("cat1", "resources", user.getUserId()).isLeft());
        }
 
-       
-       
+       @Test
+       public void testCreateSubCategory_givenValidSubCategory_thenReturnsSuccessful() {
+       user.setRole(Role.ADMIN.name());
+               SubCategoryDefinition subCatDef = new SubCategoryDefinition();
+               subCatDef.setName("subCat1");
+
+               when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(elementOperation.getCategory(any(NodeTypeEnum.class), anyString()))
+                               .thenReturn(Either.left(new CategoryDefinition()));
+               when(elementOperation.isSubCategoryUniqueForCategory(any(NodeTypeEnum.class), anyString(), anyString()))
+                               .thenReturn(Either.left(Boolean.TRUE));
+               when(elementOperation.getSubCategoryUniqueForType(any(NodeTypeEnum.class), anyString()))
+                               .thenReturn(Either.left(subCatDef));
+               when(elementOperation.createSubCategory(anyString(), any(SubCategoryDefinition.class), any(NodeTypeEnum.class)))
+                               .thenReturn(Either.left(subCatDef));
+
+               Assert.assertTrue(elementBusinessLogic.createSubCategory(subCatDef, "resources",
+                               "cat1", user.getUserId()).isLeft());
+       }
 
-       
        @Test
-       public void testGetFilteredResouces() throws Exception {
-               ElementBusinessLogic testSubject;
-               Map<FilterKeyEnum, String> filters = null;
-               boolean inTransaction = false;
-               Either<List<Component>, StorageOperationStatus> result;
-
-               // default test
-               testSubject = createTestSubject();
+       public void testCreateSubCategory_givenNullSubCategory_thenReturnsError() {
+       Assert.assertTrue(elementBusinessLogic.createSubCategory(null, "resources",
+                               "cat1", user.getUserId()).isRight());
        }
 
+       @Test(expected = ComponentException.class)
+       public void testCreateSubCategory_givenUserValidationFails_thenReturnsException() {
+       SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition();
+       doThrow(new ComponentException(new ResponseFormat())).when(userValidations).validateUserExists(eq(user.getUserId()),
+                               anyString(), anyBoolean());
+       elementBusinessLogic.createSubCategory(subCategoryDefinition, "resources", "cat1", user.getUserId());
+       }
 
        @Test
     public void testcreateCategory_VALIDATION_OF_USER_FAILED() throws Exception {
@@ -417,5 +341,4 @@ public class ElementBusinessLogicTest {
         Assert.assertEquals(true,response.isRight());
         Assert.assertEquals((Integer) 9, response.right().value().getStatus());
     }
-
 }
\ No newline at end of file
index cbb5f7b..faaddd7 100644 (file)
 package org.openecomp.sdc.be.components.impl;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-
-import org.apache.commons.math3.stat.descriptive.summary.Product;
+import org.junit.Before;
 import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.components.validation.ValidationUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ComponentMetadataDefinition;
+import org.openecomp.sdc.be.model.Product;
 import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.exception.ResponseFormat;
-
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import fj.data.Either;
+import org.openecomp.sdc.exception.ResponseFormat;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
 
 public class ProductBusinessLogicTest {
 
-       private ProductBusinessLogic createTestSubject() {
-               return new ProductBusinessLogic();
-       }
-
-       @Test
-       public void testValidateProductNameExists() throws Exception {
-               ProductBusinessLogic testSubject;
-               String productName = "";
-               String userId = "";
-               Either<Map<String, Boolean>, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-       }
-
-       @Test
-       public void testSetDeploymentArtifactsPlaceHolder() throws Exception {
-               ProductBusinessLogic testSubject;
-               Component component = null;
-               User user = null;
-
-               // default test
-               testSubject = createTestSubject();
-               testSubject.setDeploymentArtifactsPlaceHolder(component, user);
+       private Product product;
+       private User user;
+       private List<String> contacts;
+       private List<String> tags;
+
+       private String pId;
+       private String pName;
+       private String uId;
+       private String pCode;
+       private String pIcon;
+       private String desc;
+       private String role;
+
+       @InjectMocks
+       private ProductBusinessLogic productBusinessLogic;
+
+       @Mock
+       private ToscaOperationFacade toscaOperationFacade;
+
+       @Mock
+       private TitanDao titanDao;
+
+       @Mock
+       private ValidationUtils validationUtils;
+
+       @Mock
+       private ComponentsUtils componentsUtils;
+
+       @Mock
+       private IGraphLockOperation iGraphLockOperation;
+
+       @Mock
+       private UserValidations userValidations;
+
+       @Mock
+       private IElementOperation elementOperation;
+
+       @Before
+       public void setUp() {
+               productBusinessLogic = new ProductBusinessLogic();
+               MockitoAnnotations.initMocks(this);
+               product = new Product();
+               user = new User();
+               contacts = new ArrayList<>();
+               tags = new ArrayList<>();
+
+               pName = "product1";
+               pId = "productId";
+               uId = "userId";
+               pCode = "productCode";
+               pIcon = "projectIcon";
+               desc = "Testing Product Business Logic";
+               role = "PROJECT_MANAGER";
+
+               user.setUserId(uId);
+               user.setRole(role);
        }
 
        @Test
-       public void testDeleteMarkedComponents() throws Exception {
-               ProductBusinessLogic testSubject;
-               Either<List<String>, ResponseFormat> result;
+       public void testCreateProduct_givenValidProductAndUser_thenReturnsProduct() {
+               product.setName(pName);
+               product.setFullName("avengers");
+               product.setInvariantUUID("ABCD1234");
+               product.setContacts(getContacts());
+               product.setTags(getTags());
+               product.setIcon(pIcon);
+               product.setProjectCode(pCode);
+               product.setDescription(desc);
+
+               when(userValidations.validateUserNotEmpty(Mockito.any(User.class), Mockito.anyString()))
+                               .thenReturn(user);
+               when(userValidations.validateUserExists(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.validateComponentNameExists(Mockito.anyString(), Mockito.any(), Mockito.any(ComponentTypeEnum.class)))
+                               .thenReturn(Either.left(Boolean.FALSE));
+               when(iGraphLockOperation.lockComponentByName(Mockito.any(), Mockito.any(NodeTypeEnum.class)))
+                               .thenReturn(StorageOperationStatus.OK);
+               when(toscaOperationFacade.createToscaComponent(any(org.openecomp.sdc.be.model.Product.class)))
+                               .thenReturn(Either.left(product));
+               Either result = productBusinessLogic.createProduct(product, user);
+               assertTrue(result.isLeft());
+               Product returnedProduct = (Product) result.left().value();
+
+               assertEquals(product.getFullName(), returnedProduct.getFullName());
 
-               // default test
-               testSubject = createTestSubject();
-               
        }
 
-       @Test
-       public void testGetComponentInstanceBL() throws Exception {
-               ProductBusinessLogic testSubject;
-               ComponentInstanceBusinessLogic result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       @Test(expected = ComponentException.class)
+       public void testCreateProduct_givenEmptyUserId_thenReturnsException() {
+               when(userValidations.validateUserNotEmpty(Mockito.any(User.class), Mockito.anyString()))
+                               .thenThrow(new ComponentException(new ResponseFormat()));
+               productBusinessLogic.createProduct(product, user);
        }
 
-       @Test
-       public void testGetComponentInstancesFilteredByPropertiesAndInputs() throws Exception {
-               ProductBusinessLogic testSubject;
-               String componentId = "";
-               ComponentTypeEnum componentTypeEnum = null;
-               String userId = "";
-               String searchText = "";
-               Either<List<ComponentInstance>, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       @Test(expected = ComponentException.class)
+       public void testCreateProduct_givenUnknownUser_thenReturnsException() {
+               ComponentException componentException = new ComponentException(ActionStatus.USER_NOT_FOUND);
+               when(userValidations.validateUserNotEmpty(any(User.class), anyString()))
+                               .thenReturn(user);
+               when(userValidations.validateUserExists(anyString(), anyString(), anyBoolean()))
+                               .thenThrow(componentException);
+               productBusinessLogic.createProduct(product, user);
        }
 
-       @Test
-       public void testGetCacheManagerOperation() throws Exception {
-               ProductBusinessLogic testSubject;
-               ICacheMangerOperation result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       @Test(expected = ComponentException.class)
+       public void testCreateProduct_givenInvalidUserRole_thenReturnsException() {
+               user.setRole("CREATOR");
+               doThrow(new ComponentException(new ResponseFormat())).when(userValidations).validateUserRole(any(), anyList());
+               assertTrue(productBusinessLogic.createProduct(product, user).isRight());
        }
 
        @Test
-       public void testSetCacheManagerOperation() throws Exception {
-               ProductBusinessLogic testSubject;
-               ICacheMangerOperation cacheManagerOperation = null;
-
-               // default test
-               testSubject = createTestSubject();
-               testSubject.setCacheManagerOperation(cacheManagerOperation);
+       public void testCreateProduct_givenProductIsNull_thenReturnsError() {
+               product = null;
+               assertTrue(productBusinessLogic.createProduct(product, user).isRight());
        }
 
        @Test
-       public void testGetUiComponentDataTransferByComponentId() throws Exception {
-               ProductBusinessLogic testSubject;
-               String componentId = "";
-               List<String> dataParamsToReturn = null;
-               Either<UiComponentDataTransfer, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testCreateProduct_givenInvalidProductFullNames_thenReturnsErrors() {
+               List<String> invalidProductNames = new ArrayList<>();
+               invalidProductNames.add(null);
+               invalidProductNames.add("~~");
+               invalidProductNames.add("yo");
+               invalidProductNames.add("infinity");
+               when(toscaOperationFacade.validateComponentNameExists(anyString(), any(), any(ComponentTypeEnum.class)))
+                               .thenReturn(Either.left(Boolean.TRUE));
+               for (String s : invalidProductNames) {
+                       product.setName(s);
+                       assertTrue(productBusinessLogic.createProduct(product, user).isRight());
+               }
        }
 
-       
        @Test
-       public void testCreateProduct() throws Exception {
-               ProductBusinessLogic testSubject;
-               Product product = null;
-               User user = null;
-               Either<Product, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               product = null;
-               
+       public void testValidateProductName_givenValidName_thenReturnsSuccessful() {
+               when(userValidations.validateUserExists(anyString(), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.validateComponentNameUniqueness(eq(pName), any(), any(ComponentTypeEnum.class)))
+                               .thenReturn(Either.left(Boolean.TRUE));
+
+               Map result = productBusinessLogic.validateProductNameExists(pName, uId).left().value();
+               assertEquals(Boolean.TRUE, result.get("isValid"));
        }
 
-       
        @Test
-       public void testCheckUnupdatableProductFields() throws Exception {
-               ProductBusinessLogic testSubject;
-               Product product = null;
-
-               // default test
-               testSubject = createTestSubject();
+       public void testValidateProductName_givenInvalidName_thenReturnsError() {
+               String invalidProductName = "~~";
+               when(userValidations.validateUserExists(anyString(), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.validateComponentNameUniqueness(eq(invalidProductName), any(), any(ComponentTypeEnum.class)))
+                               .thenReturn(Either.left(Boolean.FALSE));
+               Map result = productBusinessLogic.validateProductNameExists(invalidProductName, uId).left().value();
+               assertEquals(Boolean.FALSE, result.get("isValid"));
        }
 
-       
        @Test
-       public void testValidateProductBeforeCreate() throws Exception {
-               ProductBusinessLogic testSubject;
-               Product product = null;
-               User user = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Product, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testValidateProductName_givenNameUniquenessCheckFails_thenReturnsError() {
+               when(userValidations.validateUserExists(anyString(), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.validateComponentNameUniqueness(eq(pName), any(), any(ComponentTypeEnum.class)))
+                               .thenReturn(Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS));
+               assertTrue(productBusinessLogic.validateProductNameExists(pName, uId).isRight());
        }
 
-       
        @Test
-       public void testValidateProductFieldsBeforeCreate() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testGetProduct_givenValidProductIdAndUser_thenReturnsSuccessful() {
+               when(toscaOperationFacade.getToscaElement(eq(pName)))
+                               .thenReturn(Either.left(product));
+               assertTrue(productBusinessLogic.getProduct(pName, user).isLeft());
        }
 
-       
        @Test
-       public void testValidateAndUpdateProductContactsList() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testGetProduct_givenInvalidProductId_thenReturnsError() {
+               when(toscaOperationFacade.getToscaElement(eq(pName)))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+               assertTrue(productBusinessLogic.getProduct(pName, user).isRight());
        }
 
-       
        @Test
-       public void testValidateGrouping() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testDeleteProduct_givenValidProductIdAndUser_thenReturnsSuccessful() {
+               when(toscaOperationFacade.deleteToscaComponent(pId))
+                               .thenReturn(Either.left(product));
+               assertTrue(productBusinessLogic.deleteProduct(pId, user).isLeft());
        }
 
-       
        @Test
-       public void testGetProduct() throws Exception {
-               ProductBusinessLogic testSubject;
-               String productId = "";
-               User user = null;
-               Either<Product, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testDeleteProduct_givenInvalidProductId_thenReturnsError() {
+               when(toscaOperationFacade.deleteToscaComponent(pId))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+               assertTrue(productBusinessLogic.deleteProduct(pId, user).isRight());
        }
 
-       
        @Test
-       public void testDeleteProduct() throws Exception {
-               ProductBusinessLogic testSubject;
-               String productId = "";
-               User user = null;
-               Either<Product, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testUpdateProductMetadata_givenValidProductAndUser_thenReturnsSuccessful() {
+               String componentId = "component1";
+               String projectName = "Product1";
+               String version = "2.0";
+               String lifecycleState = "NOT_CERTIFIED_CHECKOUT";
+               String uniqueId = "pUniqueId";
+
+               Product product = new Product();
+               ProductMetadataDataDefinition productMetadataDataDefinition = new ProductMetadataDataDefinition();
+               ComponentMetadataDefinition componentMetadataDefinition = new ComponentMetadataDefinition(productMetadataDataDefinition);
+               CategoryDefinition categoryDefinition = new CategoryDefinition();
+               SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition();
+               GroupingDefinition groupingDefinition = new GroupingDefinition();
+
+               List<CategoryDefinition> categoryDefinitionList = new ArrayList<>();
+               List<SubCategoryDefinition> subCategoryDefinitionList = new ArrayList<>();
+               List<GroupingDefinition> groupingDefinitionsList = new ArrayList<>();
+
+               categoryDefinition.setName("cat1");
+               subCategoryDefinition.setName("subCat1");
+               groupingDefinition.setName("subCatGroup1");
+
+               groupingDefinitionsList.add(groupingDefinition);
+               subCategoryDefinition.setGroupings(groupingDefinitionsList);
+               subCategoryDefinitionList.add(subCategoryDefinition);
+               categoryDefinition.setSubcategories(subCategoryDefinitionList);
+               categoryDefinitionList.add(categoryDefinition);
+
+               productMetadataDataDefinition.setFullName(projectName);
+               productMetadataDataDefinition.setName(projectName);
+               productMetadataDataDefinition.setState(lifecycleState);
+               productMetadataDataDefinition.setUniqueId(uniqueId);
+               productMetadataDataDefinition.setComponentType(ComponentTypeEnum.PRODUCT);
+
+               product.setMetadataDefinition(componentMetadataDefinition);
+               product.setLastUpdaterUserId(uId);
+               product.setDescription(desc);
+               product.setVersion(version);
+               product.setProjectCode(pCode);
+               product.setIcon(pIcon);
+               product.setCategories(categoryDefinitionList);
+               product.setContacts(contacts);
+               product.setTags(tags);
+
+               when(userValidations.validateUserExists(eq(uId), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.getToscaElement(eq(componentId)))
+                               .thenReturn(Either.left(product));
+               when(toscaOperationFacade.getToscaElement(eq(componentId), any(JsonParseFlagEnum.class)))
+                               .thenReturn(Either.left(product));
+               when(elementOperation.getAllProductCategories())
+                               .thenReturn(Either.left(categoryDefinitionList));
+               when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
+                               .thenReturn(StorageOperationStatus.OK);
+               when(toscaOperationFacade.updateToscaElement(any(Product.class)))
+                               .thenReturn(Either.left(product));
+
+               assertTrue(productBusinessLogic.updateProductMetadata(componentId, product, user).isLeft());
        }
 
-       
        @Test
-       public void testValidateProductFullNameAndCleanup() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testUpdateProductMetadata_givenUpdateProductNull_thenReturnsError() {
+               Product updateProduct = null;
+               String productId = null;
+               assertTrue(productBusinessLogic.updateProductMetadata(productId, updateProduct, user).isRight());
        }
 
-       
        @Test
-       public void testValidateProductNameAndCleanup() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
+       public void testUpdateProductMetadata_givenProductDoesNotExist_thenReturnsError() {
+               String productId = "product1";
+               when(toscaOperationFacade.getToscaElement(eq(productId)))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+               assertTrue(productBusinessLogic.updateProductMetadata(productId, product, user).isRight());
        }
 
-       
        @Test
-       public void testValidateTagsListAndRemoveDuplicates() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product product = null;
-               String oldProductName = "";
-               AuditingActionEnum actionEnum = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-       }
+       public void testUpdateProductMetada_givenUserRestricted_thenReturnsError() {
 
-       
-       @Test
-       public void testUpdateProductMetadata() throws Exception {
-               ProductBusinessLogic testSubject;
-               String productId = "";
-               Product updatedProduct = null;
-               User user = null;
-               Either<Product, ResponseFormat> result;
-
-               // test 1
-               testSubject = createTestSubject();
-               updatedProduct = null;
-       }
+               ProductMetadataDataDefinition productMetadataDataDefinition = new ProductMetadataDataDefinition();
+               productMetadataDataDefinition.setLifecycleState("CERTIFIED");
+               ComponentMetadataDefinition componentMetadataDefinition = new ComponentMetadataDefinition(productMetadataDataDefinition);
+               product.setMetadataDefinition(componentMetadataDefinition);
 
-       
-       @Test
-       public void testValidateAndUpdateProductMetadata() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Product, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
-       }
 
-       
-       @Test
-       public void testValidateAndUpdateProductName() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+               when(userValidations.validateUserExists(eq(uId), anyString(), anyBoolean()))
+                               .thenReturn(user);
+               when(toscaOperationFacade.getToscaElement(eq(pId)))
+                               .thenReturn(Either.left(product));
+               when(toscaOperationFacade.getToscaElement(eq(pId), eq(JsonParseFlagEnum.ParseMetadata)))
+                               .thenReturn(Either.left(product));
+               assertTrue(productBusinessLogic.updateProductMetadata(pId, product, user).isRight());
        }
 
-       
-       @Test
-       public void testValidateAndUpdateFullName() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
-       }
 
-       
        @Test
-       public void testValidateAndUpdateCategory() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
-       }
+       public void testGetProductByNameAndVersion_givenValidNameAndVersion_thenReturnsSuccessful() {
+               String productVersion = "2.0";
 
-       
-       @Test
-       public void testValidateAndUpdateContactList() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+               when(toscaOperationFacade.getComponentByNameAndVersion(eq(ComponentTypeEnum.PRODUCT), eq(pName), eq(productVersion)))
+                               .thenReturn(Either.left(product));
+               assertTrue(productBusinessLogic.getProductByNameAndVersion(pName, productVersion, uId).isLeft());
        }
 
-       
        @Test
-       public void testValidateAndUpdateTags() throws Exception {
-               ProductBusinessLogic testSubject;
-               User user = null;
-               Product currentProduct = null;
-               Product updatedProduct = null;
-               Either<Boolean, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       public void testGetProductByNameAndVersion_givenInvalidDetails_thenReturnsError() {
+               String productVersion = "2.0";
+               when(toscaOperationFacade.getComponentByNameAndVersion(eq(ComponentTypeEnum.PRODUCT), eq(pName), eq(productVersion)))
+                               .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+               assertTrue(productBusinessLogic.getProductByNameAndVersion(pName, productVersion, uId).isRight());
        }
 
-       
-       @Test
-       public void testValidateTagPattern() throws Exception {
-               ProductBusinessLogic testSubject;
-               String tag = "";
-               boolean result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       private List<String> getContacts() {
+               contacts.add("user1");
+               return contacts;
        }
 
-       
-       @Test
-       public void testGetProductByNameAndVersion() throws Exception {
-               ProductBusinessLogic testSubject;
-               String productName = "";
-               String productVersion = "";
-               String userId = "";
-               Either<Product, ResponseFormat> result;
-
-               // default test
-               testSubject = createTestSubject();
-               
+       private List<String> getTags() {
+               tags.add("product1");
+               return tags;
        }
 }
\ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java
new file mode 100644 (file)
index 0000000..ea9095f
--- /dev/null
@@ -0,0 +1,307 @@
+/*
+ * -
+ *  * ============LICENSE_START=======================================================
+ *  *  Copyright (C) 2019  Nordix Foundation.
+ *  * ================================================================================
+ *  * 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.
+ *  *
+ *  * SPDX-License-Identifier: Apache-2.0
+ *  * ============LICENSE_END=========================================================
+ *
+ */
+
+package org.openecomp.sdc.be.components.upgrade;
+
+import fj.data.Either;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentDependency;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.ServiceMetadataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.operations.UpgradeOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.exception.ResponseFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+
+public class UpgradeBusinessLogicTest {
+
+    private static final String COMPONENT_ID = "componentId";
+    private static final String USER_ID = "admin123";
+    private static final String SERVICE_ID = "service01";
+    private static final String RESOURCE_ID = "resource01";
+
+    private User user;
+    private Resource resource;
+    private Service service;
+    private ResourceMetadataDefinition resourceMetadataDefinition;
+    private ResourceMetadataDataDefinition resourceMetadataDataDefinition;
+    private ServiceMetadataDefinition serviceMetadataDefinition;
+    private ServiceMetadataDataDefinition serviceMetadataDataDefinition;
+
+    @Mock
+    private LifecycleBusinessLogic lifecycleBusinessLogic;
+
+    @Mock
+    private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+    @Mock
+    private UserValidations userValidations;
+
+    @Mock
+    private ToscaOperationFacade toscaOperationFacade;
+
+    @Mock
+    private ComponentsUtils componentsUtils;
+
+    @Mock
+    private UpgradeOperation upgradeOperation;
+
+    @Mock
+    private TitanDao titanDao;
+
+    @InjectMocks
+    private UpgradeBusinessLogic upgradeBusinessLogic;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        upgradeBusinessLogic = new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic,
+                userValidations, toscaOperationFacade, componentsUtils, upgradeOperation, titanDao);
+
+        user = new User();
+        user.setRole(Role.ADMIN.name());
+        user.setUserId(USER_ID);
+
+        resourceMetadataDataDefinition = new ResourceMetadataDataDefinition();
+        resourceMetadataDefinition = new ResourceMetadataDefinition(resourceMetadataDataDefinition);
+        serviceMetadataDataDefinition = new ServiceMetadataDataDefinition();
+        serviceMetadataDefinition = new ServiceMetadataDefinition(serviceMetadataDataDefinition);
+
+        resource = new Resource(resourceMetadataDefinition);
+        service = new Service(serviceMetadataDefinition);
+
+        when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), anyBoolean()))
+                .thenReturn(user);
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenValidResource_returnsSuccessful() {
+
+        resourceMetadataDataDefinition.setHighestVersion(true);
+        resourceMetadataDataDefinition.setLifecycleState(LifecycleStateEnum.CERTIFIED.name());
+        resourceMetadataDataDefinition.setComponentType(ComponentTypeEnum.RESOURCE);
+        resourceMetadataDataDefinition.setResourceType(ResourceTypeEnum.VF);
+
+        when(toscaOperationFacade.getToscaFullElement(anyString()))
+                .thenReturn(Either.left(resource));
+
+        UpgradeStatus automatedUpgradeStatus = upgradeBusinessLogic.automatedUpgrade(COMPONENT_ID, getRequests(), user.getUserId());
+        assertEquals(ActionStatus.OK, automatedUpgradeStatus.getStatus());
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenResourceIsNotVFType_returnsUnsuccessful() {
+        resourceMetadataDataDefinition.setResourceType(ResourceTypeEnum.PNF);
+        resourceMetadataDataDefinition.setHighestVersion(true);
+        resourceMetadataDataDefinition.setLifecycleState(LifecycleStateEnum.CERTIFIED.name());
+        when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID))
+                .thenReturn(Either.left(resource));
+
+        UpgradeStatus automatedUpgradeStatus = upgradeBusinessLogic.automatedUpgrade(
+                COMPONENT_ID, getRequests(), user.getUserId());
+
+        assertEquals("Status should be GENERAL Error ", ActionStatus.GENERAL_ERROR,
+                automatedUpgradeStatus.getStatus());
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenResourceVersionIsNotHighest_thenReturnsError() {
+        ResponseFormat responseFormat = new ResponseFormat();
+        responseFormat.setStatus(001);
+
+        resourceMetadataDataDefinition.setHighestVersion(false);
+
+        when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID))
+                .thenReturn(Either.left(resource));
+        when(componentsUtils.getResponseFormat(eq(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED), any()))
+                .thenReturn(responseFormat);
+
+        UpgradeStatus status = upgradeBusinessLogic.automatedUpgrade(COMPONENT_ID, null, user.getUserId());
+
+        assertEquals(responseFormat.getStatus(), status.getError().getStatus());
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenInvalidResourceId_thenReturnsError() {
+
+        String invalidResourceId = "invalidResourceId";
+        ResponseFormat stubResponseFormat = new ResponseFormat();
+        stubResponseFormat.setStatus(001);
+
+        when(toscaOperationFacade.getToscaFullElement(invalidResourceId))
+                .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+        when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR))
+                .thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+
+        when(componentsUtils.getResponseFormatByResource(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString()))
+                .thenReturn(stubResponseFormat);
+
+
+        UpgradeStatus status = upgradeBusinessLogic.automatedUpgrade(invalidResourceId,
+                null, user.getUserId());
+        assertEquals(stubResponseFormat.getStatus(), status.getError().getStatus());
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenResourceIsArchived_thenReturnsError() {
+        ResponseFormat responseFormat = new ResponseFormat();
+        responseFormat.setStatus(001);
+
+        resourceMetadataDataDefinition.setHighestVersion(true);
+        resourceMetadataDataDefinition.setLifecycleState(LifecycleStateEnum.CERTIFIED.name());
+        resourceMetadataDataDefinition.setArchived(true);
+
+        when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID))
+                .thenReturn(Either.left(resource));
+        when(componentsUtils.getResponseFormat(eq(ActionStatus.COMPONENT_IS_ARCHIVED), any()))
+                .thenReturn(responseFormat);
+
+        UpgradeStatus status = upgradeBusinessLogic.automatedUpgrade(COMPONENT_ID, null, user.getUserId());
+
+        assertEquals(responseFormat.getStatus(), status.getError().getStatus());
+    }
+
+    @Test
+    public void testAutomatedUpgrade_givenService_thenReturnsSuccessful() {
+        user.setRole(Role.TESTER.name());
+
+        List<String> stubInstanceIdsList = new ArrayList<>();
+
+        List<ComponentInstance> stubComponentInstanceList = new ArrayList<>();
+        ComponentInstance componentInstance = new ComponentInstance();
+        componentInstance.setToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY, Boolean.TRUE);
+        componentInstance.setSourceModelUid("sm1");
+        stubComponentInstanceList.add(componentInstance);
+
+        List<ComponentInstanceProperty> stubComponentPropertyList = new ArrayList<>();
+        ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
+        stubComponentPropertyList.add(componentInstanceProperty);
+
+        Map<String, List<ComponentInstanceProperty>> stubComponentInstanceProperties = new HashMap<>();
+        stubComponentInstanceProperties.put("prop1", stubComponentPropertyList);
+        service.setComponentInstancesProperties(stubComponentInstanceProperties);
+        service.setComponentInstances(stubComponentInstanceList);
+
+        serviceMetadataDataDefinition.setHighestVersion(true);
+        serviceMetadataDataDefinition.setLifecycleState(LifecycleStateEnum.CERTIFIED.name());
+        serviceMetadataDataDefinition.setComponentType(ComponentTypeEnum.SERVICE);
+        serviceMetadataDataDefinition.setUniqueId("sUniqueId1");
+        serviceMetadataDataDefinition.setInvariantUUID("iid");
+        serviceMetadataDataDefinition.setVersion("1.0");
+
+
+        ServiceMetadataDataDefinition serviceMetadataDataDefinition2 = new ServiceMetadataDataDefinition();
+        serviceMetadataDataDefinition2.setLifecycleState(LifecycleStateEnum.CERTIFIED.name());
+        serviceMetadataDataDefinition2.setComponentType(ComponentTypeEnum.SERVICE);
+        serviceMetadataDataDefinition2.setUniqueId("sUniqueId2");
+        serviceMetadataDataDefinition2.setInvariantUUID("iid");
+        serviceMetadataDataDefinition2.setVersion("2.0");
+
+        Service service2 = new Service(new ServiceMetadataDefinition(serviceMetadataDataDefinition2));
+
+        when(toscaOperationFacade.getToscaFullElement(anyString()))
+               .thenReturn(Either.left(service));
+
+        when(toscaOperationFacade.getToscaElement(RESOURCE_ID))
+                .thenReturn(Either.left(service));
+        when(toscaOperationFacade.getToscaElement(eq(componentInstance.getSourceModelUid()), any(ComponentParametersView.class)))
+                .thenReturn(Either.left(service2));
+
+        doReturn(Either.left(service)).when(lifecycleBusinessLogic).changeComponentState(
+                any(ComponentTypeEnum.class), any(), any(User.class),
+                any(LifeCycleTransitionEnum.class), any(LifecycleChangeInfoWithAction.class), anyBoolean(), anyBoolean());
+
+        when(upgradeOperation.getInstanceIdFromAllottedEdge(any(), any()))
+                .thenReturn(stubInstanceIdsList);
+        when(toscaOperationFacade.updateComponentInstancePropsToComponent(any(Map.class), any()))
+                .thenReturn(Either.left(stubComponentInstanceProperties));
+        when(componentInstanceBusinessLogic.changeInstanceVersion(any(Component.class), any(ComponentInstance.class), any(ComponentInstance.class), any(User.class), any(ComponentTypeEnum.class)))
+                .thenReturn(Either.left(componentInstance));
+
+        UpgradeStatus status = upgradeBusinessLogic.automatedUpgrade(COMPONENT_ID, getRequests(), user.getUserId());
+        Assert.assertEquals(ActionStatus.OK, status.getStatus());
+    }
+
+    @Test
+    public void testGetComponentDependencies_givenValidComponentId_thenReturnsSuccessful() {
+        String componentId = "componentId";
+        List<ComponentDependency> stubComponentDependencies
+                = new ArrayList<>();
+        stubComponentDependencies.add(new ComponentDependency());
+
+        when(upgradeOperation.getComponentDependencies(componentId))
+                .thenReturn(Either.left(stubComponentDependencies));
+
+        assertEquals("should contain one component dependency", 1,
+                upgradeBusinessLogic.getComponentDependencies(componentId, user.getUserId()).left().value().size());
+    }
+
+    private List<UpgradeRequest> getRequests() {
+        List<UpgradeRequest> stubRequests = new ArrayList<>();
+        UpgradeRequest request1 = new UpgradeRequest();
+        request1.setServiceId(SERVICE_ID);
+        request1.setResourceId(RESOURCE_ID);
+        stubRequests.add(request1);
+        return stubRequests;
+    }
+}
\ No newline at end of file