diff options
Diffstat (limited to 'catalog-be/src/test/java/org/openecomp/sdc/be/servlets')
37 files changed, 835 insertions, 1414 deletions
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java index 5158c438df..ecc89af3f8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java @@ -20,12 +20,10 @@ package org.openecomp.sdc.be.servlets; -import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.externalapi.servlet.ArtifactExternalServlet; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -34,7 +32,6 @@ import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.exception.ResponseFormat; import javax.ws.rs.core.Response; import java.io.IOException; @@ -69,10 +66,10 @@ public class AbstractValidationsServletTest { String payloadName = "valid_vf.csar"; String rootPath = System.getProperty("user.dir"); - Path path = null; - byte[] data = null; - String payloadData = null; - Either<Map<String, byte[]>, ResponseFormat> returnValue = null; + Path path; + byte[] data; + String payloadData; + Map<String, byte[]> returnValue = null; try { path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar"); data = Files.readAllBytes(path); @@ -83,13 +80,11 @@ public class AbstractValidationsServletTest { Method privateMethod = null; privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getCsarFromPayload", UploadResourceInfo.class); privateMethod.setAccessible(true); - returnValue = (Either<Map<String, byte[]>, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo); + returnValue = (Map<String, byte[]>) privateMethod.invoke(servlet, resourceInfo); } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } - assertTrue(returnValue.isLeft()); - Map<String, byte[]> csar = returnValue.left().value(); - assertNotNull(csar); + assertNotNull(returnValue); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AdditionalInformationServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AdditionalInformationServletTest.java index e49420ef3b..edc01e8800 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AdditionalInformationServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AdditionalInformationServletTest.java @@ -20,18 +20,16 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - import org.junit.Test; import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.user.UserBusinessLogic; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; + +import static org.mockito.Mockito.mock; + public class AdditionalInformationServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java index 2636048408..c670b517ba 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java @@ -22,30 +22,13 @@ package org.openecomp.sdc.be.servlets; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import fj.data.Either; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -59,19 +42,21 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.facade.operations.CatalogOperation; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.catalog.CatalogComponent; @@ -102,6 +87,26 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class ArchiveEndpointTest extends JerseyTest { private static final ServletContext servletContext = mock(ServletContext.class); @@ -113,6 +118,11 @@ public class ArchiveEndpointTest extends JerseyTest { private static final ServletUtils servletUtils = mock(ServletUtils.class); private static final UserBusinessLogic userAdmin = mock(UserBusinessLogic.class); private static final ComponentsUtils componentUtils = mock(ComponentsUtils.class); + private static final CatalogOperation catalogOperations = mock(CatalogOperation.class); +// private static final ToscaOperationFacade toscaOperationFacade = mock(ToscaOperationFacade.class); + private static final ToscaOperationFacade toscaOperationFacade = Mockito.spy(new ToscaOperationFacade()); + + private static final ResponseFormat responseFormat = mock(ResponseFormat.class); private static final ResponseFormat notFoundResponseFormat = mock(ResponseFormat.class); private static final ResponseFormat badRequestResponseFormat = mock(ResponseFormat.class); @@ -137,7 +147,9 @@ public class ArchiveEndpointTest extends JerseyTest { @Bean ArchiveEndpoint archiveEndpoint() { - return new ArchiveEndpoint(archiveBusinessLogic()); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + return new ArchiveEndpoint(userBusinessLogic, componentsUtils, archiveBusinessLogic()); } @Bean @@ -157,7 +169,7 @@ public class ArchiveEndpointTest extends JerseyTest { @Bean ArchiveBusinessLogic archiveBusinessLogic() { - return new ArchiveBusinessLogic(janusGraphDao(), accessValidations(), archiveOperation(), toscaOperationFacade(), componentUtils); + return new ArchiveBusinessLogic(janusGraphDao(), accessValidations(), archiveOperation(), toscaOperationFacade(), componentUtils, catalogOperations); } @Bean @@ -180,7 +192,7 @@ public class ArchiveEndpointTest extends JerseyTest { @Bean ToscaOperationFacade toscaOperationFacade() { - return new ToscaOperationFacade(); + return toscaOperationFacade; } @Bean @@ -281,7 +293,7 @@ public class ArchiveEndpointTest extends JerseyTest { private static final User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(), System.currentTimeMillis()); private static final User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System .currentTimeMillis()); - private static final User otherUser = new User("other", "other", "other", "other@email.com", Role.OPS.name(), System.currentTimeMillis()); + private static final User otherUser = new User("other", "other", "other", "other@email.com", Role.TESTER.name(), System.currentTimeMillis()); @BeforeClass public static void setup() { @@ -307,23 +319,23 @@ public class ArchiveEndpointTest extends JerseyTest { when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat); when(graphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); - - Either<User, ActionStatus> adminEither = Either.left(adminUser); - Either<User, ActionStatus> designerEither = Either.left(designerUser); - Either<User, ActionStatus> otherEither = Either.left(otherUser); - - when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminEither); - when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerEither); - when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherEither); + when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminUser); + when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser); + when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherUser); //======================================================================================================================== - String appConfigDir = "src/test/resources/config/catalog-be"; + String appConfigDir = "src/test/resources/config"; ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); configuration.setJanusGraphInMemoryGraph(true); + org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout(); + heatDeploymentArtifactTimeout.setDefaultMinutes(30);; + configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout); + configurationManager.setConfiguration(configuration); + configurationManager.setConfiguration(configuration); ExternalConfiguration.setAppName("catalog-be"); } @@ -334,15 +346,31 @@ public class ArchiveEndpointTest extends JerseyTest { } @Test - public void archiveAndGetArchivedComponents_SingleComponent() { - archiveComponent(serviceVertex.getUniqueId(), HttpStatus.OK.value()); + public void archiveAndGetArchivedService_SingleService() { + Component serviceComponent = mock(Component.class); + final String serviceUniqueId = serviceVertex.getUniqueId(); + when(toscaOperationFacade.getToscaElement(serviceUniqueId)).thenReturn(Either.left(serviceComponent)); + when(catalogOperations.updateCatalog(ChangeTypeEnum.ARCHIVE, serviceComponent)).thenReturn(ActionStatus.OK); + archiveService(serviceUniqueId, HttpStatus.OK.value()); assertOnGetArchivedComponents(ComponentTypeEnum.SERVICE_PARAM_NAME, 1); + //restoreService(serviceUniqueId, 200); + } + + @Test + public void archiveAndGetArchivedResource_SingleResource() { + Component component = mock(Component.class); + final String uniqueId = resourceVertex.getUniqueId(); + when(toscaOperationFacade.getToscaElement(uniqueId)).thenReturn(Either.left(component)); + when(catalogOperations.updateCatalog(ChangeTypeEnum.ARCHIVE, component)).thenReturn(ActionStatus.OK); + archiveResource(uniqueId, HttpStatus.OK.value()); + assertOnGetArchivedComponents(ComponentTypeEnum.RESOURCE_PARAM_NAME, 1); + //restoreResource(uniqueId, 200); } @Test public void attemptArchiveCheckedOutService() { checkoutComponent(serviceVertex); - archiveComponent(serviceVertex.getUniqueId(), HttpStatus.CONFLICT.value()); + archiveService(serviceVertex.getUniqueId(), HttpStatus.CONFLICT.value()); } @Test @@ -384,12 +412,12 @@ public class ArchiveEndpointTest extends JerseyTest { */ @Test public void archiveWithInvalidUid() { - archiveComponent("fakeUid", HttpStatus.NOT_FOUND.value()); + archiveService("fakeUid", HttpStatus.NOT_FOUND.value()); } @Test public void restoreWithInvalidUid() { - restoreComponent("fakeUid", HttpStatus.NOT_FOUND.value()); + restoreService("fakeUid", HttpStatus.NOT_FOUND.value()); } @Test @@ -420,10 +448,13 @@ public class ArchiveEndpointTest extends JerseyTest { assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); } - private void archiveComponent(String id, int expectedStatus){ archiveOrRestoreComponent(id, ArchiveOperation.Action.ARCHIVE, expectedStatus); } - private void restoreComponent(String id, int expectedStatus){ archiveOrRestoreComponent(id, ArchiveOperation.Action.RESTORE, expectedStatus); } + private void archiveService(String id, int expectedStatus){ archiveOrRestoreService(id, ArchiveOperation.Action.ARCHIVE, expectedStatus); } + private void restoreService(String id, int expectedStatus){ archiveOrRestoreService(id, ArchiveOperation.Action.RESTORE, expectedStatus); } + + private void archiveResource(String id, int expectedStatus){ archiveOrRestoreResource(id, ArchiveOperation.Action.ARCHIVE, expectedStatus); } + private void restoreResource(String id, int expectedStatus){ archiveOrRestoreResource(id, ArchiveOperation.Action.RESTORE, expectedStatus); } - private void archiveOrRestoreComponent(String compUid, ArchiveOperation.Action action, int expectedStatus) { + private void archiveOrRestoreService(String compUid, ArchiveOperation.Action action, int expectedStatus) { String path = String.format("/v1/catalog/services/%s/%s", compUid, action.name().toLowerCase()); Response response = target() .path(path) @@ -435,6 +466,18 @@ public class ArchiveEndpointTest extends JerseyTest { assertThat(response.getStatus()).isEqualTo(expectedStatus); } + private void archiveOrRestoreResource(String compUid, ArchiveOperation.Action action, int expectedStatus) { + String path = String.format("/v1/catalog/resources/%s/%s", compUid, action.name().toLowerCase()); + Response response = target() + .path(path) + .request() + .accept(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, designerUser.getUserId()) + .post(null); + + assertThat(response.getStatus()).isEqualTo(expectedStatus); + } + private void assertOnGetArchivedComponents(String componentType, int expectedCount) { String path = "/v1/catalog/archive"; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArtifactServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArtifactServletTest.java index 74a6555eca..efa5b51041 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArtifactServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArtifactServletTest.java @@ -20,19 +20,16 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - import org.junit.Test; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.user.UserBusinessLogic; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; + +import static org.mockito.Mockito.mock; + public class ArtifactServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AttributeServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AttributeServletTest.java index 47d2cf4f2f..6184fa8d7e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AttributeServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AttributeServletTest.java @@ -20,14 +20,9 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - +import com.google.common.base.Equivalence.Wrapper; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; @@ -35,7 +30,10 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.common.base.Equivalence.Wrapper; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; + +import static org.mockito.Mockito.mock; public class AttributeServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java index 3f07d95096..91f9b5b919 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.upgrade.ServiceInfo; @@ -44,7 +43,13 @@ import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ComponentInstance; +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.Service; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.UpgradeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -68,10 +73,10 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); @@ -143,7 +148,7 @@ public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { @Before public void init() { prepareComponents(); - when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(user); + when(userValidations.validateUserExists(eq(USER_ID))).thenReturn(user); when(toscaOperationFacade.getToscaFullElement(eq(RESOURCE_ID_PREV))).thenReturn(Either.left(vfPrev)); when(toscaOperationFacade.getToscaFullElement(eq(RESOURCE_ID_NEW))).thenReturn(Either.left(vfNew)); when(toscaOperationFacade.getToscaFullElement(eq(SERVICE_ID_PREV))).thenReturn(Either.left(servicePrev)); @@ -154,7 +159,7 @@ public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { eq(true)); when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID_PREV), any(ComponentParametersView.class))).thenReturn(Either.left(vfPrev)); - when(componentInstanceBusinessLogic.changeInstanceVersion(any(Service.class), any(ComponentInstance.class), any(ComponentInstance.class), any(User.class), eq(ComponentTypeEnum.SERVICE))).thenReturn(Either.left(istanceNew)); + when(componentInstanceBusinessLogic.changeInstanceVersion(any(Service.class), any(ComponentInstance.class), any(ComponentInstance.class), any(User.class), eq(ComponentTypeEnum.SERVICE))).thenReturn(istanceNew); doReturn(Either.left(serviceNewCheckIn)).when(lifecycleBusinessLogic).changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_NEW), any(User.class), eq(LifeCycleTransitionEnum.CHECKIN), any(LifecycleChangeInfoWithAction.class), eq(false), eq(true)); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java index ca407eaed0..f5b558e0d6 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java @@ -20,12 +20,9 @@ package org.openecomp.sdc.be.servlets; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import fj.data.Either; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import javax.ws.rs.client.Entity; import org.eclipse.jetty.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; @@ -45,31 +42,38 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.model.User; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; -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.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.SERVICE_PARAM_NAME; /** * The test suite designed for test functionality of ComponentInstanceServlet class @@ -111,10 +115,11 @@ public class ComponentInstanceServletTest extends JerseyTest { Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) .header("USER_ID", USER_ID) .get( Response.class); - assertEquals(response.getStatus(), HttpStatus.OK_200); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200); } @Test @@ -136,36 +141,6 @@ public class ComponentInstanceServletTest extends JerseyTest { } @Test - public void testCopyComponentInstanceSuccess(){ - - String componentId = "componentId"; - String componentInstanceId = "componentInstanceId"; - String path = "/v1/catalog/services/" + componentId + "/copyComponentInstance/" + componentInstanceId; - - Either<Map<String, ComponentInstance>, ResponseFormat> successResponse = Either.left(new HashMap<String, ComponentInstance>()); - when(componentInstanceBusinessLogic.copyComponentInstance(any(ComponentInstance.class), eq(componentId), eq(componentInstanceId), eq(USER_ID))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); - - ComponentInstance c = new ComponentInstance(); - c.setName("comp1"); - c.setUniqueId("comp1"); - c.setComponentUid("comp1"); - c.setPosX("10"); - c.setPosY("10"); - c.setCapabilities(new HashMap<String, List<CapabilityDefinition>>()); - c.setRequirements(new HashMap<String, List<RequirementDefinition>>()); - - Response response = target() - .path(path) - .request(MediaType.APPLICATION_JSON) - .header("USER_ID", USER_ID) - .post(Entity.json(c)); - - assertEquals(response.getStatus(), HttpStatus.OK_200); - } - - @Test public void testBatchDeleteResourceInstancesSuccess() { String componentId = "componentId"; @@ -237,7 +212,7 @@ public class ComponentInstanceServletTest extends JerseyTest { when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class), ArgumentMatchers.<Class<RequirementCapabilityRelDef[]>>any(), nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(convertReqEither); - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponseEither = Either.left(ref); + RequirementCapabilityRelDef actionResponseEither = ref; when(componentInstanceBusinessLogic .dissociateRIFromRI(componentId, USER_ID, ref, ComponentTypeEnum.findByParamName(containerComponentType))) .thenReturn(actionResponseEither); @@ -317,4 +292,142 @@ public class ComponentInstanceServletTest extends JerseyTest { when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); } + + @Test + public void testUpdateResourceInstancePropertiesSuccess(){ + + String containerComponentType = "services"; + String componentId = "componentId"; + String resourceInstanceId = "resourceInstanceId"; + ComponentInstanceProperty [] properties = new ComponentInstanceProperty[1]; + ComponentInstanceProperty property = new ComponentInstanceProperty(); + property.setName("property"); + property.setValue("value"); + property.setType("String"); + properties[0] = (property); + ObjectMapper mapper = new ObjectMapper(); + String propertyJson = null; + try { + propertyJson = mapper.writeValueAsString(properties); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" + + resourceInstanceId + "/properties"; + when(componentsUtils.convertJsonToObjectUsingObjectMapper(propertyJson, new User(), ComponentInstanceProperty[].class, + null, ComponentTypeEnum.RESOURCE_INSTANCE)).thenReturn(Either.left(properties)); + when(componentInstanceBusinessLogic.createOrUpdatePropertiesValues(eq(ComponentTypeEnum.findByParamName(SERVICE_PARAM_NAME)), + eq(componentId), eq(resourceInstanceId), eq(Arrays.asList(properties)), eq(USER_ID))).thenReturn(Either.left(Arrays.asList(properties))); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID).post(Entity.entity(properties, MediaType.APPLICATION_JSON)); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200); + } + + @Test + public void testUpdateResourceInstanceInputsSuccess(){ + + String containerComponentType = "services"; + String componentId = "componentId"; + String resourceInstanceId = "resourceInstanceId"; + ComponentInstanceInput[] inputs = new ComponentInstanceInput[1]; + ComponentInstanceInput input = new ComponentInstanceInput(); + input.setName("input"); + input.setValue("value"); + input.setType("String"); + inputs[0] = (input); + ObjectMapper mapper = new ObjectMapper(); + String inputJson = null; + try { + inputJson = mapper.writeValueAsString(inputs); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" + + resourceInstanceId + "/inputs"; + when(componentsUtils.convertJsonToObjectUsingObjectMapper(inputJson, new User(), ComponentInstanceInput[].class, + null, ComponentTypeEnum.RESOURCE_INSTANCE)).thenReturn(Either.left(inputs)); + when(componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(eq(ComponentTypeEnum.findByParamName(SERVICE_PARAM_NAME)), + eq(componentId), eq(resourceInstanceId), eq(Arrays.asList(inputs)), eq(USER_ID))).thenReturn(Either.left(Arrays.asList(inputs))); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID).post(Entity.entity(inputs, MediaType.APPLICATION_JSON)); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200); + } + + @Test + public void testUpdateResourceInstancePropertiesFailure(){ + + String containerComponentType = "services"; + String componentId = "componentId"; + String resourceInstanceId = "resourceInstanceId"; + ComponentInstanceProperty [] properties = new ComponentInstanceProperty[1]; + ComponentInstanceProperty property = new ComponentInstanceProperty(); + property.setName("property"); + property.setValue("value"); + property.setType("String"); + properties[0] = (property); + ObjectMapper mapper = new ObjectMapper(); + String propertyJson = null; + try { + propertyJson = mapper.writeValueAsString(properties); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" + + resourceInstanceId + "/properties"; + when(componentsUtils.convertJsonToObjectUsingObjectMapper(propertyJson, new User(), ComponentInstanceProperty[].class, + null, ComponentTypeEnum.RESOURCE_INSTANCE)).thenReturn(Either.left(properties)); + when(componentInstanceBusinessLogic.createOrUpdatePropertiesValues(eq(ComponentTypeEnum.findByParamName(SERVICE_PARAM_NAME)), + eq(componentId), eq(resourceInstanceId), eq(Arrays.asList(properties)), eq(USER_ID))) + .thenReturn(Either.right(new ResponseFormat(404))); + when(responseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND_404); + when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID).post(Entity.entity(properties, MediaType.APPLICATION_JSON)); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND_404); + } + + @Test + public void testUpdateResourceInstanceInputsFailure(){ + + String containerComponentType = "services"; + String componentId = "componentId"; + String resourceInstanceId = "resourceInstanceId"; + ComponentInstanceInput [] inputs = new ComponentInstanceInput[1]; + ComponentInstanceInput input = new ComponentInstanceInput(); + input.setName("input"); + input.setValue("value"); + input.setType("String"); + inputs[0] = (input); + ObjectMapper mapper = new ObjectMapper(); + String inputJson = null; + try { + inputJson = mapper.writeValueAsString(inputs); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" + + resourceInstanceId + "/inputs"; + when(componentsUtils.convertJsonToObjectUsingObjectMapper(inputJson, new User(), ComponentInstanceInput[].class, + null, ComponentTypeEnum.RESOURCE_INSTANCE)).thenReturn(Either.left(inputs)); + when(componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(eq(ComponentTypeEnum.findByParamName(SERVICE_PARAM_NAME)), + eq(componentId), eq(resourceInstanceId), eq(Arrays.asList(inputs)), eq(USER_ID))) + .thenReturn(Either.right(new ResponseFormat(404))); + when(responseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND_404); + when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID).post(Entity.entity(inputs, MediaType.APPLICATION_JSON)); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND_404); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java index 4fcbd06927..02d273b8a9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import com.google.gson.Gson; import fj.data.Either; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpSession; -import javax.ws.rs.core.Response; import org.glassfish.grizzly.http.util.HttpStatus; import org.junit.Assert; import org.junit.Before; @@ -48,6 +40,14 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Response; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class ComponentPropertyServletTest extends JerseySpringBaseTest { @Mock @@ -72,6 +72,11 @@ public class ComponentPropertyServletTest extends JerseySpringBaseTest { private static final String INVALID_PROPERTY_NAME = "invalid_name_$.&"; private static final String STRING_TYPE = "string"; + @Before + public void initClass() { + initMockitoStubbings(); + } + @Test public void testCreatePropertyOnService_success() { PropertyDefinition property = new PropertyDefinition(); @@ -105,6 +110,14 @@ public class ComponentPropertyServletTest extends JerseySpringBaseTest { Assert.assertEquals(HttpStatus.BAD_REQUEST_400.getStatusCode(), propertyInService.getStatus()); } + private static void initMockitoStubbings() { + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(context); + when(context.getAttribute(eq(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))).thenReturn(wrapper); + when(wrapper.getWebAppContext(any())).thenReturn(webAppContext); + when(webAppContext.getBean(eq(ComponentsUtils.class))).thenReturn(componentsUtils); + } + private String getValidProperty() { return "{\n" + " \"valid_name_123\": {\n" diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentServletTest.java index 8f823c3a7c..0e444fee92 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentServletTest.java @@ -27,8 +27,6 @@ import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -55,8 +53,6 @@ public class ComponentServletTest extends JerseySpringBaseTest{ private static final String USER_ID = "userId"; private static final String RESOURCE_ID = "resourceId"; private ResourceBusinessLogic resourceBusinessLogic; - private UserBusinessLogic userBusinessLogic; - private ComponentsUtils componentsUtils; private PolicyDefinition policy1, policy2; @Override @@ -70,10 +66,9 @@ public class ComponentServletTest extends JerseySpringBaseTest{ @Override protected ResourceConfig configure() { resourceBusinessLogic = mock(ResourceBusinessLogic.class); - userBusinessLogic = mock(UserBusinessLogic.class); - componentsUtils = mock(ComponentsUtils.class); - ComponentServlet componentServlet = new ComponentServlet(userBusinessLogic, componentsUtils, - new ComponentBusinessLogicProvider(resourceBusinessLogic, null, null)); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + ComponentServlet componentServlet = new ComponentServlet(userBusinessLogic, componentsUtils, new ComponentBusinessLogicProvider(resourceBusinessLogic, null, null)); return super.configure().register(componentServlet); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigMgrServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigMgrServletTest.java index 97537cbe8b..2ec190f93b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigMgrServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigMgrServletTest.java @@ -20,11 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.http.HttpServletRequest; - +import com.datastax.driver.core.Configuration; import org.junit.Test; -import com.datastax.driver.core.Configuration; +import javax.servlet.http.HttpServletRequest; public class ConfigMgrServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigServletTest.java index a982dabaf4..36eb3e9909 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConfigServletTest.java @@ -20,10 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.http.HttpServletRequest; - import org.junit.Test; +import javax.servlet.http.HttpServletRequest; + public class ConfigServletTest { private ConfigServlet createTestSubject() { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConsumerServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConsumerServletTest.java deleted file mode 100644 index 6aa11a6366..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ConsumerServletTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ConsumerDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.exception.ResponseFormat; - -import fj.data.Either; - -public class ConsumerServletTest { - - private ConsumerServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - ConsumerBusinessLogic consumerBusinessLogic = mock(ConsumerBusinessLogic.class); - return new ConsumerServlet(userBusinessLogic, componentsUtils, consumerBusinessLogic); - } - - - @Test - public void testCreateConsumer() throws Exception { - ConsumerServlet testSubject; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetConsumer() throws Exception { - ConsumerServlet testSubject; - String consumerId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testDeleteConsumer() throws Exception { - ConsumerServlet testSubject; - String consumerId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetConsumerBL() throws Exception { - ConsumerServlet testSubject; - ServletContext context = null; - ConsumerBusinessLogic result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testConvertJsonToObject() throws Exception { - ConsumerServlet testSubject; - String data = ""; - User user = null; - AuditingActionEnum actionEnum = null; - Either<ConsumerDefinition, ResponseFormat> result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/CsarBuildServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/CsarBuildServletTest.java deleted file mode 100644 index 6d820841f0..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/CsarBuildServletTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.components.impl.ResourceImportManager; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.DownloadArtifactLogic; -import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.resources.api.IResourceUploader; -import org.openecomp.sdc.be.user.UserBusinessLogic; - - -public class CsarBuildServletTest { - - private CsarBuildServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - IResourceUploader resourceUploader = mock(IResourceUploader.class); - DownloadArtifactLogic logic = mock(DownloadArtifactLogic.class); - - return new CsarBuildServlet(userBusinessLogic, componentsUtils, resourceUploader, - logic); - } - - - @Test - public void testGetDefaultTemplate() throws Exception { - CsarBuildServlet testSubject; - HttpServletRequest request = null; - String serviceName = ""; - String serviceVersion = ""; - Response result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDefaultTemplate(request, serviceName, serviceVersion); - } - - - @Test - public void testGetToscaCsarTemplate() throws Exception { - CsarBuildServlet testSubject; - HttpServletRequest request = null; - String serviceName = ""; - String serviceVersion = ""; - Response result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaCsarTemplate(request, serviceName, serviceVersion); - } - - - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/DistributionServiceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/DistributionServiceServletTest.java index df26749ef0..7a89a6bee5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/DistributionServiceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/DistributionServiceServletTest.java @@ -20,18 +20,16 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.user.UserBusinessLogic; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.user.UserBusinessLogic; +import static org.mockito.Mockito.mock; public class DistributionServiceServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ElementServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ElementServletTest.java index 16d0942e0f..f90ef19293 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ElementServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ElementServletTest.java @@ -22,9 +22,9 @@ package org.openecomp.sdc.be.servlets; -import com.google.common.collect.Lists; import fj.data.Either; import org.apache.commons.text.StrSubstitutor; +import org.apache.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; @@ -32,7 +32,6 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; -import org.apache.http.HttpStatus; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; @@ -41,11 +40,11 @@ import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; +import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -77,9 +76,10 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import java.util.*; -import java.util.stream.Collectors; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -92,6 +92,7 @@ public class ElementServletTest extends JerseyTest { public static final HttpSession session = Mockito.mock(HttpSession.class); public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + public static final BeGenericServlet beGenericServlet = Mockito.mock(BeGenericServlet.class); public static final Resource resource = Mockito.mock(Resource.class); public static final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class); public static final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class); @@ -126,6 +127,8 @@ public class ElementServletTest extends JerseyTest { private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System .currentTimeMillis()); + private static ConfigurationManager configurationManager; + @BeforeClass public static void setup() { @@ -157,20 +160,31 @@ public class ElementServletTest extends JerseyTest { when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), any())).thenReturn(notFoundResponseFormat); when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), any())).thenReturn(notFoundResponseFormat); when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), any())).thenReturn(badRequestResponseFormat); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + when(beGenericServlet.getElementBL(any())).thenReturn(elementBusinessLogic); + when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic); + when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentUtils); + when(beGenericServlet.getComponentsUtils()).thenReturn(componentUtils); Either<User, ActionStatus> designerEither = Either.left(designerUser); - when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerEither); + when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser); String appConfigDir = "src/test/resources/config"; ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + configurationManager = new ConfigurationManager(configurationSource); org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); configuration.setJanusGraphInMemoryGraph(true); + Configuration.HeatDeploymentArtifactTimeout testHeatDeploymentArtifactTimeout = new Configuration.HeatDeploymentArtifactTimeout(); + testHeatDeploymentArtifactTimeout.setDefaultMinutes(1); + configuration.setHeatArtifactDeploymentTimeout(testHeatDeploymentArtifactTimeout); configurationManager.setConfiguration(configuration); ExternalConfiguration.setAppName("catalog-be"); + + } @Before @@ -271,7 +285,7 @@ public class ElementServletTest extends JerseyTest { @Test public void getAllCategoriesExceptionDuringProcessingTest() { - String path = "/v1/categories"; + String path = "/v1/setup/ui"; when(elementBusinessLogic.getAllCategories(designerUser.getUserId())) .thenThrow(new RuntimeException("Test exception: getAllCategories")); @@ -287,8 +301,16 @@ public class ElementServletTest extends JerseyTest { @Test public void getAllCategoriesTest() { - String path = "/v1/categories"; + String path = "/v1/setup/ui"; Either<UiCategories, ResponseFormat> getAllCategoriesEither = Either.left(new UiCategories()); + Either<List<ArtifactType>, ActionStatus> otherEither = Either.left(new ArrayList<>()); + when(elementBusinessLogic.getDefaultHeatTimeout()).thenReturn(Either.left(configurationManager.getConfiguration().getHeatArtifactDeploymentTimeout())); + when(elementBusinessLogic.getAllDeploymentArtifactTypes()).thenReturn(Either.left(new HashMap<String, Object>())); + when(elementBusinessLogic.getResourceTypesMap()).thenReturn(Either.left(new HashMap<String, String>())); + when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId())) + .thenReturn(otherEither); + + when(elementBusinessLogic.getAllCategories(designerUser.getUserId())) .thenReturn(getAllCategoriesEither); @@ -933,10 +955,12 @@ public class ElementServletTest extends JerseyTest { @Test public void configurationNoConfigurationFoundTest() { - String path = "/v1/configuration/ui"; + String path = "/v1/setup/ui"; Either<List<ArtifactType>, ActionStatus> otherEither = Either.left(new ArrayList<>()); - Either<Integer, ActionStatus> defaultHeatTimeoutEither = Either.left(1); + Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new Configuration.HeatDeploymentArtifactTimeout(); + heatDeploymentArtifactTimeout.setDefaultMinutes(1); + Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> defaultHeatTimeoutEither = Either.left(heatDeploymentArtifactTimeout); Either<Map<String, Object>, ActionStatus> deploymentEither = Either.left(new HashMap<>()); Either<Map<String, String>, ActionStatus> resourceTypesMapEither = Either.left(new HashMap<>()); @@ -956,12 +980,12 @@ public class ElementServletTest extends JerseyTest { .header(Constants.USER_ID_HEADER, designerUser.getUserId()) .get(); - assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK); + assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR); } @Test public void configurationExceptionDuringProcessingTest() { - String path = "/v1/configuration/ui"; + String path = "/v1/setup/ui"; when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId())) .thenThrow(new RuntimeException("Test exception: artifactTypes")); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpointTest.java new file mode 100644 index 0000000000..07435c4e03 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpointTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import org.apache.http.HttpStatus; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Test; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ExceptionHandlerEndpointTest extends JerseySpringBaseTest { + + private static ComponentsUtils componentUtils; + + @org.springframework.context.annotation.Configuration + @Import(BaseTestConfig.class) + static class ExceptionHandlerConfig { + + @Bean + ExceptionHandlerEndpoint exceptionHandlerEndpoint() { + return new ExceptionHandlerEndpoint(componentUtils); + } + } + + @Override + protected void configureClient(ClientConfig config) { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + config.register(jacksonJsonProvider); + } + + @Override + protected ResourceConfig configure() { + componentUtils = mock(ComponentsUtils.class); + + return super.configure(ExceptionHandlerConfig.class) + .register(ExceptionHandlerEndpoint.class); + } + + @Test + public void getHandleException() { + when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + Response response = target().path("/v1/catalog/handleException").request().get(Response.class); + assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus()); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java index 20741aad73..742382155a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java @@ -39,6 +39,8 @@ import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; @@ -47,6 +49,7 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; +import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; @@ -72,7 +75,9 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.anyList; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.openecomp.sdc.be.model.operations.api.StorageOperationStatus.NOT_FOUND; public class GroupEndpointTest extends JerseySpringBaseTest { @@ -101,7 +106,10 @@ public class GroupEndpointTest extends JerseySpringBaseTest { @Bean GroupEndpoint groupEndpoint() { - return new GroupEndpoint(groupBusinessLogic()); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + + return new GroupEndpoint(userBusinessLogic, componentsUtils, groupBusinessLogic()); } @Bean @@ -168,9 +176,9 @@ public class GroupEndpointTest extends JerseySpringBaseTest { when(accessValidations.validateUserCanRetrieveComponentData(eq(VALID_COMPONENT_ID), eq("resources"), eq(VALID_USER), anyString())) .thenReturn(cr); when(componentValidations.getComponentInstance(cr, A)).thenReturn(Optional.of(ci)); - doNothing().when(groupsOperation).updateGroupOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class)); + doNothing().when(groupsOperation).updateGroupOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), any(PromoteVersionEnum.class)); when(groupOperation.validateAndUpdatePropertyValue(isA(GroupProperty.class))).thenReturn(StorageOperationStatus.OK); - when(groupsOperation.updateGroupPropertiesOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), anyList())).thenAnswer(new Answer<Either>() { + when(groupsOperation.updateGroupPropertiesOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), anyList(), any(PromoteVersionEnum.class))).thenAnswer(new Answer<Either>() { @Override public Either answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupServletTest.java index 01383eae14..ddd5a2098d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupServletTest.java @@ -20,21 +20,19 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - import org.junit.Test; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.resources.api.IResourceUploader; import org.openecomp.sdc.be.user.UserBusinessLogic; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; + +import static org.mockito.Mockito.mock; + public class GroupServletTest { private GroupServlet createTestSubject() { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java index c6cd098f8f..286c1a0656 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java @@ -43,8 +43,13 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; -import org.openecomp.sdc.be.model.operations.impl.*; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.OperationUtils; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.resources.data.GroupTypeData; +import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; @@ -63,10 +68,10 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.mockito.Mockito.mock; public class GroupTypesEndpointTest extends JerseySpringBaseTest { @@ -95,7 +100,9 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { @Bean GroupTypesEndpoint groupTypesEndpoint() { - return new GroupTypesEndpoint(groupTypeBusinessLogic()); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + return new GroupTypesEndpoint(userBusinessLogic, componentsUtils, groupTypeBusinessLogic()); } @Bean @@ -123,7 +130,7 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { @Before public void init() { - when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(user); + when(userValidations.validateUserExists(eq(USER_ID))).thenReturn(user); when(janusGraphGenericDao.getByCriteriaWithPredicate(eq(NodeTypeEnum.GroupType), any(), eq(GroupTypeData.class))).thenReturn(Either.left(buildGroupTypeDataList())); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/InputsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/InputsServletTest.java index da5352c206..0974bd5dd4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/InputsServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/InputsServletTest.java @@ -21,11 +21,9 @@ package org.openecomp.sdc.be.servlets; import fj.data.Either; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Application; +import org.glassfish.grizzly.http.util.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.grizzly.http.util.HttpStatus; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.BeforeClass; @@ -37,7 +35,10 @@ import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.InputsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -53,17 +54,23 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper; import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; @@ -75,7 +82,12 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class InputsServletTest extends JerseyTest { @@ -106,6 +118,10 @@ public class InputsServletTest extends JerseyTest { private static ResourceImportManager resourceImportManager; private static HttpServletRequest request; + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + @BeforeClass public static void configureMocks() { request = mock(HttpServletRequest.class); @@ -120,6 +136,8 @@ public class InputsServletTest extends JerseyTest { componentsUtils = mock(ComponentsUtils.class); servletUtils = mock(ServletUtils.class); resourceImportManager = mock(ResourceImportManager.class); + + } @Before @@ -152,6 +170,7 @@ public class InputsServletTest extends JerseyTest { servletUtils, resourceImportManager, dataTypeBusinessLogic); ResourceConfig resourceConfig = new ResourceConfig() .register(inputsServlet) + .register(new ComponentExceptionMapper(componentsUtils)) .register(new AbstractBinder() { @Override protected void configure() { @@ -164,6 +183,9 @@ public class InputsServletTest extends JerseyTest { return resourceConfig; } + + + private InputDefinition setUpListInput() { InputDefinition listInput = new InputDefinition(); listInput.setName(LISTINPUT_NAME); @@ -390,7 +412,7 @@ public class InputsServletTest extends JerseyTest { @Test public void test_deleteInput_success() throws Exception { when(inputsBusinessLogic.deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME)) - .thenReturn(Either.left(new InputDefinition())); + .thenReturn(new InputDefinition()); when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode())); // invoke delete call @@ -407,28 +429,9 @@ public class InputsServletTest extends JerseyTest { @Test public void test_deleteInput_failure_deleteInput() throws Exception { - doReturn(Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()))).when(inputsBusinessLogic) - .deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME); - - ResponseFormat responseFormat = new ResponseFormat(HttpStatus.OK_200.getStatusCode()); - doReturn(responseFormat).when(componentsUtils).getResponseFormat(ActionStatus.OK); - - // invoke delete call - Response response = target("/v1/catalog/services/{id}/delete/{inputId}/input") - .resolveTemplate("id", RESOURCE_ID) - .resolveTemplate("inputId", LISTINPUT_NAME) - .request(MediaType.APPLICATION_JSON) - .header(Constants.USER_ID_HEADER, USER_ID) - .delete(); - assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode()); - verify(componentsUtils, never()).getResponseFormat(ActionStatus.OK); - } - - - @Test - public void test_deleteInput_failure_exception() throws Exception { - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode())); - when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode())); + ComponentException componentException = new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + when(inputsBusinessLogic.deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME)) + .thenThrow(componentException); // invoke delete call Response response = target("/v1/catalog/services/{id}/delete/{inputId}/input") diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java index 5b204476b0..af5c421078 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - import com.fasterxml.jackson.databind.DeserializationFeature; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Feature; import org.glassfish.grizzly.servlet.HttpSessionImpl; import org.glassfish.grizzly.servlet.WebappContext; import org.glassfish.hk2.utilities.binding.AbstractBinder; @@ -36,6 +30,7 @@ import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvi import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.TestProperties; import org.junit.BeforeClass; @@ -47,6 +42,13 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Feature; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.mockito.Mockito.mock; + public abstract class JerseySpringBaseTest extends JerseyTest { private static final Logger log = Logger.getLogger(JerseySpringBaseTest.class.getName()); @@ -88,6 +90,7 @@ public abstract class JerseySpringBaseTest extends JerseyTest { bind(request).to(HttpServletRequest.class); } }) + .register(RolesAllowedDynamicFeature.class) .register(DefaultExceptionMapper.class) .register(ComponentExceptionMapper.class) .register(StorageExceptionMapper.class) diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/LifecycleServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/LifecycleServletTest.java deleted file mode 100644 index b69f2a58dd..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/LifecycleServletTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.User; - -import fj.data.Either; -import org.openecomp.sdc.be.user.UserBusinessLogic; - -public class LifecycleServletTest { - - private LifecycleServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - LifecycleBusinessLogic lifecycleBusinessLogic = mock(LifecycleBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - - return new LifecycleServlet(userBusinessLogic, componentsUtils, lifecycleBusinessLogic); - } - - - @Test - public void testChangeResourceState() throws Exception { - LifecycleServlet testSubject; - String jsonChangeInfo = ""; - String componentCollection = ""; - String lifecycleTransition = ""; - String componentId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testValidateTransitionEnum() throws Exception { - LifecycleServlet testSubject; - String lifecycleTransition = ""; - User user = null; - Either<LifeCycleTransitionEnum, Response> result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java index 2d181ccbf6..1ba2c44a24 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java @@ -20,27 +20,8 @@ package org.openecomp.sdc.be.servlets; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.common.api.Constants.GET_POLICY; - import com.fasterxml.jackson.databind.DeserializationFeature; import fj.data.Either; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.glassfish.grizzly.http.util.HttpStatus; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; @@ -58,8 +39,13 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.aaf.RoleAuthorizationHandler; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -82,9 +68,37 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.exception.ResponseFormat; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.common.api.Constants.GET_POLICY; + + + @RunWith(MockitoJUnitRunner.class) public class PolicyServletTest extends JerseySpringBaseTest{ @@ -95,6 +109,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ private static ServletUtils servletUtils; private static PropertyDeclarationOrchestrator propertyDeclarationOrchestrator; private static ToscaOperationFacade toscaOperationFacade; + private static RoleAuthorizationHandler roleAuthorizationHandler; private static ResponseFormat responseFormat; @Captor private static ArgumentCaptor<PolicyDefinition> policyCaptor; @@ -114,25 +129,33 @@ public class PolicyServletTest extends JerseySpringBaseTest{ private static final String PROP_1 = "prop1"; private static final String UPDATE_TARGETS_URL = "/v1/catalog/{componentType}/{componentId}/policies/{policyId}/targets"; + static ConfigurationSource configurationSource = new FSConfigurationSource( + ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); @BeforeClass public static void initClass() { + ResponseFormatManager.getInstance(); createMocks(); when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); } - + @Before public void beforeMethod() { + Mockito.reset(businessLogic); final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider))); + ThreadLocalsHolder.setApiType(FilterDecisionEnum.EXTERNAL); + when(request.isUserInRole(anyString())).thenReturn(true); + } + @Test public void testGetPolicySuccess(){ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; - Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition()); + PolicyDefinition successResponse = new PolicyDefinition(); when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -145,8 +168,6 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void testGetPolicyFailure(){ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -160,7 +181,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ public void testPostPolicySuccess(){ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName; PolicyDefinition policy = new PolicyDefinition(); - Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy); + PolicyDefinition successResponse = policy; when(businessLogic.createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true))).thenReturn(successResponse); when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); when(componentsUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); @@ -177,8 +198,6 @@ public class PolicyServletTest extends JerseySpringBaseTest{ public void testPostPolicyFailure(){ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName; PolicyDefinition policy = new PolicyDefinition(); - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -193,9 +212,8 @@ public class PolicyServletTest extends JerseySpringBaseTest{ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; PolicyDefinition policy = new PolicyDefinition(); policy.setUniqueId(POLICY_ID); - Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy); + PolicyDefinition successResponse = policy; when(businessLogic.updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID), eq(true))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -209,8 +227,6 @@ public class PolicyServletTest extends JerseySpringBaseTest{ public void testPutPolicyFailure(){ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; PolicyDefinition policy = new PolicyDefinition(); - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -223,9 +239,8 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void testDeletePolicySuccess(){ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; - Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition()); + PolicyDefinition successResponse = new PolicyDefinition(); when(businessLogic.deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -238,8 +253,6 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void testDeletePolicyFailure(){ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); Response response = target() .path(path) .request(MediaType.APPLICATION_JSON) @@ -251,12 +264,14 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void getPolicyProperties_operationForbidden() { - when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.right(new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()))); + // doThrow(new ComponentException(ActionStatus.GENERAL_ERROR)).when(businessLogic).getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID); + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)) + .thenThrow(new ByActionStatusComponentException(ActionStatus.AUTH_FAILED, USER_ID)); Response response = buildGetPropertiesRequest().get(); assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); } - @Test + @Test//(expected = ComponentException.class) public void getPolicyProperties_unHandledError_returnGeneralError() { when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenThrow(new RuntimeException()); Response response = buildGetPropertiesRequest().get(); @@ -266,14 +281,14 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void getPolicyProperties_wrongComponentType() { Response response = buildGetPropertiesRequest("unknownType").get(); - assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); //verifyZeroInteractions(businessLogic); } @Test public void getPolicyProperties() { List<PropertyDataDefinition> properties = getPropertiesList(); - when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.left(properties)); + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(properties); List<PropertyDataDefinition> policyProps = buildGetPropertiesRequest().get(new GenericType<List<PropertyDataDefinition>>() {}); assertThat(policyProps) .usingElementComparatorOnFields("uniqueId") @@ -283,7 +298,8 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void updatePolicyPropertiesSuccess() { List<PropertyDataDefinition> properties = getPropertiesList(); - when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.left(properties)); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), + any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(properties); List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(new GenericType<List<PropertyDataDefinition>>() {}); assertThat(policyProps) .usingElementComparatorOnFields("uniqueId") @@ -293,7 +309,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ @Test public void updatePolicyTargetsSuccess() { List<PolicyTargetDTO> targets = getTargetDTOList(); - when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(Either.left(new PolicyDefinition())); + when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(new PolicyDefinition()); Response policyTargets = buildUpdateTargetsRequest(ComponentTypeEnum.RESOURCE_PARAM_NAME, targets).invoke(); assertThat(policyTargets.getStatus()).isEqualTo(200); } @@ -302,7 +318,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ public void updatePolicyPropertiesFailure() { List<PropertyDataDefinition> properties = getPropertiesList(); ResponseFormat notFoundResponse = new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode()); - when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.right(notFoundResponse)); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenThrow(new ByResponseFormatComponentException(notFoundResponse)); Response policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(); assertEquals(HttpStatus.NOT_FOUND_404.getStatusCode(), policyProps.getStatus()); } @@ -338,7 +354,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ addGetPolicyValueToProperty(origProperty, policyDefinition); - when(businessLogic.deletePolicy(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(policyDefinition.getUniqueId()), eq(USER_ID), eq(true))).thenReturn(Either.left(policyDefinition)); + when(businessLogic.deletePolicy(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(policyDefinition.getUniqueId()), eq(USER_ID), eq(true))).thenReturn(policyDefinition); Response deleteResponse = buildDeletePolicyRequest(policyDefinition).invoke(); assertEquals(HttpStatus.OK_200.getStatusCode(), deleteResponse.getStatus()); @@ -470,7 +486,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ return componentInstInputsMap; } - + @Override protected ResourceConfig configure() { return super.configure() @@ -495,6 +511,7 @@ public class PolicyServletTest extends JerseySpringBaseTest{ componentsUtils = Mockito.mock(ComponentsUtils.class); servletUtils = Mockito.mock(ServletUtils.class); responseFormat = Mockito.mock(ResponseFormat.class); + roleAuthorizationHandler = Mockito.mock(RoleAuthorizationHandler.class); } private static class BaseBusinessLogicTest extends BaseBusinessLogic { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java index d1510c15b1..d9f00f4f36 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java @@ -28,6 +28,7 @@ import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; @@ -52,8 +53,10 @@ public class PolicyTypesEndpointTest extends JerseySpringBaseTest { protected ResourceConfig configure() { policyTypeBusinessLogic = mock(PolicyTypeBusinessLogic.class); componentUtils = mock(ComponentsUtils.class); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); return super.configure() - .register(new PolicyTypesEndpoint(policyTypeBusinessLogic)); + .register(new PolicyTypesEndpoint(userBusinessLogic, componentsUtils, policyTypeBusinessLogic)); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ProductServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ProductServletTest.java deleted file mode 100644 index 352c76a3f6..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ProductServletTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.user.UserBusinessLogic; - -public class ProductServletTest { - - private ProductServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ProductBusinessLogic productBusinessLogic = mock(ProductBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - - return new ProductServlet(userBusinessLogic, productBusinessLogic, componentsUtils); - } - - - @Test - public void testCreateProduct() throws Exception { - ProductServlet testSubject; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetProductById() throws Exception { - ProductServlet testSubject; - String productId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetServiceByNameAndVersion() throws Exception { - ProductServlet testSubject; - String productName = ""; - String productVersion = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testDeleteProduct() throws Exception { - ProductServlet testSubject; - String productId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUpdateProductMetadata() throws Exception { - ProductServlet testSubject; - String productId = ""; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testValidateServiceName() throws Exception { - ProductServlet testSubject; - String productName = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RepresentationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RepresentationUtilsTest.java index 8f520d7d89..3d10bb1199 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RepresentationUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RepresentationUtilsTest.java @@ -27,7 +27,9 @@ import org.openecomp.sdc.be.model.Operation; import java.util.HashMap; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class RepresentationUtilsTest { @@ -56,19 +58,6 @@ public class RepresentationUtilsTest { result = RepresentationUtils.toRepresentation(elementToRepresent); } - - - - @Test - public void testConvertJsonToArtifactDefinition() throws Exception { - String content = ""; - Class<ArtifactDefinition> clazz = null; - ArtifactDefinition result; - - // default test - result = RepresentationUtils.convertJsonToArtifactDefinition(content, clazz); - } - @Test public void checkIsEmptyFiltering() throws Exception { HashMap<String, Operation> op = new HashMap<>(); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RequirementsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RequirementsServletTest.java deleted file mode 100644 index 61f2b15e65..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/RequirementsServletTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.user.UserBusinessLogic; - -public class RequirementsServletTest { - - private RequirementsServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ComponentInstanceBusinessLogic componentInstanceBL = mock(ComponentInstanceBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - - return new RequirementsServlet(userBusinessLogic, componentsUtils); - } - - - @Test - public void testUpdateRequirement() throws Exception { - RequirementsServlet testSubject; - String resourceId = ""; - String requirementId = ""; - String requirementData = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServletTest.java deleted file mode 100644 index 02a16f86dc..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServletTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; - -import ch.qos.logback.classic.Logger; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.DownloadArtifactLogic; -import org.openecomp.sdc.be.resources.api.IResourceUploader; -import org.openecomp.sdc.be.user.UserBusinessLogic; - -public class ResourceArtifactDownloadServletTest { - - private ResourceArtifactDownloadServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - IResourceUploader resourceUploader = mock(IResourceUploader.class); - DownloadArtifactLogic downloadArtifactLogic = mock(DownloadArtifactLogic.class); - - return new ResourceArtifactDownloadServlet(userBusinessLogic, componentsUtils, - resourceUploader, downloadArtifactLogic); - } - - - @Test - public void testGetResourceArtifactByName() throws Exception { - ResourceArtifactDownloadServlet testSubject; - String resourceName = ""; - String resourceVersion = ""; - String artifactName = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetResourceArtifactMetadata() throws Exception { - ResourceArtifactDownloadServlet testSubject; - String resourceName = ""; - String resourceVersion = ""; - String artifactName = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetLogger() throws Exception { - ResourceArtifactDownloadServlet testSubject; - Logger result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java index 6344e6f72f..284cc3fb47 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java @@ -73,6 +73,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -137,13 +138,12 @@ public class ResourceServletTest extends JerseyTest { user = new User(); user.setUserId(userId); user.setRole(Role.ADMIN.name()); - Either<User, ActionStatus> eitherUser = Either.left(user); - when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(userAdmin.getUser(userId)).thenReturn(user); when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); ImmutablePair<Resource, ActionStatus> pair = new ImmutablePair<>(new Resource(), ActionStatus.OK); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> ret = Either.left(pair); - when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(ret); + when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(pair); + when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic); } @@ -1001,7 +1001,7 @@ public class ResourceServletTest extends JerseyTest { ret.setVendorRelease("VendorRelease"); ret.setContactId("AT1234"); ret.setIcon("router"); - ret.setTags(Arrays.asList(new String[] { "ciMyCompute" })); + ret.setTags(Collections.singletonList("ciMyCompute")); ret.setPayloadData( "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); return ret; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java deleted file mode 100644 index efe8043ff5..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import com.google.gson.Gson; -import org.glassfish.hk2.utilities.binding.AbstractBinder; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.media.multipart.FormDataBodyPart; -import org.glassfish.jersey.media.multipart.FormDataMultiPart; -import org.glassfish.jersey.media.multipart.MultiPart; -import org.glassfish.jersey.media.multipart.MultiPartFeature; -import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.test.JerseyTest; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.sdc.be.auditing.impl.AuditingManager; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.SpringConfig; -import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.UploadResourceInfo; -import org.openecomp.sdc.be.resources.api.IResourceUploader; -import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -public class ResourceUploadServletTest extends JerseyTest { - private static final Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class); - final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - final HttpSession session = Mockito.mock(HttpSession.class); - final ServletContext servletContext = Mockito.mock(ServletContext.class); - final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class); - final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class); - - Gson gson = new Gson(); - - public void zipDirectory() { - - } - - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader); - when(iResourceUploader.saveArtifact((ESArtifactData) any(), eq(true))).thenReturn(ResourceUploadStatus.OK); - when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager); - } - - @Override - protected Application configure() { - - ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); - return new ResourceConfig(ResourceUploadServlet.class) - .register(MultiPartFeature.class) - .register(new AbstractBinder() { - - @Override - protected void configure() { - // The below code was cut-pasted to here from setup() because - // due to it now has - // to be executed during servlet initialization - bind(request).to(HttpServletRequest.class); - when(request.getSession()).thenReturn(session); - when(session.getServletContext()).thenReturn(servletContext); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { - - when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); - - } - - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - } - }) - .property("contextConfig", context); - - } - - @Override - protected void configureClient(ClientConfig config) { - config.register(MultiPartFeature.class); - } - - @Test - public void testMultipart() { - FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip")); - List<String> tags = new ArrayList<>(); - tags.add("tag1"); - tags.add("tag2"); - UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null); - - FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE); - MultiPart multipartEntity = new FormDataMultiPart(); - multipartEntity.bodyPart(filePart); - multipartEntity.bodyPart(metadataPart); - - Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); - log.debug("{}", response); - } - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourcesServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourcesServletTest.java index 42103b0740..239e7232af 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourcesServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourcesServletTest.java @@ -20,17 +20,10 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; - -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - +import com.google.common.base.Equivalence.Wrapper; +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -41,9 +34,12 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.common.base.Equivalence.Wrapper; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.mockito.Mockito.mock; public class ResourcesServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ServiceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ServiceServletTest.java deleted file mode 100644 index c2a8afec85..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ServiceServletTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import static org.mockito.Mockito.mock; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.*; -import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.exception.ResponseFormat; - -import com.google.common.base.Equivalence.Wrapper; -import com.google.common.util.concurrent.Service; - -import fj.data.Either; - -public class ServiceServletTest { - - private ServiceServlet createTestSubject() { - UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); - ComponentInstanceBusinessLogic componentInstanceBL = mock(ComponentInstanceBusinessLogic.class); - ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - ServletUtils servletUtils = mock(ServletUtils.class); - ResourceImportManager resourceImportManager = mock(ResourceImportManager.class); - ServiceBusinessLogic serviceBusinessLogic = mock(ServiceBusinessLogic.class); - ResourceBusinessLogic resourceBusinessLogic = mock(ResourceBusinessLogic.class); - - return new ServiceServlet(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, - resourceImportManager, serviceBusinessLogic, resourceBusinessLogic); - } - - - @Test - public void testCreateService() throws Exception { - ServiceServlet testSubject; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testParseToService() throws Exception { - ServiceServlet testSubject; - String serviceJson = ""; - User user = null; - Either<Service, ResponseFormat> result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testValidateServiceName() throws Exception { - ServiceServlet testSubject; - String serviceName = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testGetComponentAuditRecords() throws Exception { - ServiceServlet testSubject; - String componentType = ""; - String componentUniqueId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testFillUUIDAndVersion() throws Exception { - ServiceServlet testSubject;Wrapper<Response> responseWrapper = null; - Wrapper<String> uuidWrapper = null; - Wrapper<String> versionWrapper = null; - User user = null; - ComponentTypeEnum componentTypeEnum = null; - String componentUniqueId = ""; - ServletContext context = null; - - - // default test - } - - - @Test - public void testDeleteService() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testDeleteServiceByNameAndVersion() throws Exception { - ServiceServlet testSubject; - String serviceName = ""; - String version = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testUpdateServiceMetadata() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testUpdateGroupInstancePropertyValues() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - String componentInstanceId = ""; - String groupInstanceId = ""; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testGetServiceById() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testGetServiceByNameAndVersion() throws Exception { - ServiceServlet testSubject; - String serviceName = ""; - String serviceVersion = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testUpdateServiceDistributionState() throws Exception { - ServiceServlet testSubject; - LifecycleChangeInfoWithAction jsonChangeInfo = null; - String serviceId = ""; - String state = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testActivateDistribution() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - String env = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testMarkDistributionAsDeployed() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - String did = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testTempUrlToBeDeleted() throws Exception { - ServiceServlet testSubject; - String serviceId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testDownloadServiceArtifact() throws Exception { - ServiceServlet testSubject; - String artifactName = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - - } - - - @Test - public void testExecuteCommand() throws Exception { - ServiceServlet testSubject; - String artifactName = ""; - Either<byte[], ResponseFormat> result; - - // default test - testSubject = createTestSubject(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesFetchServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesFetchServletTest.java index f27c886e68..2305cd3059 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesFetchServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesFetchServletTest.java @@ -20,17 +20,23 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.mock; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.user.UserBusinessLogic; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.*; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.user.UserBusinessLogic; +import static org.mockito.Mockito.mock; public class TypesFetchServletTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java index 39dee258cb..825b4d8883 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java @@ -49,6 +49,7 @@ import org.openecomp.sdc.be.model.operations.impl.CommonTypeOperations; import org.openecomp.sdc.be.model.operations.impl.OperationUtils; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.resources.data.AnnotationTypeData; +import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; @@ -68,7 +69,9 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class TypesUploadEndpointTest extends JerseySpringBaseTest { @@ -86,7 +89,9 @@ public class TypesUploadEndpointTest extends JerseySpringBaseTest { @Bean TypesUploadEndpoint typesUploadEndpoint() { - return new TypesUploadEndpoint(commonImportManager(), annotationTypeOperations(), accessValidations); + UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class); + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + return new TypesUploadEndpoint(userBusinessLogic, componentsUtils, commonImportManager(), annotationTypeOperations(), accessValidations); } @Bean diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java index 92652f59d0..a247bd4b35 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java @@ -65,7 +65,6 @@ import java.util.List; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; public class TypesUploadServletTest extends JerseyTest { @@ -94,8 +93,7 @@ public class TypesUploadServletTest extends JerseyTest { User user = new User(); user.setUserId(userId); user.setRole(Role.ADMIN.name()); - Either<User, ActionStatus> eitherUser = Either.left(user); - when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(userAdmin.getUser(userId)).thenReturn(user); when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201); when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); @@ -112,7 +110,7 @@ public class TypesUploadServletTest extends JerseyTest { Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); - assertEquals(HttpStatus.CREATED_201, response.getStatus()); + assertEquals(response.getStatus(), HttpStatus.CREATED_201); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java deleted file mode 100644 index af08992252..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import com.google.gson.Gson; -import fj.data.Either; -import org.glassfish.hk2.utilities.binding.AbstractBinder; -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.test.JerseyTest; -import org.junit.Before; -import org.junit.BeforeClass; -import org.openecomp.sdc.be.auditing.impl.AuditingManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.utils.UserStatusEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.api.UserRoleEnum; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.http.HttpStatus; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.core.Application; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class UserAdminServletTest extends JerseyTest { - - final static HttpServletRequest request = mock(HttpServletRequest.class); - final static HttpSession session = mock(HttpSession.class); - final static ServletContext servletContext = mock(ServletContext.class); - final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class); - final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class); - final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class); - final static AuditingManager auditingManager = mock(AuditingManager.class); - final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - final static ResponseFormat okResponseFormat = mock(ResponseFormat.class); - - final static String ADMIN_ATT_UID = "jh0003"; - Gson gson = new Gson(); - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - - when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager); - when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils); - when(componentsUtils.getAuditingManager()).thenReturn(auditingManager); - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat); - when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value()); - - } - - @Before - public void beforeTest() { - reset(userAdminManager); - doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false); - - reset(request); - when(request.getSession()).thenReturn(session); - when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID); - } - - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class); - - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } - - private static Either<User, ActionStatus> buildEitherUser(String userId, boolean isActive) { - User user = new User(); - user.setUserId(userId); - user.setRole(UserRoleEnum.ADMIN.getName()); - if (!isActive) { - user.setStatus(UserStatusEnum.INACTIVE); - } - return Either.left(user); - } - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserEndpointTest.java new file mode 100644 index 0000000000..fc18459608 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserEndpointTest.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import fj.data.Either; +import org.eclipse.jetty.http.HttpStatus; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.janusgraph.graphdb.types.system.EmptyVertex; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.facade.operations.UserOperation; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.be.user.UserBusinessLogicExt; +import org.openecomp.sdc.common.api.Constants; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.dao.utils.UserStatusEnum.ACTIVE; +import static org.openecomp.sdc.be.dao.utils.UserStatusEnum.INACTIVE; +import static org.openecomp.sdc.be.user.Role.ADMIN; +import static org.openecomp.sdc.be.user.Role.DESIGNER; + +public class UserEndpointTest extends JerseySpringBaseTest { + + static final String USER_ID = "jh0003"; + static final String NEW_USER_ID = "ab0001"; + static final String MODIFIER_ID = "admin1"; + + private static ComponentsUtils componentUtils; + private static JanusGraphGenericDao janusGraphGenericDao; + private static ToscaOperationFacade toscaOperationFacade; + private static LifecycleBusinessLogic lifecycleBusinessLogic; + private static UserOperation facadeUserOperation; + + + private UserData userData = new UserData(); + private UserData modifierData = new UserData(); + + @org.springframework.context.annotation.Configuration + @Import(BaseTestConfig.class) + static class UserTestConfig { + + @Bean + UserAdminServlet userEndpoint() { + ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + return new UserAdminServlet(userBusinessLogic(), componentsUtils, userBusinessLogicExt()); + } + + @Bean + UserBusinessLogic userBusinessLogic() { + return new UserBusinessLogic(userAdminOperation(), componentUtils, facadeUserOperation); + } + + @Bean + UserBusinessLogicExt userBusinessLogicExt() { + return new UserBusinessLogicExt(userBusinessLogic(), userAdminOperation(), lifecycleBusinessLogic, componentUtils); + } + + @Bean + UserAdminOperation userAdminOperation() { + return new UserAdminOperation(janusGraphGenericDao, toscaOperationFacade); + } + } + + @BeforeClass + public static void initClass() { + janusGraphGenericDao = mock(JanusGraphGenericDao.class); + componentUtils = mock(ComponentsUtils.class); + toscaOperationFacade = mock(ToscaOperationFacade.class); + lifecycleBusinessLogic = mock(LifecycleBusinessLogic.class); + facadeUserOperation = mock(UserOperation.class); + } + + @Before + public void setup() { + setUserProperties(userData, USER_ID, DESIGNER, ACTIVE); + setUserProperties(modifierData, MODIFIER_ID, ADMIN, ACTIVE); + Either<UserData, JanusGraphOperationStatus> janusGraphValidUser = Either.left(userData); + Either<UserData, JanusGraphOperationStatus> janusGraphValidModifier = Either.left(modifierData); + when(janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), USER_ID, UserData.class)) + .thenReturn(janusGraphValidUser); + when(janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), MODIFIER_ID, UserData.class)) + .thenReturn(janusGraphValidModifier); + when(janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), NEW_USER_ID, UserData.class)) + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + } + + private void setUserProperties(UserData user, String userId, Role role, UserStatusEnum statusEnum) { + user.setUserId(userId); + user.setRole(role.name()); + user.setStatus(statusEnum.name()); + } + + @Override + protected void configureClient(ClientConfig config) { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + config.register(jacksonJsonProvider); + config.register(MultiPartFeature.class); + } + + @Override + protected ResourceConfig configure() { + return super.configure(UserEndpointTest.UserTestConfig.class) + .register(UserAdminServlet.class) + .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING"); + } + + @Test + public void getUser_success() { + User user = target().path("/v1/user/" + USER_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .get(User.class); + assertThat(user.getUserId()).isEqualTo(USER_ID); + } + + @Test + public void getUserRole_success() { + String result = target().path("/v1/user/" + USER_ID + "/role") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, MODIFIER_ID) + .get(String.class); + assertThat(result).isEqualTo("{ \"role\" : \"" + DESIGNER.name() + "\" }"); + } + + @Test + public void updateUserRole_success() { + UserAdminServlet.UserRole role = new UserAdminServlet.UserRole(); + role.setRole(ADMIN); + EmptyVertex emptyVertex = new EmptyVertex(); + UserData updatedUser = new UserData(); + setUserProperties(updatedUser, USER_ID, ADMIN, ACTIVE); + when(janusGraphGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), USER_ID)) + .thenReturn(Either.left(emptyVertex)); + when(janusGraphGenericDao.getOutgoingEdgesByCriteria(eq(emptyVertex), eq(GraphEdgeLabels.STATE), any())) + .thenReturn(Either.left(new ArrayList<>())); + when(janusGraphGenericDao.updateNode(eq(updatedUser), eq(UserData.class))).thenReturn(Either.left(updatedUser)); + User user = target().path("/v1/user/" + USER_ID + "/role") + .request(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, MODIFIER_ID) + .post(Entity.entity(role, MediaType.APPLICATION_JSON),User.class); + assertThat(user.getRole()).isEqualTo(ADMIN.name()); + } + + @Test + public void createUser_success() { + User newUser = new User(); + newUser.setUserId(NEW_USER_ID); + UserData updatedUser = new UserData(); + setUserProperties(updatedUser, NEW_USER_ID, DESIGNER, ACTIVE); + //when(janusGraphGenericDao.updateNode(any(), eq(UserData.class))).thenReturn(Either.left(updatedUser)); + when(janusGraphGenericDao.createNode(any(), eq(UserData.class))).thenReturn(Either.left(updatedUser)); + Response response = target().path("/v1/user") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, MODIFIER_ID) + .post(Entity.entity(newUser, MediaType.APPLICATION_JSON),Response.class); + assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED_201); + User createdUser = response.readEntity(User.class); + assertThat(createdUser.getUserId()).isEqualTo(NEW_USER_ID); + assertThat(createdUser.getStatus()).isEqualTo(ACTIVE); + } + + @Test + public void authorizeUser_success() { + when(janusGraphGenericDao.updateNode(any(), eq(UserData.class))).thenReturn(Either.left(userData)); + User user = target().path("/v1/user/authorize") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .header("HTTP_CSP_FIRSTNAME", "Jimmy") + .header("HTTP_CSP_LASTNAME", "Hendrix") + .header("HTTP_CSP_EMAIL", "admin@sdc.com") + .get(User.class); + assertThat(user.getUserId()).isEqualTo(USER_ID); + } + + @Test + public void deactivateUser_success() { + EmptyVertex emptyVertex = new EmptyVertex(); + UserData updatedUser = new UserData(); + setUserProperties(updatedUser, USER_ID, DESIGNER, INACTIVE); + when(janusGraphGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), USER_ID)) + .thenReturn(Either.left(emptyVertex)); + when(janusGraphGenericDao.getOutgoingEdgesByCriteria(eq(emptyVertex), eq(GraphEdgeLabels.STATE), any())) + .thenReturn(Either.left(new ArrayList<>())); + when(janusGraphGenericDao.updateNode(eq(updatedUser), eq(UserData.class))).thenReturn(Either.left(updatedUser)); + User user = target().path("/v1/user/" + USER_ID) + .request(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, MODIFIER_ID) + .delete(User.class); + assertThat(user.getUserId()).isEqualTo(USER_ID); + } + +} |