Fix locally failing TCs in catalog-be
Migrate to Junit 5 TCs that extends JerseyTest
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Change-Id: I4c81e70836ee5e634291d74cd1773d221dce3702
Issue-ID: SDC-3377
Signed-off-by: aribeiro <anderson.ribeiro@est.tech>
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java
index 2cc9426..a442481 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java
@@ -22,6 +22,8 @@
import com.att.nsa.mr.client.MRBatchingPublisher;
import com.fasterxml.jackson.databind.ObjectMapper;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
import org.openecomp.sdc.be.catalog.api.IMessageQueueHandlerProducer;
import org.openecomp.sdc.be.catalog.api.IStatus;
import org.openecomp.sdc.be.catalog.api.ITypeMessage;
@@ -29,112 +31,108 @@
import org.openecomp.sdc.be.components.distribution.engine.DmaapClientFactory;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DmaapProducerConfiguration;
+import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.enums.StatusCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
@Component
public class DmaapProducer implements IMessageQueueHandlerProducer {
- private static final Logger LOG = Logger.getLogger(DmaapProducer.class.getName());
- private static final Logger metricLog = Logger.getLogger(DmaapProducer.class.getName());
- @Autowired
- private DmaapClientFactory dmaapClientFactory;
- private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
- private MRBatchingPublisher publisher;
- @Autowired
- private DmaapProducerHealth dmaapHealth;
+ private static final Logger LOG = Logger.getLogger(DmaapProducer.class.getName());
+ private final DmaapClientFactory dmaapClientFactory;
+ private final DmaapProducerHealth dmaapHealth;
+ private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
+ private MRBatchingPublisher publisher;
- public MRBatchingPublisher getPublisher() {
- return publisher;
- }
+ public DmaapProducer(final DmaapClientFactory dmaapClientFactory,
+ final DmaapProducerHealth dmaapHealth) {
+ this.dmaapClientFactory = dmaapClientFactory;
+ this.dmaapHealth = dmaapHealth;
+ }
- @Override
- public IStatus pushMessage(ITypeMessage message) {
- try {
- DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration()
- .getDmaapProducerConfiguration();
- if (!producerConfiguration.getActive()) {
- LOG.info(
- "[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
- dmaapHealth.report(false);
- return IStatus.getServiceDisabled();
- }
- if (publisher == null) {
- IStatus initStatus = init();
- if (initStatus.getResultStatus() != ResultStatusEnum.SUCCESS) {
+ @Override
+ public IStatus pushMessage(ITypeMessage message) {
+ try {
+ DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration()
+ .getDmaapProducerConfiguration();
+ if (!producerConfiguration.getActive()) {
+ LOG.info(
+ "[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
+ dmaapHealth.report(false);
+ return IStatus.getServiceDisabled();
+ }
+ if (publisher == null) {
+ IStatus initStatus = init();
+ if (initStatus.getResultStatus() != ResultStatusEnum.SUCCESS) {
- return initStatus;
- }
- }
- ObjectMapper mapper = new ObjectMapper();
- String jsonInString = mapper.writeValueAsString(message);
- if (publisher != null) {
- LOG.info("before send message . response {}", jsonInString);
+ return initStatus;
+ }
+ }
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonInString = mapper.writeValueAsString(message);
+ if (publisher != null) {
+ LOG.info("before send message . response {}", jsonInString);
- LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(), message.toString());
+ LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(),
+ message.toString());
- int pendingMsg = publisher.send(jsonInString);
- LOG.info("sent message . response {}", pendingMsg);
- LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer", StatusCode.COMPLETE.getStatusCode(), "DmaapProducer-pushMessage",message.toString(), pendingMsg );
+ int pendingMsg = publisher.send(jsonInString);
+ LOG.info("sent message . response {}", pendingMsg);
+ LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer",
+ StatusCode.COMPLETE.getStatusCode(), "DmaapProducer-pushMessage", message.toString(), pendingMsg);
- }
+ }
-
-
- dmaapHealth.report(true);
- } catch (Exception e) {
- LOG.error("Failed to send message . Exception {}", e.getMessage());
- return IStatus.getFailStatus();
- }
+ dmaapHealth.report(true);
+ } catch (Exception e) {
+ LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "Failed to send message . Exception {}", e.getMessage());
+ return IStatus.getFailStatus();
+ }
- return IStatus.getSuccessStatus();
- }
+ return IStatus.getSuccessStatus();
+ }
- @PostConstruct
- @Override
- public IStatus init() {
- LOG.debug("MessageQueueHandlerProducer:: Start initializing");
- DmaapProducerConfiguration configuration = configurationManager.getConfiguration()
- .getDmaapProducerConfiguration();
- if (configuration.getActive()) {
- try {
- publisher = dmaapClientFactory.createProducer(configuration);
- if (publisher == null) {
- LOG.error("Failed to connect to topic ");
- dmaapHealth.report(false);
- return IStatus.getFailStatus();
- }
+ @PostConstruct
+ @Override
+ public IStatus init() {
+ LOG.debug("MessageQueueHandlerProducer:: Start initializing");
+ DmaapProducerConfiguration configuration = configurationManager.getConfiguration()
+ .getDmaapProducerConfiguration();
+ if (configuration.getActive()) {
+ try {
+ publisher = dmaapClientFactory.createProducer(configuration);
+ if (publisher == null) {
+ LOG.error("Failed to connect to topic ");
+ dmaapHealth.report(false);
+ return IStatus.getFailStatus();
+ }
- } catch (Exception e) {
- LOG.error("Failed to connect to topic . Exeption {}", e.getMessage());
- dmaapHealth.report(false);
- return IStatus.getFailStatus();
- }
- dmaapHealth.report(true);
- return IStatus.getSuccessStatus();
- }
- LOG.info("[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
- dmaapHealth.report(false);
- return IStatus.getServiceDisabled();
- }
+ } catch (Exception e) {
+ LOG.error("Failed to connect to topic . Exeption {}", e.getMessage());
+ dmaapHealth.report(false);
+ return IStatus.getFailStatus();
+ }
+ dmaapHealth.report(true);
+ return IStatus.getSuccessStatus();
+ }
+ LOG.info("[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
+ dmaapHealth.report(false);
+ return IStatus.getServiceDisabled();
+ }
- @PreDestroy
- public void shutdown() {
- LOG.debug("DmaapProducer::shutdown...");
- try {
- if (publisher != null) {
- publisher.close();
- }
- } catch (Exception e) {
- LOG.error("Failed to close messageQ . Exeption {}", e.getMessage());
+ @PreDestroy
+ public void shutdown() {
+ LOG.debug("DmaapProducer::shutdown...");
+ try {
+ if (publisher != null) {
+ publisher.close();
+ }
+ } catch (Exception e) {
+ LOG.error("Failed to close messageQ . Exeption {}", e.getMessage());
- }
+ }
- }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
index dfc9166..9eb9c34 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
@@ -1758,14 +1758,12 @@
ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value();
- Either<String, ResponseFormat> result = null;
String did = ThreadLocalsHolder.getUuid();
Service service = activationRequestInformation.getServiceToActivate();
- result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
- return result;
+ return buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
}
- public Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
+ private Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
String envName = getEnvNameFromConfiguration();
INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext);
ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier);
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerTest.java
index cd0c321..be84780 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerTest.java
@@ -20,14 +20,25 @@
package org.openecomp.sdc.be.catalog.impl;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.openecomp.sdc.be.catalog.enums.ResultStatusEnum.FAIL;
+import static org.openecomp.sdc.be.catalog.enums.ResultStatusEnum.SERVICE_DISABLED;
+
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.catalog.api.IComponentMessage;
import org.openecomp.sdc.be.catalog.api.IStatus;
import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
+import org.openecomp.sdc.be.components.distribution.engine.DmaapClientFactory;
+import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DmaapProducerConfiguration;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
@@ -35,41 +46,42 @@
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+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.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.fail;
-import static org.openecomp.sdc.be.catalog.enums.ResultStatusEnum.FAIL;
-import static org.openecomp.sdc.be.catalog.enums.ResultStatusEnum.SERVICE_DISABLED;
-import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
-
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
-public class DmaapProducerTest {
- private static final Logger LOG = LoggerFactory.getLogger(DmaapProducer.class);
+class DmaapProducerTest {
- @Autowired
- ConfigurationManager configurationManager;
-
- @Autowired
+ private static final Logger LOG = LoggerFactory.getLogger(DmaapProducerTest.class);
+
+ private ConfigurationManager configurationManager;
private DmaapProducer dmaapProducer;
-
+ private DmaapClientFactory dmaapClientFactory;
- //actually sends the message
-
+ @BeforeEach
+ public void setup() {
+ final ConfigurationSource configurationSource = new FSConfigurationSource(
+ ExternalConfiguration.getChangeListener(),
+ "src/test/resources/config/catalog-be");
+ configurationManager = new ConfigurationManager(configurationSource);
+ final Configuration configuration = new Configuration();
+ final DmaapProducerConfiguration dmaapProducerConfiguration = new DmaapProducerConfiguration();
+ dmaapProducerConfiguration.setActive(true);
+ configuration.setJanusGraphInMemoryGraph(true);
+ configurationManager.setConfiguration(configuration);
+ configurationManager.getConfiguration().setDmaapProducerConfiguration(dmaapProducerConfiguration);
+ ExternalConfiguration.setAppName("catalog-be");
+ dmaapProducer = new DmaapProducer(mock(DmaapClientFactory.class), mock(DmaapProducerHealth.class));
+ }
@Test
- public void pushComponentMessageTest() {
+ void pushComponentMessageTest() {
boolean oldVal = isActive();
-
- Resource resource = new Resource();
+ final Resource resource = new Resource();
resource.setUniqueId("mockUniqueId");
resource.setUUID("mockNameUUID");
resource.setResourceType(ResourceTypeEnum.VF);
@@ -84,56 +96,51 @@
resource.setHighestVersion(true);
resource.setArchived(false);
- List<CategoryDefinition> categories = new ArrayList<>();
- CategoryDefinition cat = new CategoryDefinition();
- cat.setName("mockCategory");
- cat.setNormalizedName("mockCategory");
- cat.setUniqueId("uniqueId");
- SubCategoryDefinition subcat = new SubCategoryDefinition();
- subcat.setName("mockSubCategory");
- subcat.setNormalizedName("mockSubCategory");
- subcat.setUniqueId("mockSubCategoryUniqueId");
- cat.addSubCategory(subcat);
- categories.add(cat);
+ final List<CategoryDefinition> categories = new ArrayList<>();
+ final CategoryDefinition categoryDefinition = new CategoryDefinition();
+ categoryDefinition.setName("mockCategory");
+ categoryDefinition.setNormalizedName("mockCategory");
+ categoryDefinition.setUniqueId("uniqueId");
+ final SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition();
+ subCategoryDefinition.setName("mockSubCategory");
+ subCategoryDefinition.setNormalizedName("mockSubCategory");
+ subCategoryDefinition.setUniqueId("mockSubCategoryUniqueId");
+ categoryDefinition.addSubCategory(subCategoryDefinition);
+ categories.add(categoryDefinition);
resource.setCategories(categories);
- IComponentMessage message = new ComponentMessage(resource, ChangeTypeEnum.LIFECYCLE, new CatalogUpdateTimestamp(123, 1234));
- ObjectMapper mapper = new ObjectMapper();
+ final IComponentMessage message = new ComponentMessage(resource, ChangeTypeEnum.LIFECYCLE,
+ new CatalogUpdateTimestamp(123, 1234));
try {
- String jsonInString = mapper.writeValueAsString(message);
- LOG.info("[DmaapProducer] pushing message =>{}",jsonInString);
- //push msg by configuration => will send the message if configuration enables
- //IStatus status = dmaapProducer.pushComponentMessage(message);
+ LOG.info("[DmaapProducer] pushing message =>{}", new ObjectMapper().writeValueAsString(message));
+ //push message by configuration => will send the message if configuration enables
//will not test network connectivity to avoid build server automation fail
-
toggleInactive();
IStatus status = dmaapProducer.pushMessage(message);
assertThat(status.getResultStatus()).isEqualTo(SERVICE_DISABLED);
-
toggleActive();
dmaapProducer.shutdown();
status = dmaapProducer.pushMessage(message);
assertThat(status.getResultStatus()).isEqualTo(FAIL);
-
- } catch (JsonProcessingException e) {
+ } catch (final JsonProcessingException e) {
fail("'JsonProcessingException' detected!", e);
- } catch (Exception e) {
+ } catch (final Exception e) {
fail("Unknown exception detected", e);
- }finally {
+ } finally {
configurationManager.getConfiguration().getDmaapProducerConfiguration().setActive(oldVal);
}
}
- private boolean isActive(){
+ private boolean isActive() {
return configurationManager.getConfiguration().getDmaapProducerConfiguration().getActive();
}
- private void toggleInactive(){
+ private void toggleInactive() {
configurationManager.getConfiguration().getDmaapProducerConfiguration().setActive(false);
}
- private void toggleActive(){
+ private void toggleActive() {
configurationManager.getConfiguration().getDmaapProducerConfiguration().setActive(true);
}
-}
\ No newline at end of file
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java
index 68fa486..9b6a26d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java
@@ -28,8 +28,8 @@
import static org.mockito.Mockito.when;
import fj.data.Either;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
@@ -57,10 +57,7 @@
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.exception.ResponseFormat;
-/**
- * Created by chaya on 10/26/2017.
- */
-public class ServiceDistributionBLTest extends ComponentBusinessLogicMock {
+class ServiceDistributionBLTest extends ComponentBusinessLogicMock {
private final ServiceDistributionValidation serviceDistributionValidation = Mockito.mock(ServiceDistributionValidation.class);
private final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class);
@@ -70,9 +67,8 @@
private final ForwardingPathValidator forwardingPathValidator = Mockito.mock(ForwardingPathValidator.class);
private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
-
@InjectMocks
- ServiceBusinessLogic bl = new ServiceBusinessLogic(elementDao, groupOperation, groupInstanceOperation,
+ private final ServiceBusinessLogic bl = new ServiceBusinessLogic(elementDao, groupOperation, groupInstanceOperation,
groupTypeOperation, groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation,
artifactsBusinessLogic, distributionEngine, componentInstanceBusinessLogic,
serviceDistributionValidation, forwardingPathValidator, uiComponentDataConverter,
@@ -80,8 +76,6 @@
componentNameValidator, componentTagsValidator, componentValidator, componentIconValidator,
componentProjectCodeValidator, componentDescriptionValidator);
- ComponentsUtils componentsUtils;
-
private Service serviceToActivate;
private ActivationRequestInformation activationRequestInformation;
private String WORKLOAD_CONTEXT = "vnfContext";
@@ -89,46 +83,42 @@
private String DID = "distributionId";
private User modifier;
-
- public ServiceDistributionBLTest() {
- }
-
- @Before
+ @BeforeEach
public void setup() {
ExternalConfiguration.setAppName("catalog-be");
MockitoAnnotations.initMocks(this);
- componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ final ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
bl.setComponentsUtils(componentsUtils);
serviceToActivate = new Service();
serviceToActivate.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
activationRequestInformation = new ActivationRequestInformation(serviceToActivate, WORKLOAD_CONTEXT, TENANT);
when(toscaOperationFacade.getToscaElement(anyString(), any(ComponentParametersView.class)))
- .thenReturn(Either.left(serviceToActivate));
+ .thenReturn(Either.left(serviceToActivate));
when(distributionEngine.buildServiceForDistribution(any(Service.class), anyString(), anyString()))
- .thenReturn(new NotificationDataImpl());
+ .thenReturn(new NotificationDataImpl());
modifier = new User();
modifier.setUserId("uid");
modifier.setFirstName("user");
}
@Test
- public void testActivateServiceOnTenantValidationFails() {
+ void testActivateServiceOnTenantValidationFails() {
int VALIDATION_FAIL_STATUS = 666;
when(serviceDistributionValidation.validateActivateServiceRequest
- (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class)))
- .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS)));
+ (anyString(), anyString(), any(User.class), any(ServiceDistributionReqInfo.class)))
+ .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS)));
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isRight());
assertEquals((int) stringResponseFormatEither.right().value().getStatus(), VALIDATION_FAIL_STATUS);
}
//TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
- @Test
- public void testDistributionAuthenticationFails() {
+ @Test()
+ void testDistributionAuthenticationFails() {
mockAllMethodsUntilDENotification();
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),any(User.class)))
- .thenReturn(ActionStatus.AUTHENTICATION_ERROR);
+ when(distributionEngine.notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.AUTHENTICATION_ERROR);
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isRight());
assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
@@ -136,11 +126,11 @@
}
//TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
- @Test
- public void testDistributionUnknownHostFails() {
+ @Test()
+ void testDistributionUnknownHostFails() {
mockAllMethodsUntilDENotification();
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
- .thenReturn(ActionStatus.UNKNOWN_HOST);
+ when(distributionEngine.notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.UNKNOWN_HOST);
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isRight());
assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
@@ -148,11 +138,11 @@
}
//TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
- @Test
- public void testDistributionConnectionErrorFails() {
+ @Test()
+ void testDistributionConnectionErrorFails() {
mockAllMethodsUntilDENotification();
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
- .thenReturn(ActionStatus.CONNNECTION_ERROR);
+ when(distributionEngine.notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.CONNNECTION_ERROR);
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isRight());
assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
@@ -160,11 +150,22 @@
}
//TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
- @Test
- public void testDistributionObjectNotFoundFails() {
+ @Test()
+ void testDistributionObjectNotFoundFails() {
mockAllMethodsUntilDENotification();
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
- .thenReturn(ActionStatus.OBJECT_NOT_FOUND);
+ when(distributionEngine.notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.OBJECT_NOT_FOUND);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
+ assertEquals("SVC4676", stringResponseFormatEither.right().value().getMessageId());
+ }
+
+ @Test()
+ void testDistributionGeneralFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isRight());
assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
@@ -172,22 +173,12 @@
}
@Test
- public void testDistributionGeneralFails() {
- mockAllMethodsUntilDENotification();
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(), any(User.class)))
- .thenReturn(ActionStatus.GENERAL_ERROR);
- Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
- assertTrue(stringResponseFormatEither.isRight());
- assertEquals(502, (int) stringResponseFormatEither.right().value().getStatus());
- assertEquals("SVC4676", stringResponseFormatEither.right().value().getMessageId());
- }
-
- @Test
- public void testDistributionOk() {
+ void testDistributionOk() {
mockAllMethodsUntilDENotification();
ThreadLocalsHolder.setUuid(DID);
- when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(), anyString(), any(User.class)))
- .thenReturn(ActionStatus.OK);
+ when(distributionEngine
+ .notifyService(anyString(), any(Service.class), any(INotificationData.class), anyString(), anyString(), any(User.class)))
+ .thenReturn(ActionStatus.OK);
Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
assertTrue(stringResponseFormatEither.isLeft());
assertEquals(stringResponseFormatEither.left().value(), DID);
@@ -195,8 +186,8 @@
private void mockAllMethodsUntilDENotification() {
when(serviceDistributionValidation.validateActivateServiceRequest
- (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class)))
- .thenReturn(Either.left(activationRequestInformation));
+ (anyString(), anyString(), any(User.class), any(ServiceDistributionReqInfo.class)))
+ .thenReturn(Either.left(activationRequestInformation));
when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java
index f331e07..6239d33 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogicTest.java
@@ -21,16 +21,22 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+
import fj.data.Either;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -42,223 +48,214 @@
import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
import org.openecomp.sdc.be.resources.data.ConsumerData;
import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.impl.ExternalConfiguration;
-import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.HashMap;
-import java.util.Map;
+class ConsumerBusinessLogicTest extends BaseBusinessLogicMock {
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
+ private User user;
+ private ConsumerDefinition consumer;
+ private ConsumerDataDefinition consumerDataDefinition;
-public class ConsumerBusinessLogicTest extends BaseBusinessLogicMock {
+ @InjectMocks
+ private ConsumerBusinessLogic consumerBusinessLogic;
- private User user;
- private ConsumerDefinition consumer;
- private ConsumerDataDefinition consumerDataDefinition;
+ @Mock
+ private ComponentsUtils componentsUtils;
- @InjectMocks
- private ConsumerBusinessLogic consumerBusinessLogic;
+ @Mock
+ private UserBusinessLogic UserBusinessLogic;
- @Mock
- private ComponentsUtils componentsUtils;
+ @Mock
+ private IGraphLockOperation iGraphLockOperation;
- @Mock
- private UserBusinessLogic UserBusinessLogic;
+ @Mock
+ private ConsumerOperation consumerOperation;
- @Mock
- private IGraphLockOperation iGraphLockOperation;
+ @Mock
+ private ConsumerData consumerData;
- @Mock
- private ConsumerOperation consumerOperation;
+ @BeforeEach
+ public void setUp() {
+ consumerBusinessLogic = new ConsumerBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
+ interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ consumerDataDefinition = new ConsumerDataDefinition();
+ consumer = new ConsumerDefinition();
+ MockitoAnnotations.initMocks(this);
+ user = new User("Stan", "Lee", "stan.lee",
+ "stan.lee@marvel.com", "ADMIN", 1542024000L);
+ }
- @Mock
- private ConsumerData consumerData;
+ @Test
+ void testCreateConsumer_givenMissingUser_thenReturnsError() {
+ User user = new User();
+ ConsumerDefinition consumerDefinition = new ConsumerDefinition();
+ Mockito.when(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION))
+ .thenReturn(new ResponseFormat());
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumerDefinition).isRight());
+ }
- @Before
- public void setUp(){
- consumerBusinessLogic = new ConsumerBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
- consumerDataDefinition = new ConsumerDataDefinition();
- consumer = new ConsumerDefinition();
- MockitoAnnotations.initMocks(this);
- user = new User("Stan", "Lee", "stan.lee",
- "stan.lee@marvel.com", "ADMIN", 1542024000L);
- }
+ @Test
+ void testCreateConsumer_givenNonListedUser_thenReturnsError() {
+ ConsumerDefinition consumerDefinition = new ConsumerDefinition();
+ Mockito.when(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS))
+ .thenReturn(new ResponseFormat());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false))
+ .thenThrow(new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION));
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumerDefinition).isRight());
+ }
- @Test
- public void testCreateConsumer_givenMissingUser_thenReturnsError() {
- User user = new User();
- ConsumerDefinition consumerDefinition = new ConsumerDefinition();
- Mockito.when(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION))
- .thenReturn(new ResponseFormat());
- assertTrue(consumerBusinessLogic.createConsumer(user, consumerDefinition).isRight());
- }
+ @Test
+ void testCreateConsumer_givenNonAdminUser_thenReturnsError() {
+ user.setRole("DESIGNER");
+ Mockito.when(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION))
+ .thenReturn(new ResponseFormat());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
- @Test
- public void testCreateConsumer_givenNonListedUser_thenReturnsError() {
- ConsumerDefinition consumerDefinition = new ConsumerDefinition();
- Mockito.when(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS))
- .thenReturn(new ResponseFormat());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenThrow(new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION));
- assertTrue(consumerBusinessLogic.createConsumer(user, consumerDefinition).isRight());
- }
+ @Test
+ void testCreateConsumer_givenInvalidConsumerNames_thenReturnsError() {
+ Map<String, ActionStatus> invalidConsumerNames = new HashMap<>();
+ invalidConsumerNames.put(null, ActionStatus.MISSING_DATA);
+ invalidConsumerNames.put(".#()", ActionStatus.INVALID_CONTENT);
+ invalidConsumerNames.put(RandomStringUtils.random(256, true, false), ActionStatus.EXCEEDS_LIMIT);
+ for (Map.Entry<String, ActionStatus> e : invalidConsumerNames.entrySet()) {
+ consumer.setConsumerName(e.getKey());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer name"))
+ .thenReturn(new ResponseFormat());
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
+ }
- @Test
- public void testCreateConsumer_givenNonAdminUser_thenReturnsError() {
- user.setRole("DESIGNER");
- Mockito.when(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION))
- .thenReturn(new ResponseFormat());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
+ @Test
+ void testCreateConsumer_givenInvalidConsumerPasswords_thenReturnsError() {
+ Map<String, ActionStatus> invalidPasswordResults = new HashMap<>();
+ invalidPasswordResults.put(null, ActionStatus.MISSING_DATA);
+ invalidPasswordResults.put(RandomStringUtils.random(64, '*'), ActionStatus.INVALID_CONTENT_PARAM);
+ invalidPasswordResults.put("password", ActionStatus.INVALID_LENGTH);
+ for (Map.Entry<String, ActionStatus> e : invalidPasswordResults.entrySet()) {
+ consumer.setConsumerName("_marvel");
+ consumer.setConsumerPassword(e.getKey());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer password"))
+ .thenReturn(new ResponseFormat());
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
+ }
- @Test
- public void testCreateConsumer_givenInvalidConsumerNames_thenReturnsError() {
- Map<String, ActionStatus> invalidConsumerNames = new HashMap<>();
- invalidConsumerNames.put(null, ActionStatus.MISSING_DATA);
- invalidConsumerNames.put(".#()", ActionStatus.INVALID_CONTENT);
- invalidConsumerNames.put(RandomStringUtils.random(256, true, false), ActionStatus.EXCEEDS_LIMIT);
- for(Map.Entry<String, ActionStatus> e: invalidConsumerNames.entrySet()){
- consumer.setConsumerName(e.getKey());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer name"))
- .thenReturn(new ResponseFormat());
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
- }
+ @Test
+ void testCreateConsumer_givenInvalidConsumerSalts_thenReturnsError() {
+ consumer.setConsumerPassword(RandomStringUtils.random(64, true, true));
+ Map<String, ActionStatus> invalidPasswordSalts = new HashMap<>();
+ invalidPasswordSalts.put(null, ActionStatus.MISSING_DATA);
+ invalidPasswordSalts.put(RandomStringUtils.random(32, "*"), ActionStatus.INVALID_CONTENT_PARAM);
+ invalidPasswordSalts.put("password", ActionStatus.INVALID_LENGTH);
+ for (Map.Entry<String, ActionStatus> e : invalidPasswordSalts.entrySet()) {
+ consumer.setConsumerName("_marvel");
+ consumer.setConsumerSalt(e.getKey());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer salt"))
+ .thenReturn(new ResponseFormat());
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
+ }
- @Test
- public void testCreateConsumer_givenInvalidConsumerPasswords_thenReturnsError() {
- Map<String, ActionStatus> invalidPasswordResults = new HashMap<>();
- invalidPasswordResults.put(null, ActionStatus.MISSING_DATA);
- invalidPasswordResults.put(RandomStringUtils.random(64, '*' ), ActionStatus.INVALID_CONTENT_PARAM);
- invalidPasswordResults.put("password", ActionStatus.INVALID_LENGTH);
- for(Map.Entry<String, ActionStatus> e: invalidPasswordResults.entrySet()){
- consumer.setConsumerName("_marvel");
- consumer.setConsumerPassword(e.getKey());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer password"))
- .thenReturn(new ResponseFormat());
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
- }
+ @Test
+ void testCreateConsumer_givenConsumerNotLocked_thenReturnsError() {
+ consumer.setConsumerName("_marvel");
+ consumer.setConsumerPassword(RandomStringUtils.random(64, true, true));
+ consumer.setConsumerSalt(RandomStringUtils.random(32, 'a'));
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
+ .thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
- @Test
- public void testCreateConsumer_givenInvalidConsumerSalts_thenReturnsError() {
- consumer.setConsumerPassword(RandomStringUtils.random(64, true,true));
- Map<String, ActionStatus> invalidPasswordSalts = new HashMap<>();
- invalidPasswordSalts.put(null, ActionStatus.MISSING_DATA);
- invalidPasswordSalts.put(RandomStringUtils.random(32, "*" ), ActionStatus.INVALID_CONTENT_PARAM);
- invalidPasswordSalts.put("password", ActionStatus.INVALID_LENGTH);
- for(Map.Entry<String, ActionStatus> e: invalidPasswordSalts.entrySet()){
- consumer.setConsumerName("_marvel");
- consumer.setConsumerSalt(e.getKey());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(componentsUtils.getResponseFormat(e.getValue(), "Consumer salt"))
- .thenReturn(new ResponseFormat());
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
- }
+ @Test
+ void testCreateConsumer_givenUnableToCreateCredentials_thenReturnsError() {
+ ConsumerDataDefinition consumerDataDefinition = new ConsumerDataDefinition();
+ consumerDataDefinition.setConsumerName("_marvel");
+ consumerDataDefinition.setConsumerPassword(RandomStringUtils.random(64, true, true));
+ consumerDataDefinition.setConsumerSalt(RandomStringUtils.random(32, 'a'));
+ ConsumerDefinition consumer = new ConsumerDefinition(consumerDataDefinition);
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
+ .thenReturn(StorageOperationStatus.OK);
+ Mockito.when(consumerOperation.getCredentials(anyString()))
+ .thenReturn(Either.right(StorageOperationStatus.OK));
+ Mockito.when(consumerOperation.createCredentials(any(ConsumerData.class)))
+ .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
+ }
- @Test
- public void testCreateConsumer_givenConsumerNotLocked_thenReturnsError() {
- consumer.setConsumerName("_marvel");
- consumer.setConsumerPassword(RandomStringUtils.random(64, true,true));
- consumer.setConsumerSalt(RandomStringUtils.random(32, 'a'));
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
- .thenReturn(StorageOperationStatus.GENERAL_ERROR);
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
+ @Test
+ void testCreateConsumer_givenValidUserAndConsumer_thenReturnsConsumer() {
+ ConsumerDataDefinition consumerDataDefinition = new ConsumerDataDefinition();
+ consumerDataDefinition.setConsumerName("_marvel");
+ consumerDataDefinition.setConsumerPassword(RandomStringUtils.random(64, true, true));
+ consumerDataDefinition.setConsumerSalt(RandomStringUtils.random(32, 'a'));
+ ConsumerDefinition consumer = new ConsumerDefinition(consumerDataDefinition);
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
+ .thenReturn(StorageOperationStatus.OK);
+ Mockito.when(consumerOperation.getCredentials(anyString()))
+ .thenReturn(Either.right(StorageOperationStatus.OK));
+ Mockito.when(consumerOperation.createCredentials(any(ConsumerData.class)))
+ .thenReturn(Either.left(new ConsumerData(consumerDataDefinition)));
+ assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isLeft());
+ }
- @Test
- public void testCreateConsumer_givenUnableToCreateCredentials_thenReturnsError() {
- ConsumerDataDefinition consumerDataDefinition = new ConsumerDataDefinition();
- consumerDataDefinition.setConsumerName("_marvel");
- consumerDataDefinition.setConsumerPassword(RandomStringUtils.random(64, true,true));
- consumerDataDefinition.setConsumerSalt(RandomStringUtils.random(32, 'a'));
- ConsumerDefinition consumer = new ConsumerDefinition(consumerDataDefinition);
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
- .thenReturn(StorageOperationStatus.OK);
- Mockito.when(consumerOperation.getCredentials(anyString()))
- .thenReturn(Either.right(StorageOperationStatus.OK));
- Mockito.when(consumerOperation.createCredentials(any(ConsumerData.class)))
- .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isRight());
- }
+ @Test
+ void testGetConsumer_givenNullUser_thenReturnsError() {
+ Mockito.when(consumerOperation.getCredentials("marvel123"))
+ .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
+ assertTrue(consumerBusinessLogic.getConsumer("marvel123", null).isRight());
+ }
- @Test
- public void testCreateConsumer_givenValidUserAndConsumer_thenReturnsConsumer() {
- ConsumerDataDefinition consumerDataDefinition = new ConsumerDataDefinition();
- consumerDataDefinition.setConsumerName("_marvel");
- consumerDataDefinition.setConsumerPassword(RandomStringUtils.random(64, true,true));
- consumerDataDefinition.setConsumerSalt(RandomStringUtils.random(32, 'a'));
- ConsumerDefinition consumer = new ConsumerDefinition(consumerDataDefinition);
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(iGraphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
- .thenReturn(StorageOperationStatus.OK);
- Mockito.when(consumerOperation.getCredentials(anyString()))
- .thenReturn(Either.right(StorageOperationStatus.OK));
- Mockito.when(consumerOperation.createCredentials(any(ConsumerData.class)))
- .thenReturn(Either.left(new ConsumerData(consumerDataDefinition)));
- assertTrue(consumerBusinessLogic.createConsumer(user, consumer).isLeft());
- }
+ @Test
+ void testGetConsumer_givenValidUserAndConsumerId_thenReturnsConsumer() {
+ Mockito.when(consumerOperation.getCredentials("marvel123"))
+ .thenReturn(Either.left(new ConsumerData()));
+ Mockito.when(consumerData.getConsumerDataDefinition())
+ .thenReturn(consumerDataDefinition);
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ assertTrue(consumerBusinessLogic.getConsumer("marvel123", user).isLeft());
+ }
- @Test
- public void testGetConsumer_givenNullUser_thenReturnsError() {
- Mockito.when(consumerOperation.getCredentials("marvel123"))
- .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
- assertTrue(consumerBusinessLogic.getConsumer("marvel123", null).isRight());
- }
+ @Test
+ void testUpdateConsumer_givenValidConsumer_thenReturnsUpdatedConsumer() {
+ ConsumerDefinition updatedConsumer = new ConsumerDefinition(consumerDataDefinition);
+ updatedConsumer.setConsumerName("marvel2");
+ ConsumerDataDefinition updatedConsumerDataDef = new ConsumerDataDefinition();
+ updatedConsumerDataDef.setConsumerName("marvel2");
+ ConsumerData consumerData = new ConsumerData(updatedConsumerDataDef);
+ Mockito.when(consumerOperation.updateCredentials(any(ConsumerData.class)))
+ .thenReturn(Either.left(consumerData));
+ assertEquals(updatedConsumer.getConsumerName(), consumerBusinessLogic.updateConsumer(consumer).left().value().getConsumerName());
+ }
- @Test
- public void testGetConsumer_givenValidUserAndConsumerId_thenReturnsConsumer() {
- Mockito.when(consumerOperation.getCredentials("marvel123"))
- .thenReturn(Either.left(new ConsumerData()));
- Mockito.when(consumerData.getConsumerDataDefinition())
- .thenReturn(consumerDataDefinition);
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- assertTrue(consumerBusinessLogic.getConsumer("marvel123", user).isLeft());
- }
+ @Test
+ void testUpdateConsumer_givenUpdateFailure_thenReturnsError() {
+ Mockito.when(consumerOperation.updateCredentials(any(ConsumerData.class)))
+ .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+ assertTrue(consumerBusinessLogic.updateConsumer(consumer).isRight());
+ }
- @Test
- public void testUpdateConsumer_givenValidConsumer_thenReturnsUpdatedConsumer() {
- ConsumerDefinition updatedConsumer = new ConsumerDefinition(consumerDataDefinition);
- updatedConsumer.setConsumerName("marvel2");
- ConsumerDataDefinition updatedConsumerDataDef = new ConsumerDataDefinition();
- updatedConsumerDataDef.setConsumerName("marvel2");
- ConsumerData consumerData = new ConsumerData(updatedConsumerDataDef);
- Mockito.when(consumerOperation.updateCredentials(any(ConsumerData.class)))
- .thenReturn(Either.left(consumerData));
- assertEquals(updatedConsumer.getConsumerName(), consumerBusinessLogic.updateConsumer(consumer).left().value().getConsumerName());
- }
+ @Test
+ void testDeleteConsumer_givenValidUserAndConsumerId_thenReturnsSuccessful() {
+ ConsumerData consumerData = new ConsumerData(new ConsumerDataDefinition());
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(consumerOperation.deleteCredentials("marvel123"))
+ .thenReturn(Either.left(consumerData));
+ assertTrue(consumerBusinessLogic.deleteConsumer("marvel123", user).isLeft());
+ }
- @Test
- public void testUpdateConsumer_givenUpdateFailure_thenReturnsError() {
- Mockito.when(consumerOperation.updateCredentials(any(ConsumerData.class)))
- .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
- assertTrue(consumerBusinessLogic.updateConsumer(consumer).isRight());
- }
-
- @Test
- public void testDeleteConsumer_givenValidUserAndConsumerId_thenReturnsSuccessful() {
- ConsumerData consumerData = new ConsumerData(new ConsumerDataDefinition());
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(consumerOperation.deleteCredentials("marvel123"))
- .thenReturn(Either.left(consumerData));
- assertTrue(consumerBusinessLogic.deleteConsumer("marvel123", user).isLeft());
- }
-
- @Test
- public void testDeleteConsumer_givenInvalidUser_thenReturnsError() {
- Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
- Mockito.when(consumerOperation.deleteCredentials("marvel123"))
- .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
- assertTrue(consumerBusinessLogic.deleteConsumer("marvel123", user).isRight());
- }
-}
\ No newline at end of file
+ @Test
+ void testDeleteConsumer_givenInvalidUser_thenReturnsError() {
+ Mockito.when(UserBusinessLogic.getUser(user.getUserId(), false)).thenReturn(user);
+ Mockito.when(consumerOperation.deleteCredentials("marvel123"))
+ .thenReturn(Either.right(StorageOperationStatus.USER_NOT_FOUND));
+ assertTrue(consumerBusinessLogic.deleteConsumer("marvel123", user).isRight());
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java
index cd0b1c9..ebc5702 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java
@@ -29,14 +29,30 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyObject;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -70,29 +86,14 @@
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+@ExtendWith(MockitoExtension.class)
+class GroupBusinessLogicTest {
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.anyMap;
-import static org.mockito.ArgumentMatchers.anyObject;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
-
-
-@RunWith(MockitoJUnitRunner.class)
-public class GroupBusinessLogicTest {
-
+ static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ "src/test/resources/config/catalog-be");
+ static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
@InjectMocks
private GroupBusinessLogic test;
-
@Mock
private ApplicationDataTypeCache dataTypeCache;
@Mock
@@ -110,13 +111,9 @@
@Mock
private JanusGraphDao janusGraphDao;
@Mock
- PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
+ private PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
- static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
- "src/test/resources/config/catalog-be");
- static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- @Before
+ @BeforeEach
public void setUp() throws Exception {
test.setDataTypeCache(dataTypeCache);
test.setToscaOperationFacade(toscaOperationFacade);
@@ -126,7 +123,7 @@
}
@Test
- public void testCreateGroups_NoDataType() {
+ void testCreateGroups_NoDataType() {
Either<List<GroupDefinition>, ResponseFormat> result;
Component component = new Resource();
List<GroupDefinition> groupDefinitions = new ArrayList<>();
@@ -138,7 +135,7 @@
}
@Test
- public void testCreateGroups() {
+ void testCreateGroups() {
Either<List<GroupDefinition>, ResponseFormat> result;
Component component = new Resource();
component.setUniqueId("id");
@@ -158,7 +155,7 @@
}
@Test
- public void testValidUpdateVfGrpNameOnGraph() {
+ void testValidUpdateVfGrpNameOnGraph() {
Either<List<GroupDefinition>, ResponseFormat> result;
Component component = new Resource();
component.setSystemName("name");
@@ -175,7 +172,7 @@
}
@Test
- public void testValidAndUpdateGrpInstancePropValues_fail() {
+ void testValidAndUpdateGrpInstancePropValues_fail() {
Either<GroupInstance, ResponseFormat> result;
String componentId = "id";
String instanceId = "id";
@@ -186,13 +183,13 @@
oldGroupInstance.setProperties(properties);
try {
result = test.validateAndUpdateGroupInstancePropertyValues(componentId, instanceId, oldGroupInstance, newProperties);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
assertThat(e.getActionStatus()).isEqualTo(ActionStatus.GENERAL_ERROR);
}
}
@Test
- public void testCreateGroup() {
+ void testCreateGroup() {
GroupDefinition result;
String componentId = "id";
String grpType = "grpType";
@@ -214,7 +211,7 @@
configurationManager.getConfiguration().setExcludedGroupTypesMapping(excludedGroupTypesMap);
List<PropertyDefinition> properties = asList(
- buildProperty("network_collection_type", "l3-network", "network collection type, defined with default value"));
+ buildProperty("network_collection_type", "l3-network", "network collection type, defined with default value"));
groupTypeDefinition.setProperties(properties);
when(groupTypeOperation.getLatestGroupTypeByType(grpType, false)).thenReturn(Either.left(groupTypeDefinition));
when(toscaOperationFacade.canAddGroups(componentId)).thenReturn(true);
@@ -238,9 +235,9 @@
}
@Test
- public void testUpdateGroup() throws Exception {
+ void testUpdateGroup() throws Exception {
- Component component= new Resource();
+ Component component = new Resource();
GroupDefinition updatedGroup = new GroupDefinition();
List<GroupDefinition> grpdefList = new ArrayList<>();
updatedGroup.setName("GRP.01");
@@ -251,15 +248,14 @@
when(accessValidations.validateUserCanWorkOnComponent("compid", ComponentTypeEnum.SERVICE, "USR01", "UpdateGroup")).thenReturn(component);
when(groupsOperation.updateGroup(component, updatedGroup)).thenReturn(Either.left(updatedGroup));
GroupDefinition Gdefinition = test.updateGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
- "USR01", updatedGroup);
- Assert.assertEquals(Gdefinition,updatedGroup);
+ "USR01", updatedGroup);
+ Assert.assertEquals(Gdefinition, updatedGroup);
}
+ @Test
+ void testUpdateGroup_Invalidname() throws Exception {
- @Test(expected = ComponentException.class)
- public void testUpdateGroup_Invalidname() throws Exception {
-
- Component component= new Resource();
+ Component component = new Resource();
GroupDefinition updatedGroup = new GroupDefinition();
List<GroupDefinition> grpdefList = new ArrayList<>();
updatedGroup.setName("GRP~01");
@@ -268,15 +264,16 @@
component.setUniqueId("GRP.01");
component.setGroups(grpdefList);
when(accessValidations.validateUserCanWorkOnComponent("compid", ComponentTypeEnum.SERVICE, "USR01", "UpdateGroup")).thenReturn(component);
- GroupDefinition Gdefinition = test.updateGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
+ assertThrows(ComponentException.class, () -> {
+ GroupDefinition Gdefinition = test.updateGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
"USR01", updatedGroup);
-
+ });
}
- @Test(expected = ComponentException.class)
- public void testDeleteGroup_exception() throws Exception {
+ @Test
+ void testDeleteGroup_exception() throws Exception {
- Component component= new Resource();
+ Component component = new Resource();
GroupDefinition updatedGroup = new GroupDefinition();
List<GroupDefinition> grpdefList = new ArrayList<>();
updatedGroup.setName("GRP~01");
@@ -285,17 +282,19 @@
component.setUniqueId("GRP.01");
component.setGroups(grpdefList);
when(accessValidations.validateUserCanWorkOnComponent("compid", ComponentTypeEnum.SERVICE, "USR01", "DeleteGroup")).thenReturn(component);
- when(groupsOperation.deleteGroups(anyObject(),anyList())).thenReturn(Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND));
+ when(groupsOperation.deleteGroups(anyObject(), anyList())).thenReturn(Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND));
when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
- GroupDefinition Gdefinition = test.deleteGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
+ assertThrows(ComponentException.class, () -> {
+ GroupDefinition Gdefinition = test.deleteGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
"USR01");
+ });
}
@Test
- public void testDeleteGroup(){
+ void testDeleteGroup() {
- Component component= new Resource();
+ Component component = new Resource();
List<GroupDefinition> groupDefList = new ArrayList<>();
GroupDefinition updatedGroup = new GroupDefinition();
updatedGroup.setName("GRP~01");
@@ -306,12 +305,12 @@
List<GroupDefinition> groupDefListCopy = new ArrayList<>();
groupDefListCopy.add(updatedGroup);
when(accessValidations.validateUserCanWorkOnComponent("compid", ComponentTypeEnum.SERVICE, "USR01", "DeleteGroup")).thenReturn(component);
- when(groupsOperation.deleteGroups(anyObject(),anyList())).thenReturn(Either.left(groupDefListCopy));
+ when(groupsOperation.deleteGroups(anyObject(), anyList())).thenReturn(Either.left(groupDefListCopy));
when(groupsOperation.deleteCalculatedCapabilitiesWithProperties(anyString(), anyObject())).thenReturn(StorageOperationStatus.OK);
- when(policyTargetsUpdateHandler.removePoliciesTargets(anyObject(),anyString(),anyObject())).thenReturn(ActionStatus.OK);
+ when(policyTargetsUpdateHandler.removePoliciesTargets(anyObject(), anyString(), anyObject())).thenReturn(ActionStatus.OK);
GroupDefinition Gdefinition = test.deleteGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01",
- "USR01");
- Assert.assertEquals(Gdefinition,updatedGroup);
+ "USR01");
+ Assert.assertEquals(Gdefinition, updatedGroup);
}
}
\ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
index c8dde95..eedd44d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
@@ -7,9 +7,9 @@
* 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.
@@ -20,9 +20,19 @@
package org.openecomp.sdc.be.components.merge.instance;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
-import org.junit.Before;
-import org.junit.Test;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
@@ -48,16 +58,7 @@
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-public class ComponentInstancePropsAndInputsMergeTest {
+class ComponentInstancePropsAndInputsMergeTest {
private static final String INSTANCE_ID1 = "inst1";
private static final User USER = new User();
@@ -84,16 +85,16 @@
private DataForMergeHolder oldDataHolder;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- resourceToUpdate = new ResourceBuilder().addInstanceInput(INSTANCE_ID1, "instInput1")
- .addInstanceInput(INSTANCE_ID1, "instInput2")
- .addInstanceProperty(INSTANCE_ID1, "instProp1")
- .addInstanceProperty(INSTANCE_ID1, "instProp2")
- .addInput("input1")
- .addInput("input2")
- .setUniqueId("resourceId").build();
+ resourceToUpdate = new ResourceBuilder().addInstanceInput(INSTANCE_ID1, "instInput1")
+ .addInstanceInput(INSTANCE_ID1, "instInput2")
+ .addInstanceProperty(INSTANCE_ID1, "instProp1")
+ .addInstanceProperty(INSTANCE_ID1, "instProp2")
+ .addInput("input1")
+ .addInput("input2")
+ .setUniqueId("resourceId").build();
List<InputDefinition> oldInputs = ObjectGenerator.buildInputs("input1");
List<ComponentInstanceProperty> oldInstProps = ObjectGenerator.buildInstanceProperties("instProp1", "instProp3");
@@ -107,7 +108,7 @@
}
@Test
- public void mergeDataAfterCreate() throws Exception {
+ void mergeDataAfterCreate() {
List<InputDefinition> oldInputs = ObjectGenerator.buildInputs("input1");
List<ComponentInstanceProperty> oldInstProps = ObjectGenerator.buildInstanceProperties("instProp1", "instProp3");
List<ComponentInstanceInput> oldInstInputs = ObjectGenerator.buildInstanceInputs("instInput1", "instInput3");
@@ -121,46 +122,66 @@
ArgumentCaptor<ComponentParametersView> parametersViewCaptor = ArgumentCaptor.forClass(ComponentParametersView.class);
- when(toscaOperationFacade.getToscaElement(Mockito.eq("resourceId"), parametersViewCaptor.capture())).thenReturn(Either.left(resourceToUpdate));
- when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(oldInstInputs, oldInputs, resourceToUpdate, INSTANCE_ID1)).thenReturn(ActionStatus.OK);
- when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(oldInstProps, oldInputs, resourceToUpdate, INSTANCE_ID1)).thenReturn(ActionStatus.OK);
- when(componentInstanceInputsRedeclareHandler.redeclareComponentInputsForInstance(resourceToUpdate, INSTANCE_ID1, currInstanceOriginType, oldInputs)).thenReturn(ActionStatus.OK);
+ when(toscaOperationFacade.getToscaElement(Mockito.eq("resourceId"), parametersViewCaptor.capture()))
+ .thenReturn(Either.left(resourceToUpdate));
+ when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(oldInstInputs, oldInputs, resourceToUpdate, INSTANCE_ID1))
+ .thenReturn(ActionStatus.OK);
+ when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(oldInstProps, oldInputs, resourceToUpdate, INSTANCE_ID1))
+ .thenReturn(ActionStatus.OK);
+ when(componentInstanceInputsRedeclareHandler
+ .redeclareComponentInputsForInstance(resourceToUpdate, INSTANCE_ID1, currInstanceOriginType, oldInputs)).thenReturn(ActionStatus.OK);
Component mergeResult = testInstance.mergeDataAfterCreate(USER, dataForMergeHolder, resourceToUpdate, INSTANCE_ID1);
assertEquals(mergeResult, resourceToUpdate);
assertComponentFilter(parametersViewCaptor.getValue());
}
- @Test(expected = ComponentException.class)
- public void mergeDataAfterCreate_failedToMergeComponentInstanceInputs() throws Exception {
- ResponseFormat errorResponse = new ResponseFormat();
+ @Test
+ void mergeDataAfterCreate_failedToMergeComponentInstanceInputs() {
+ final ResponseFormat errorResponse = new ResponseFormat();
when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(errorResponse);
- when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString())).thenReturn(ActionStatus.GENERAL_ERROR);
- testInstance.mergeDataAfterCreate(USER, new DataForMergeHolder(), new Service(), "inst1");
+ when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString()))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
+ final DataForMergeHolder dataHolder = new DataForMergeHolder();
+ final Service service = new Service();
+ assertThrows(ComponentException.class, () -> {
+ testInstance.mergeDataAfterCreate(USER, dataHolder, service, "inst1");
+ });
verifyZeroInteractions(componentInstanceInputsRedeclareHandler, componentInstancePropertiesMergeBL, toscaOperationFacade);
}
- @Test(expected = ComponentException.class)
- public void mergeDataAfterCreate_failedToMergeComponentInstProps() throws Exception {
- ResponseFormat errorResponse = new ResponseFormat();
- when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString())).thenReturn(ActionStatus.OK);
- when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(anyList(), anyList(), any(Component.class), anyString())).thenReturn(ActionStatus.GENERAL_ERROR);
+ @Test
+ void mergeDataAfterCreate_failedToMergeComponentInstProps() {
+ final ResponseFormat errorResponse = new ResponseFormat();
+ when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString()))
+ .thenReturn(ActionStatus.OK);
+ when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(anyList(), anyList(), any(Component.class), anyString()))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(errorResponse);
- testInstance.mergeDataAfterCreate(USER, new DataForMergeHolder(), new Service(), "inst1");
+ final DataForMergeHolder dataHolder = new DataForMergeHolder();
+ final Service service = new Service();
+ assertThrows(ComponentException.class, () -> {
+ testInstance.mergeDataAfterCreate(USER, dataHolder, service, "inst1");
+ });
verifyZeroInteractions(componentInstanceInputsRedeclareHandler, toscaOperationFacade);
}
-
- @Test(expected = ComponentException.class)
- public void mergeDataAfterCreate_mergeInputs_FailedToFetchResource() throws Exception {
- ResponseFormat errorResponse = new ResponseFormat();
- when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString())).thenReturn(ActionStatus.OK);
- when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(anyList(), anyList(), any(Component.class), anyString())).thenReturn(ActionStatus.OK);
- when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+ @Test
+ void mergeDataAfterCreate_mergeInputs_FailedToFetchResource() {
+ final ResponseFormat errorResponse = new ResponseFormat();
+ when(componentInstanceInputsMergeBL.mergeComponentInstanceInputs(anyList(), anyList(), any(Component.class), anyString()))
+ .thenReturn(ActionStatus.OK);
+ when(componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(anyList(), anyList(), any(Component.class), anyString()))
+ .thenReturn(ActionStatus.OK);
+ when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class)))
+ .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR);
when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(errorResponse);
- DataForMergeHolder dataHolder = new DataForMergeHolder();
+ final DataForMergeHolder dataHolder = new DataForMergeHolder();
dataHolder.setOrigComponentInputs(ObjectGenerator.buildInputs("input1", "input2"));
- testInstance.mergeDataAfterCreate(USER, dataHolder, new Service(), "inst1");
+ final Service service = new Service();
+ assertThrows(ComponentException.class, () -> {
+ testInstance.mergeDataAfterCreate(USER, dataHolder, service, "inst1");
+ });
verifyZeroInteractions(componentInstanceInputsRedeclareHandler);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServletTest.java
index 40341be..40dd38a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServletTest.java
@@ -30,8 +30,19 @@
package org.openecomp.sdc.be.externalapi.servlet;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
import fj.data.Either;
+import java.util.Arrays;
+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 org.apache.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
@@ -39,11 +50,19 @@
import org.glassfish.jersey.test.TestProperties;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
-import org.openecomp.sdc.be.components.impl.*;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.SpringConfig;
@@ -68,48 +87,31 @@
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.GenericType;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Arrays;
-import java.util.List;
+@TestInstance(Lifecycle.PER_CLASS)
+class AbstractTemplateServletTest extends JerseyTest {
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
+ private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ private final HttpSession session = Mockito.mock(HttpSession.class);
+ private final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ private final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ private final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
+ private final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
+ private final ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class);
+ private final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
+ private final Resource resource = Mockito.mock(Resource.class);
+ private final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class);
+ private final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class);
+ private final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class);
+ private final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();
+ private final LifecycleBusinessLogic lifecycleBusinessLogic = Mockito.mock(LifecycleBusinessLogic.class);
+ private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
+ private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
-public class AbstractTemplateServletTest extends JerseyTest {
-
- private static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- private static final HttpSession session = Mockito.mock(HttpSession.class);
- private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- private static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- private static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- private static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
- private static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
- private static final ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class);
- private static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
- private static final Resource resource = Mockito.mock(Resource.class);
- private static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class);
- private static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class);
- private static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class);
- private static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();
- private static final LifecycleBusinessLogic lifecycleBusinessLogic = Mockito.mock(LifecycleBusinessLogic.class);
- private static final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
- private static final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
- private static String serviceVertexUuid;
-
-
- @BeforeClass
- public static void setup() {
+ @BeforeAll
+ public void setup() {
ExternalConfiguration.setAppName("catalog-be");
when(request.getSession()).thenReturn(session);
when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId");
@@ -117,7 +119,8 @@
when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/abstract"));
when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
@@ -129,23 +132,31 @@
when(resource.getName()).thenReturn("MockVFCMT");
when(resource.getSystemName()).thenReturn("mockvfcmt");
Either<Resource, ResponseFormat> eitherRet = Either.left(resource);
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
+ when(componentsUtils
+ .convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class),
+ Mockito.any(),
+ Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic);
when(categoryDefinition.getName()).thenReturn("Template");
when(subCategoryDefinition.getName()).thenReturn("Monitoring Template");
when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition));
- when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition)));
- when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(resource);
+ when(elementBusinessLogic.getAllResourceCategories())
+ .thenReturn(Either.left(Arrays.asList(categoryDefinition)));
+ when(resourceBusinessLogic
+ .createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(resource);
when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter);
when(request.isUserInRole(anyString())).thenReturn(true);
- Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
+ Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter)
+ .convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
Mockito.eq(true));
String appConfigDir = "src/test/abstract/config";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ 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();
@@ -154,49 +165,64 @@
configurationManager.setConfiguration(configuration);
}
- private static void mockResponseFormat() {
- when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> {
- ResponseFormat ret;
- final ActionStatus actionStatus = invocation.getArgument(0);
- switch( actionStatus ){
- case CREATED :{
- ret = new ResponseFormat(HttpStatus.SC_CREATED);
- break;
- }
- default :{
- ret = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- break;
- }
- }
- return ret;
- });
+ @BeforeEach
+ public void beforeEach() throws Exception {
+ super.setUp();
}
- @Test
- public void createVfcmtHappyScenario() {
- final JSONObject createRequest = buildCreateJsonRequest();
- Response response = target().path("/v1/catalog/abstract").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID")
- .post(Entity.json(createRequest.toJSONString()), Response.class);
- assertEquals(response.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ @AfterEach
+ public void afterEach() throws Exception {
+ super.tearDown();
}
+
+ private void mockResponseFormat() {
+ when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class)))
+ .thenAnswer((Answer<ResponseFormat>) invocation -> {
+ ResponseFormat ret;
+ final ActionStatus actionStatus = invocation.getArgument(0);
+ switch (actionStatus) {
+ case CREATED: {
+ ret = new ResponseFormat(HttpStatus.SC_CREATED);
+ break;
+ }
+ default: {
+ ret = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ break;
+ }
+ }
+ return ret;
+ });
+ }
+
+ @Test
+ void createVfcmtHappyScenario() {
+ final JSONObject createRequest = buildCreateJsonRequest();
+ Response response = target().path("/v1/catalog/abstract").request(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, "mockAttID")
+ .post(Entity.json(createRequest.toJSONString()), Response.class);
+ assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus());
+ }
+
private static final String BASIC_CREATE_REQUEST = "{\r\n" +
- " \"name\": \"VFCMT_1\",\r\n" +
- " \"description\": \"VFCMT Description\",\r\n" +
- " \"resourceType\" : \"VFCMT\",\r\n" +
- " \"category\": \"Template\",\r\n" +
- " \"subcategory\": \"Monitoring Template\",\r\n" +
- " \"vendorName\" : \"DCAE\",\r\n" +
- " \"vendorRelease\" : \"1.0\",\r\n" +
- " \"tags\": [\r\n" +
- " \"VFCMT_1\"\r\n" +
- " ],\r\n" +
- " \"icon\" : \"defaulticon\",\r\n" +
- " \"contactId\": \"cs0008\"\r\n" +
- "}";
+ " \"name\": \"VFCMT_1\",\r\n" +
+ " \"description\": \"VFCMT Description\",\r\n" +
+ " \"resourceType\" : \"VFCMT\",\r\n" +
+ " \"category\": \"Template\",\r\n" +
+ " \"subcategory\": \"Monitoring Template\",\r\n" +
+ " \"vendorName\" : \"DCAE\",\r\n" +
+ " \"vendorRelease\" : \"1.0\",\r\n" +
+ " \"tags\": [\r\n" +
+ " \"VFCMT_1\"\r\n" +
+ " ],\r\n" +
+ " \"icon\" : \"defaulticon\",\r\n" +
+ " \"contactId\": \"cs0008\"\r\n" +
+ "}";
+
private JSONObject buildCreateJsonRequest() {
JSONParser parser = new JSONParser();
- return (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST));
+ return (JSONObject) FunctionalInterfaces.swallowException(() -> parser.parse(BASIC_CREATE_REQUEST));
}
@@ -205,15 +231,29 @@
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
forceSet(TestProperties.CONTAINER_PORT, "0");
return new ResourceConfig()
- .register(new CrudExternalServlet(userBusinessLogic, componentInstanceBusinessLogic,componentsUtils,servletUtils,resourceImportManager, elementBusinessLogic, assetMetadataConverter, lifecycleBusinessLogic, resourceBusinessLogic, serviceBusinessLogic))
- .register(new AbstractBinder() {
+ .register(createMockServlet())
+ .register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- })
- .property("contextConfig", context);
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
}
-}
\ No newline at end of file
+ private CrudExternalServlet createMockServlet() {
+ return new CrudExternalServlet(
+ userBusinessLogic,
+ componentInstanceBusinessLogic,
+ componentsUtils,
+ servletUtils,
+ resourceImportManager,
+ elementBusinessLogic,
+ assetMetadataConverter,
+ lifecycleBusinessLogic,
+ resourceBusinessLogic,
+ serviceBusinessLogic);
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java
index ae8d294..a2673ea 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java
@@ -7,9 +7,9 @@
* 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.
@@ -21,7 +21,19 @@
package org.openecomp.sdc.be.externalapi.servlet;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
+import java.util.Arrays;
+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 org.apache.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
@@ -29,8 +41,10 @@
import org.glassfish.jersey.test.TestProperties;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -62,20 +76,7 @@
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.util.Arrays;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
-
-public class AssetsDataServletTest extends JerseyTest {
+class AssetsDataServletTest extends JerseyTest {
private static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
private static final HttpSession session = Mockito.mock(HttpSession.class);
@@ -95,11 +96,11 @@
private static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();
private static final LifecycleBusinessLogic lifecycleBusinessLogic = Mockito.mock(LifecycleBusinessLogic.class);
private static final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
- private static final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
+ private static final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito
+ .mock(ComponentInstanceBusinessLogic.class);
-
- @BeforeClass
+ @BeforeAll
public static void setup() {
ExternalConfiguration.setAppName("catalog-be");
when(request.getSession()).thenReturn(session);
@@ -108,7 +109,8 @@
when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources"));
when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
@@ -119,24 +121,31 @@
when(resource.getName()).thenReturn("MockVFCMT");
when(resource.getSystemName()).thenReturn("mockvfcmt");
- Either<Resource, ResponseFormat> eitherRet = Either.left(resource);
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
+ Either<Resource, ResponseFormat> eitherRet = Either.left(resource);
+ when(componentsUtils
+ .convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class),
+ Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic);
when(categoryDefinition.getName()).thenReturn("Template");
when(subCategoryDefinition.getName()).thenReturn("Monitoring Template");
when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition));
- when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition)));
- when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(resource);
+ when(elementBusinessLogic.getAllResourceCategories())
+ .thenReturn(Either.left(Arrays.asList(categoryDefinition)));
+ when(resourceBusinessLogic
+ .createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(resource);
when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter);
when(request.isUserInRole(anyString())).thenReturn(true);
- Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
+ Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter)
+ .convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
Mockito.eq(true));
String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ 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();
@@ -145,53 +154,66 @@
configurationManager.setConfiguration(configuration);
}
-
- private static void mockResponseFormat() {
- when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> {
- ResponseFormat ret;
- final ActionStatus actionStatus = invocation.getArgument(0);
- switch( actionStatus ){
- case CREATED :{
- ret = new ResponseFormat(HttpStatus.SC_CREATED);
- break;
- }
- default :{
- ret = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- break;
- }
- }
- return ret;
- });
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
}
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ private static void mockResponseFormat() {
+ when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class)))
+ .thenAnswer((Answer<ResponseFormat>) invocation -> {
+ ResponseFormat ret;
+ final ActionStatus actionStatus = invocation.getArgument(0);
+ switch (actionStatus) {
+ case CREATED: {
+ ret = new ResponseFormat(HttpStatus.SC_CREATED);
+ break;
+ }
+ default: {
+ ret = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ break;
+ }
+ }
+ return ret;
+ });
+ }
@Test
- public void createVfcmtHappyScenario() {
+ void createVfcmtHappyScenario() {
final JSONObject createRequest = buildCreateJsonRequest();
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID")
- .post(Entity.json(createRequest.toJSONString()), Response.class);
- assertEquals(response.getStatus(), HttpStatus.SC_CREATED);
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, "mockAttID")
+ .post(Entity.json(createRequest.toJSONString()), Response.class);
+ assertEquals(HttpStatus.SC_CREATED, response.getStatus());
}
+
private static final String BASIC_CREATE_REQUEST = "{\r\n" +
- " \"name\": \"VFCMT_1\",\r\n" +
- " \"description\": \"VFCMT Description\",\r\n" +
- " \"resourceType\" : \"VFCMT\",\r\n" +
- " \"category\": \"Template\",\r\n" +
- " \"subcategory\": \"Monitoring Template\",\r\n" +
- " \"vendorName\" : \"DCAE\",\r\n" +
- " \"vendorRelease\" : \"1.0\",\r\n" +
- " \"tags\": [\r\n" +
- " \"VFCMT_1\"\r\n" +
- " ],\r\n" +
- " \"icon\" : \"defaulticon\",\r\n" +
- " \"contactId\": \"cs0008\"\r\n" +
- "}";
+ " \"name\": \"VFCMT_1\",\r\n" +
+ " \"description\": \"VFCMT Description\",\r\n" +
+ " \"resourceType\" : \"VFCMT\",\r\n" +
+ " \"category\": \"Template\",\r\n" +
+ " \"subcategory\": \"Monitoring Template\",\r\n" +
+ " \"vendorName\" : \"DCAE\",\r\n" +
+ " \"vendorRelease\" : \"1.0\",\r\n" +
+ " \"tags\": [\r\n" +
+ " \"VFCMT_1\"\r\n" +
+ " ],\r\n" +
+ " \"icon\" : \"defaulticon\",\r\n" +
+ " \"contactId\": \"cs0008\"\r\n" +
+ "}";
+
private JSONObject buildCreateJsonRequest() {
JSONParser parser = new JSONParser();
- return (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST));
+ return (JSONObject) FunctionalInterfaces.swallowException(() -> parser.parse(BASIC_CREATE_REQUEST));
}
@@ -200,14 +222,16 @@
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
forceSet(TestProperties.CONTAINER_PORT, "0");
return new ResourceConfig()
- .register(new CrudExternalServlet(userBusinessLogic, componentInstanceBusinessLogic,componentsUtils,servletUtils,resourceImportManager, elementBusinessLogic, assetMetadataConverter, lifecycleBusinessLogic, resourceBusinessLogic, serviceBusinessLogic))
- .register(new AbstractBinder() {
+ .register(new CrudExternalServlet(userBusinessLogic, componentInstanceBusinessLogic, componentsUtils,
+ servletUtils, resourceImportManager, elementBusinessLogic, assetMetadataConverter,
+ lifecycleBusinessLogic, resourceBusinessLogic, serviceBusinessLogic))
+ .register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- })
- .property("contextConfig", context);
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
}
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java
index a7db4ba..22f5de6 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java
@@ -22,13 +22,37 @@
package org.openecomp.sdc.be.externalapi.servlet;
+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.doThrow;
+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.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.openecomp.sdc.be.components.impl.ComponentLocker;
import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
@@ -82,46 +106,16 @@
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.eq;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.when;
-
-public class ExternalRefServletTest extends JerseyTest {
-
- private static boolean setupDone = false;
- private static String serviceVertexUuid;
- private static String resourceVertexUuid;
- private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
- private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
- private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class);
- private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class);
- private static final ToscaOperationFacade toscaOperationFacadeMock = Mockito.mock(ToscaOperationFacade.class);
- private static final AccessValidations accessValidationsMock = Mockito.mock(AccessValidations.class);
- private static final ComponentLocker componentLocker = Mockito.mock(ComponentLocker.class);
- private static final HealingJanusGraphGenericDao janusGraphGenericDao = Mockito.mock(HealingJanusGraphGenericDao.class);
- private static final IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class);
+@TestInstance(Lifecycle.PER_CLASS)
+@ExtendWith(MockitoExtension.class)
+@Disabled("Investigate 'org.springframework.beans.factory.UnsatisfiedDependencyException: "
+ + "Error creating bean with name 'externalRefServletTest.TestSpringConfig': "
+ + "Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: "
+ + "No qualifying bean of type 'org.openecomp.sdc.be.externalapi.servlet.ExternalRefServletTest' available: expected at least 1 bean which qualifies as autowire candidate."
+ + "Dependency annotations: {}'")
+class ExternalRefServletTest extends JerseyTest {
private static final String COMPONENT_ID = "ci-MyComponentName";
-
private static final String FAKE_COMPONENT_ID = "ci-MyFAKEComponentName";
private static final String MONITORING_OBJECT_TYPE = "monitoring";
private static final String WORKFLOW_OBJECT_TYPE = "workflow";
@@ -134,15 +128,543 @@
private static final String REF_5 = "ref5";
//workflow
private static final String REF_6 = "ref6";
+ private static boolean setupDone = false;
+ private static String serviceVertexUuid;
+ private static String resourceVertexUuid;
+ /* Users */
+ 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 otherDesignerUser = new User("otherDesigner", "otherDesigner", "otherDesigner",
+ "otherDesigner@email.com", Role.DESIGNER
+ .name(), System.currentTimeMillis());
+ private static final User otherUser = new User("other", "other", "other", "other@email.com", Role.DESIGNER.name(),
+ System.currentTimeMillis());
+
+ @Mock
+ public WebAppContextWrapper webAppContextWrapper;
+ @Mock
+ private ServletContext servletContext;
+ @Mock
+ private WebApplicationContext webApplicationContext;
+ @Mock
+ private ServletUtils servletUtils;
+ @Mock
+ private UserBusinessLogic userAdmin;
+ @Mock
+ private ComponentsUtils componentUtils;
+ @Mock
+ private ResponseFormat responseFormat;
+ @Mock
+ private ResponseFormat notFoundResponseFormat;
+ @Mock
+ private ResponseFormat badRequestResponseFormat;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacadeMock;
+ @Mock
+ private AccessValidations accessValidationsMock;
+ @Mock
+ private ComponentLocker componentLocker;
+ @Mock
+ private HealingJanusGraphGenericDao janusGraphGenericDao;
+ @Mock
+ private IGraphLockOperation graphLockOperation;
+ @Mock
+ private HttpServletRequest request;
+ @Mock
+ private ByResponseFormatComponentException ce;
+ @Mock
+ private Component resourceComponentMock;
+ @Mock
+ private Component serviceComponentMock;
+
+ @BeforeAll
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ //Needed for User Authorization
+ //========================================================================================================================
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+ when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
+
+ String[] params = {otherDesignerUser.getUserId()};
+ when(ce.getResponseFormat()).thenReturn(responseFormat);
+ doThrow(ce).when(accessValidationsMock)
+ .validateUserCanWorkOnComponent(any(), any(), eq(otherDesignerUser.getUserId()), any());
+ doThrow(ce).when(accessValidationsMock)
+ .validateUserCanWorkOnComponent(any(), any(), eq(otherUser.getUserId()), any());
+
+ //Needed for error configuration
+ when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
+ when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
+ when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any()))
+ .thenReturn(badRequestResponseFormat);
+ 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";
+ 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.setAafAuthNeeded(false);
+ configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout);
+ configurationManager.setConfiguration(configuration);
+ ExternalConfiguration.setAppName("catalog-be");
+ }
+
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+
+ when(resourceComponentMock.getVersion()).thenReturn(VERSION);
+ when(resourceComponentMock.getUniqueId()).thenReturn(resourceVertexUuid);
+
+ when(serviceComponentMock.getVersion()).thenReturn(VERSION);
+ when(serviceComponentMock.getUniqueId()).thenReturn(serviceVertexUuid);
+
+ List<Component> listComponents = new LinkedList<>();
+ listComponents.add(serviceComponentMock);
+
+ when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any()))
+ .thenReturn(Either.left(listComponents));
+ when(toscaOperationFacadeMock.getComponentByUuidAndVersion(serviceVertexUuid, VERSION))
+ .thenReturn(Either.left(serviceComponentMock));
+ when(toscaOperationFacadeMock.getComponentByUuidAndVersion(resourceVertexUuid, VERSION))
+ .thenReturn(Either.left(resourceComponentMock));
+ when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any()))
+ .thenReturn(Either.left(listComponents.get(0)));
+ when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(resourceVertexUuid), any()))
+ .thenReturn(Either.left(resourceComponentMock));
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
+ @Test
+ void testGetExternalRefsForExistingComponentInstance() {
+ String path = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() {
+ });
+ assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ void testGetExternalRefsForAsset() {
+ String path = String
+ .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
+ MONITORING_OBJECT_TYPE);
+
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() {
+ });
+ assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ void testGetExternalRefsForAssetWithMissingEcompHeader() {
+ String path = String
+ .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
+ MONITORING_OBJECT_TYPE);
+
+ //No X-Ecomp-Instance-ID header
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ @Test
+ void testAddExternalRefForResource() {
+ String path = String
+ .format("/v1/catalog/resources/%s/resourceInstances/%s/externalReferences/%s", resourceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ String getPath = String
+ .format("/v1/catalog/resources/%s/version/%s/externalReferences/%s", resourceVertexUuid, VERSION,
+ MONITORING_OBJECT_TYPE);
+
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(new ExternalRefDTO(REF_1)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
+
+ //Check that GET will include the new reference
+ response = target()
+ .path(getPath)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, adminUser.getUserId())
+ .get();
+
+ Map<String, List<String>> dto = response.readEntity(new GenericType<Map<String, List<String>>>() {
+ });
+ assertThat(dto.get(COMPONENT_ID)).containsExactlyInAnyOrder(REF_1);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ void testAddExternalRefForExistingComponentInstance() {
+ String path = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ String getPath = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
+
+ //Check that GET will include the new reference
+ response = target()
+ .path(getPath)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, adminUser.getUserId())
+ .get();
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() {
+ });
+ assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ void testDeleteExternalRefForExistingComponentInstance() {
+ String deletePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ String getPath = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(deletePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
+
+ //Verify that the deleted reference is returned in body
+ ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
+ assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+
+ //Check that GET will NOT include the deleted reference
+ response = target()
+ .path(getPath)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ List<String> getResponse = response.readEntity(new GenericType<List<String>>() {
+ });
+ assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ void testUpdateExternalRefForExistingComponentInstance() {
+ String updatePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ String getPath = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(updatePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ //Verify that the updated reference is returned in body
+ ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
+ assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+
+ //Check that GET will include the updated reference
+ response = target()
+ .path(getPath)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() {
+ });
+ assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ /*
+ * Rainy Scenarios
+ */
+ @Test
+ void testAddExternalRefForNonExistingAssetId() {
+ String path = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid",
+ COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testAddExternalRefForNonExistingCompInstId() {
+ String path = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testAddExistingExternalRef() {
+ String path = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(new ExternalRefDTO(REF_1)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
+ }
+
+ @Test
+ void testUpdateExternalRefForNonExistingAssetId() {
+ String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s",
+ "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+
+ Response response = target()
+ .path(updatePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ //Verify that the 404 is returned
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+
+ }
+
+ @Test
+ void testUpdateExternalRefForNonExistingObjectIdOrOldRef() {
+ String updatePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
+
+ Response response = target()
+ .path(updatePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testDeleteExternalRefForNonExistingAssetId() {
+ String deletePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset",
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ Response response = target()
+ .path(deletePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testDeleteExternalRefForNonExistingRef() {
+ String deletePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
+ Response response = target()
+ .path(deletePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testGetExternalRefsForNonExistingAsset() {
+ String path = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id",
+ VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testGetExternalRefsForNonExistingVersion() {
+ String path = String
+ .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
+ FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ void testDeleteExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
+ String path = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, otherUser.getUserId())
+ .delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
+ }
+
+ @Test
+ void testDeleteExternalRefForUserWhichIsNotCurrentUpdater() {
+ String deletePath = String
+ .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
+ COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ Response response = target()
+ .path(deletePath)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
+ .header(Constants.USER_ID_HEADER, otherDesignerUser.getUserId())
+ .delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
+ }
+
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
+ return new ResourceConfig(ExternalRefsServlet.class)
+ .register(DefaultExceptionMapper.class)
+ .register(ComponentExceptionMapper.class)
+ .register(StorageExceptionMapper.class)
+ .property("contextConfig", context);
+ }
@Configuration
@PropertySource("classpath:dao.properties")
- static class TestSpringConfig {
+ public class TestSpringConfig {
private GraphVertex serviceVertex;
private GraphVertex resourceVertex;
private ExternalReferencesOperation externalReferenceOperation;
private HealingJanusGraphDao janusGraphDao;
+ @Mock
+ private IdMapper idMapper;
@Bean
ExternalRefsServlet externalRefsServlet() {
@@ -150,7 +672,9 @@
}
@Bean
- OperationUtils operationUtils() {return new OperationUtils(janusGraphDao());}
+ OperationUtils operationUtils() {
+ return new OperationUtils(janusGraphDao());
+ }
@Bean
ComponentExceptionMapper componentExceptionMapper() {
@@ -169,7 +693,8 @@
@Bean
ExternalRefsBusinessLogic externalRefsBusinessLogic() {
- return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(), accessValidations(), componentLocker());
+ return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(),
+ accessValidations(), componentLocker());
}
@Bean
@@ -179,7 +704,8 @@
@Bean
ExternalReferencesOperation externalReferencesOperation() {
- this.externalReferenceOperation = new ExternalReferencesOperation(janusGraphDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper());
+ this.externalReferenceOperation = new ExternalReferencesOperation(janusGraphDao(), nodeTypeOpertaion(),
+ topologyTemplateOperation(), idMapper());
this.externalReferenceOperation.setHealingPipelineDao(healingPipelineDao());
GraphTestUtils.clearGraph(janusGraphDao);
initGraphForTest();
@@ -193,16 +719,17 @@
@Bean
IdMapper idMapper() {
- IdMapper idMapper = Mockito.mock(IdMapper.class);
- when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
- when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
+ when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class)))
+ .thenReturn(COMPONENT_ID);
+ when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class)))
+ .thenReturn(COMPONENT_ID);
when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null);
return idMapper;
}
@Bean
TopologyTemplateOperation topologyTemplateOperation() {
- return new TopologyTemplateOperation();
+ return new TopologyTemplateOperation();
}
@Bean
@@ -232,7 +759,7 @@
@Bean
HealingJanusGraphDao janusGraphDao() {
- this.janusGraphDao = new HealingJanusGraphDao(healingPipelineDao(),janusGraphClient());
+ this.janusGraphDao = new HealingJanusGraphDao(healingPipelineDao(), janusGraphClient());
return janusGraphDao;
}
@@ -263,7 +790,7 @@
@Bean("healingPipelineDao")
HealingPipelineDao healingPipelineDao() {
- HealingPipelineDao healingPipelineDao = new HealingPipelineDao() ;
+ HealingPipelineDao healingPipelineDao = new HealingPipelineDao();
healingPipelineDao.setHealVersion(1);
healingPipelineDao.initHealVersion();
return healingPipelineDao;
@@ -277,7 +804,8 @@
private void initGraphForTest() {
if (!setupDone) {
- resourceVertex = GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF);
+ resourceVertex = GraphTestUtils
+ .createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF);
resourceVertexUuid = resourceVertex.getUniqueId();
//create a service and add ref
@@ -285,13 +813,18 @@
serviceVertexUuid = this.serviceVertex.getUniqueId();
//monitoring references
- externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
- externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
- externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
- externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ externalReferenceOperation
+ .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
+ externalReferenceOperation
+ .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
+ externalReferenceOperation
+ .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
+ externalReferenceOperation
+ .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
//workflow references
- externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
+ externalReferenceOperation
+ .addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
final JanusGraphOperationStatus commit = this.janusGraphDao.commit();
assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK);
@@ -300,432 +833,4 @@
}
-
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
-
- /* Users */
- private static User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(), System.currentTimeMillis());
- private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System
- .currentTimeMillis());
- private static User otherDesignerUser = new User("otherDesigner", "otherDesigner", "otherDesigner", "otherDesigner@email.com", Role.DESIGNER
- .name(), System.currentTimeMillis());
- private static User otherUser = new User("other", "other", "other", "other@email.com", Role.DESIGNER.name(), System.currentTimeMillis());
-
-
- @BeforeClass
- public static void setup() {
-
- //Needed for User Authorization
- //========================================================================================================================
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
- when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
- when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
-
- ByResponseFormatComponentException ce = Mockito.mock(ByResponseFormatComponentException.class);
- String[] params = {otherDesignerUser.getUserId()};
- when(ce.getResponseFormat()).thenReturn(responseFormat);
- doThrow(ce).when(accessValidationsMock)
- .validateUserCanWorkOnComponent(any(), any(), eq(otherDesignerUser.getUserId()), any());
- doThrow(ce).when(accessValidationsMock)
- .validateUserCanWorkOnComponent(any(), any(), eq(otherUser.getUserId()), any());
-
- //Needed for error configuration
- when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
- when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
- when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat);
- 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";
- 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);
- ExternalConfiguration.setAppName("catalog-be");
- }
-
- @Before
- public void before(){
-
- Component resourceComponentMock = Mockito.mock(Component.class);
- when(resourceComponentMock.getVersion()).thenReturn(VERSION);
- when(resourceComponentMock.getUniqueId()).thenReturn(resourceVertexUuid);
-
- Component serviceComponentMock = Mockito.mock(Component.class);
- when(serviceComponentMock.getVersion()).thenReturn(VERSION);
- when(serviceComponentMock.getUniqueId()).thenReturn(serviceVertexUuid);
-
- List<Component> listComponents = new LinkedList<>();
- listComponents.add(serviceComponentMock);
-
- when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents));
- when(toscaOperationFacadeMock.getComponentByUuidAndVersion(eq(serviceVertexUuid), eq(VERSION))).thenReturn(Either.left(serviceComponentMock));
- when(toscaOperationFacadeMock.getComponentByUuidAndVersion(eq(resourceVertexUuid), eq(VERSION))).thenReturn(Either.left(resourceComponentMock));
- when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents.get(0)));
- when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(resourceVertexUuid), any())).thenReturn(Either.left(resourceComponentMock));
- }
-
- @Test
- public void testGetExternalRefsForExistingComponentInstance() {
- String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- List<String> dto = response.readEntity(new GenericType<List<String>>() {
- });
- assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
- @Test
- public void testGetExternalRefsForAsset() {
- String path = String.format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION, MONITORING_OBJECT_TYPE);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() {
- });
- assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
- @Test
- public void testGetExternalRefsForAssetWithMissingEcompHeader() {
- String path = String.format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION, MONITORING_OBJECT_TYPE);
-
- //No X-Ecomp-Instance-ID header
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
- }
-
-
- @Test
- public void testAddExternalRefForResource(){
- String path = String.format("/v1/catalog/resources/%s/resourceInstances/%s/externalReferences/%s", resourceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- String getPath = String.format("/v1/catalog/resources/%s/version/%s/externalReferences/%s", resourceVertexUuid, VERSION, MONITORING_OBJECT_TYPE);
-
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(new ExternalRefDTO(REF_1)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
-
- //Check that GET will include the new reference
- response = target()
- .path(getPath)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, adminUser.getUserId())
- .get();
-
- Map<String, List<String>> dto = response.readEntity(new GenericType<Map<String, List<String>>>(){});
- assertThat(dto.get(COMPONENT_ID)).containsExactlyInAnyOrder(REF_1);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
- @Test
- public void testAddExternalRefForExistingComponentInstance() {
- String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(new ExternalRefDTO(REF_4)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
-
- //Check that GET will include the new reference
- response = target()
- .path(getPath)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, adminUser.getUserId())
- .get();
-
- List<String> dto = response.readEntity(new GenericType<List<String>>() {
- });
- assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
- @Test
- public void testDeleteExternalRefForExistingComponentInstance() {
- String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
- String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(deletePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
-
- //Verify that the deleted reference is returned in body
- ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
- assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
-
- //Check that GET will NOT include the deleted reference
- response = target()
- .path(getPath)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- List<String> getResponse = response.readEntity(new GenericType<List<String>>() {
- });
- assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
- @Test
- public void testUpdateExternalRefForExistingComponentInstance() {
- String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
- String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(updatePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .put(Entity.json(new ExternalRefDTO(REF_4)));
-
- //Verify that the updated reference is returned in body
- ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
- assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
-
- //Check that GET will include the updated reference
- response = target()
- .path(getPath)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
-
- List<String> dto = response.readEntity(new GenericType<List<String>>() {
- });
- assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
- }
-
-
- /*
- * Rainy Scenarios
- */
- @Test
- public void testAddExternalRefForNonExistingAssetId() {
- String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid", COMPONENT_ID, MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(new ExternalRefDTO(REF_4)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testAddExternalRefForNonExistingCompInstId() {
- String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(new ExternalRefDTO(REF_4)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testAddExistingExternalRef() {
- String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(new ExternalRefDTO(REF_1)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
- }
-
- @Test
- public void testUpdateExternalRefForNonExistingAssetId() {
- String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
-
- Response response = target()
- .path(updatePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .put(Entity.json(new ExternalRefDTO(REF_4)));
-
- //Verify that the 404 is returned
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
-
- }
-
- @Test
- public void testUpdateExternalRefForNonExistingObjectIdOrOldRef() {
- String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
-
- Response response = target()
- .path(updatePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .put(Entity.json(new ExternalRefDTO(REF_4)));
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testDeleteExternalRefForNonExistingAssetId() {
- String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
- Response response = target()
- .path(deletePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testDeleteExternalRefForNonExistingRef() {
- String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
- Response response = target()
- .path(deletePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .delete();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testGetExternalRefsForNonExistingAsset() {
- String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id", VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testGetExternalRefsForNonExistingVersion() {
- String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
- }
-
- @Test
- public void testDeleteExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
- String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, otherUser.getUserId())
- .delete();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
- }
-
- @Test
- public void testDeleteExternalRefForUserWhichIsNotCurrentUpdater() {
- String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
- Response response = target()
- .path(deletePath)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
- .header(Constants.USER_ID_HEADER, otherDesignerUser.getUserId())
- .delete();
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
- }
-
- @Override
- protected Application configure() {
- ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
- return new ResourceConfig(ExternalRefsServlet.class)
- .register(DefaultExceptionMapper.class)
- .register(ComponentExceptionMapper.class)
- .register(StorageExceptionMapper.class)
- .property("contextConfig", context);
- }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ServletUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ServletUtilsTest.java
index c998318..4334b49 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ServletUtilsTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ServletUtilsTest.java
@@ -7,9 +7,9 @@
* 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.
@@ -21,45 +21,51 @@
package org.openecomp.sdc.be.impl;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import com.google.gson.Gson;
-
-import mockit.Deencapsulation;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import com.google.gson.GsonBuilder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context-test.xml"})
public class ServletUtilsTest {
- @Autowired
- ServletUtils servletUtils;
- @Test
- public void testCtrServletUtils() {
- // default test
- assertThat(servletUtils)
- .isNotNull()
- .isInstanceOf(ServletUtils.class);
+ private ServletUtils servletUtils;
+ private ComponentsUtils componentsUtils;
+ private UserBusinessLogic userBusinessLogic;
+ private Gson gson;
- ComponentsUtils componentsUtils = Deencapsulation.getField(servletUtils, "componentsUtils");
- UserBusinessLogic userBusinessLogic = Deencapsulation.getField(servletUtils, "userAdmin");
- Gson gson = Deencapsulation.getField(servletUtils, "gson");
+ @BeforeEach
+ public void setup() {
+ servletUtils = mock(ServletUtils.class);
+ userBusinessLogic = mock(UserBusinessLogic.class);
+ componentsUtils = mock(ComponentsUtils.class);
+ gson = new GsonBuilder().setPrettyPrinting().create();
+ when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
+ when(servletUtils.getGson()).thenReturn(gson);
+ when(servletUtils.getUserAdmin()).thenReturn(userBusinessLogic);
+ }
- assertThat(gson)
- .isNotNull()
- .isInstanceOf(Gson.class)
- .isEqualTo(servletUtils.getGson());
- assertThat(componentsUtils)
- .isNotNull()
- .isInstanceOf(ComponentsUtils.class)
- .isEqualTo(servletUtils.getComponentsUtils());
- assertThat(userBusinessLogic)
- .isNotNull()
- .isInstanceOf(UserBusinessLogic.class)
- .isEqualTo(servletUtils.getUserAdmin());
- }
+ @Test
+ public void testCtrServletUtils() {
+ assertThat(servletUtils)
+ .isNotNull()
+ .isInstanceOf(ServletUtils.class);
+ assertThat(gson)
+ .isNotNull()
+ .isInstanceOf(Gson.class)
+ .isEqualTo(servletUtils.getGson());
+ assertThat(componentsUtils)
+ .isNotNull()
+ .isInstanceOf(ComponentsUtils.class)
+ .isEqualTo(servletUtils.getComponentsUtils());
+ assertThat(userBusinessLogic)
+ .isNotNull()
+ .isInstanceOf(UserBusinessLogic.class)
+ .isEqualTo(servletUtils.getUserAdmin());
+ }
}
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 d879b46..4359270 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,12 +22,33 @@
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.glassfish.jersey.test.TestProperties;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic;
@@ -89,27 +110,7 @@
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 {
+class ArchiveEndpointTest extends JerseyTest {
private static final ServletContext servletContext = mock(ServletContext.class);
private static final String CSAR_UUID1 = "123456789abcdefgh";
@@ -121,7 +122,7 @@
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 = mock(ToscaOperationFacade.class);
private static final ToscaOperationFacade toscaOperationFacade = Mockito.spy(new ToscaOperationFacade());
@@ -144,6 +145,7 @@
@Configuration
@PropertySource("classpath:dao.properties")
static class TestSpringConfig {
+
private ArchiveOperation archiveOperation;
private GraphVertex catalogVertex;
@@ -171,7 +173,8 @@
@Bean
ArchiveBusinessLogic archiveBusinessLogic() {
- return new ArchiveBusinessLogic(janusGraphDao(), accessValidations(), archiveOperation(), toscaOperationFacade(), componentUtils, catalogOperations);
+ return new ArchiveBusinessLogic(janusGraphDao(), accessValidations(), archiveOperation(),
+ toscaOperationFacade(), componentUtils, catalogOperations);
}
@Bean
@@ -249,7 +252,7 @@
}
@Bean
- HealingPipelineDao healingPipelineDao(){
+ HealingPipelineDao healingPipelineDao() {
return HEALING_PIPELINE_DAO;
}
@@ -271,7 +274,6 @@
//Create Service for Scenario 1 Tests (1 Service)
serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion());
-
Map<GraphPropertyEnum, Object> props = propsForHighestVersion();
props.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false);
props.put(GraphPropertyEnum.CSAR_UUID, CSAR_UUID1);
@@ -287,7 +289,7 @@
janusGraphDao.createEdge(catalogVertex, resourceVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
}
- private Map<GraphPropertyEnum, Object> propsForHighestVersion(){
+ private Map<GraphPropertyEnum, Object> propsForHighestVersion() {
Map<GraphPropertyEnum, Object> props = new HashMap<>();
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
return props;
@@ -297,22 +299,26 @@
public static final HttpServletRequest request = mock(HttpServletRequest.class);
/* Users */
- 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.TESTER.name(), System.currentTimeMillis());
+ 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.TESTER.name(),
+ System.currentTimeMillis());
- @BeforeClass
+ @BeforeAll
public static void setup() {
//Needed for User Authorization
//========================================================================================================================
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE), any())).thenReturn(invalidServiceStateResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE), any()))
+ .thenReturn(invalidServiceStateResponseFormat);
when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
ComponentException ce = new ByResponseFormatComponentException(responseFormat);
@@ -322,24 +328,29 @@
when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
when(invalidServiceStateResponseFormat.getStatus()).thenReturn(HttpStatus.CONFLICT.value());
when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
- when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any()))
+ .thenReturn(badRequestResponseFormat);
- when(graphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
+ when(graphLockOperation.lockComponent(anyString(), any(NodeTypeEnum.class)))
+ .thenReturn(StorageOperationStatus.OK);
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";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ 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);;
+ heatDeploymentArtifactTimeout.setDefaultMinutes(30);
+ ;
configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout);
configurationManager.setConfiguration(configuration);
@@ -347,13 +358,23 @@
ExternalConfiguration.setAppName("catalog-be");
}
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
@Test
- public void getArchivedComponents_Empty() {
+ void getArchivedComponents_Empty() {
assertOnGetArchivedComponents(null, 0);
}
@Test
- public void archiveAndGetArchivedService_SingleService() {
+ void archiveAndGetArchivedService_SingleService() {
Component serviceComponent = mock(Component.class);
final String serviceUniqueId = serviceVertex.getUniqueId();
when(toscaOperationFacade.getToscaElement(serviceUniqueId)).thenReturn(Either.left(serviceComponent));
@@ -364,7 +385,7 @@
}
@Test
- public void archiveAndGetArchivedResource_SingleResource() {
+ void archiveAndGetArchivedResource_SingleResource() {
Component component = mock(Component.class);
final String uniqueId = resourceVertex.getUniqueId();
when(toscaOperationFacade.getToscaElement(uniqueId)).thenReturn(Either.left(component));
@@ -375,40 +396,40 @@
}
@Test
- public void attemptArchiveCheckedOutService() {
+ void attemptArchiveCheckedOutService() {
checkoutComponent(serviceVertex);
archiveService(serviceVertex.getUniqueId(), HttpStatus.CONFLICT.value());
}
@Test
- public void testOnArchivedVsps(){
+ void testOnArchivedVsps() {
String path = "/v1/catalog/notif/vsp/archived";
List<String> csarIds = new LinkedList<>();
csarIds.add("123456");
csarIds.add(CSAR_UUID2); //An archived CSAR ID
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(csarIds));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(csarIds));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertOnVertexProp(resourceVertexVspArchived.getUniqueId(), true);
}
@Test
- public void testOnRestoredVsps(){
+ void testOnRestoredVsps() {
String path = "/v1/catalog/notif/vsp/restored";
List<String> csarIds = new LinkedList<>();
csarIds.add("123456");
csarIds.add(CSAR_UUID1); //Non archived CSAR_ID
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(csarIds));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(csarIds));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertOnVertexProp(resourceVertex.getUniqueId(), false);
@@ -418,24 +439,24 @@
* Rainy Scenarios
*/
@Test
- public void archiveWithInvalidUid() {
+ void archiveWithInvalidUid() {
archiveService("fakeUid", HttpStatus.NOT_FOUND.value());
}
@Test
- public void restoreWithInvalidUid() {
+ void restoreWithInvalidUid() {
restoreService("fakeUid", HttpStatus.NOT_FOUND.value());
}
@Test
- public void archiveWithTester() {
+ void archiveWithTester() {
String path = String.format("/v1/catalog/services/%s/%s", serviceVertex.getUniqueId(), "archive");
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, otherUser.getUserId())
- .post(null);
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, otherUser.getUserId())
+ .post(null);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
}
@@ -455,20 +476,30 @@
assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue);
}
- 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 archiveService(String id, int expectedStatus) {
+ archiveOrRestoreService(id, ArchiveOperation.Action.ARCHIVE, 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 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 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)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(null);
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(null);
assertThat(response.getStatus()).isEqualTo(expectedStatus);
}
@@ -476,11 +507,11 @@
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);
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(null);
assertThat(response.getStatus()).isEqualTo(expectedStatus);
}
@@ -489,13 +520,15 @@
String path = "/v1/catalog/archive";
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Map<String, List<CatalogComponent>> archivedComponents = response.readEntity(new GenericType<Map<String, List<CatalogComponent>>>() { });
+ Map<String, List<CatalogComponent>> archivedComponents = response
+ .readEntity(new GenericType<Map<String, List<CatalogComponent>>>() {
+ });
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
if (componentType == null) {
@@ -511,9 +544,9 @@
ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
forceSet(TestProperties.CONTAINER_PORT, "0");
return new ResourceConfig(ArchiveEndpoint.class)
- .register(DefaultExceptionMapper.class)
- .register(ComponentExceptionMapper.class)
- .register(StorageExceptionMapper.class)
- .property("contextConfig", context);
+ .register(DefaultExceptionMapper.class)
+ .register(ComponentExceptionMapper.class)
+ .register(StorageExceptionMapper.class)
+ .property("contextConfig", context);
}
}
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 91f9b5b..42ffa1a 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,15 +20,29 @@
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.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
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.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
@@ -64,22 +78,10 @@
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.List;
+class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest {
-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.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");
+ static ConfigurationSource configurationSource = new FSConfigurationSource(
+ ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
private static final String RESOURCE_ID_PREV = "prevVF";
@@ -128,12 +130,13 @@
@Bean
UpgradeBusinessLogic upgradeBusinessLogic() {
- return new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, userValidations, toscaOperationFacade, componentsUtils, upgradeOperation,
+ return new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, userValidations,
+ toscaOperationFacade, componentsUtils, upgradeOperation,
janusGraphDao);
}
}
- @BeforeClass
+ @BeforeAll
public static void initClass() {
lifecycleBusinessLogic = mock(LifecycleBusinessLogic.class);
componentInstanceBusinessLogic = mock(ComponentInstanceBusinessLogic.class);
@@ -145,8 +148,9 @@
user = mock(User.class);
}
- @Before
- public void init() {
+ @BeforeEach
+ public void init() throws Exception {
+ super.setUp();
prepareComponents();
when(userValidations.validateUserExists(eq(USER_ID))).thenReturn(user);
when(toscaOperationFacade.getToscaFullElement(eq(RESOURCE_ID_PREV))).thenReturn(Either.left(vfPrev));
@@ -155,20 +159,33 @@
when(toscaOperationFacade.getToscaFullElement(eq(SERVICE_ID_NEW))).thenReturn(Either.left(serviceNew));
Either<Service, ResponseFormat> fromLifeCycle = Either.left(serviceNew);
- doReturn(fromLifeCycle).when(lifecycleBusinessLogic).changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_PREV), any(User.class), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), eq(false),
+ doReturn(fromLifeCycle).when(lifecycleBusinessLogic)
+ .changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_PREV), any(User.class),
+ eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), eq(false),
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(istanceNew);
+ 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(istanceNew);
- doReturn(Either.left(serviceNewCheckIn)).when(lifecycleBusinessLogic).changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_NEW), any(User.class), eq(LifeCycleTransitionEnum.CHECKIN), any(LifecycleChangeInfoWithAction.class),
+ 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));
}
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected void configureClient(ClientConfig config) {
- final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
}
@@ -178,13 +195,14 @@
}
@Test
- public void upgradeVfInService_success() {
+ void upgradeVfInService_success() {
List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
UpgradeRequest request = new UpgradeRequest(SERVICE_ID_PREV);
inputsToUpdate.add(request);
Invocation.Builder builder = buildAutomatedUpgradeCall(RESOURCE_ID_NEW);
- UpgradeStatus status = builder.post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), UpgradeStatus.class);
+ UpgradeStatus status = builder
+ .post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), UpgradeStatus.class);
assertThat(status.getStatus()).isEqualTo(ActionStatus.OK);
List<ServiceInfo> expected = new ArrayList<>();
@@ -198,20 +216,25 @@
}
@Test
- public void upgradeVfInService_IdNotExist() {
+ void upgradeVfInService_IdNotExist() {
List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
UpgradeRequest request = new UpgradeRequest(SERVICE_ID_PREV);
inputsToUpdate.add(request);
String wrongId = "1234";
- when(toscaOperationFacade.getToscaFullElement(eq(wrongId))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
- String[] variables = { wrongId };
- ServiceException serviceException = new ServiceException("SVC4063", "Error: Requested '%1' resource was not found.", variables);
+ when(toscaOperationFacade.getToscaFullElement(eq(wrongId)))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND)))
+ .thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+ String[] variables = {wrongId};
+ ServiceException serviceException = new ServiceException("SVC4063",
+ "Error: Requested '%1' resource was not found.", variables);
ResponseFormat expected = new ResponseFormat(HttpStatus.NOT_FOUND.value());
expected.setServiceException(serviceException);
- when(componentsUtils.getResponseFormatByResource(eq(ActionStatus.RESOURCE_NOT_FOUND), eq(wrongId))).thenReturn(expected);
+ when(componentsUtils.getResponseFormatByResource(eq(ActionStatus.RESOURCE_NOT_FOUND), eq(wrongId)))
+ .thenReturn(expected);
- Response response = buildAutomatedUpgradeCall(wrongId).post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
+ Response response = buildAutomatedUpgradeCall(wrongId)
+ .post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
ResponseFormat actual = response.readEntity(ResponseFormat.class);
@@ -221,19 +244,24 @@
}
@Test
- public void upgradeVfInService_NotHihgestCertified() {
+ void upgradeVfInService_NotHihgestCertified() {
List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
UpgradeRequest request = new UpgradeRequest(RESOURCE_ID_PREV);
inputsToUpdate.add(request);
- when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
- String[] variables = { vfPrev.getName() };
- ServiceException serviceException = new ServiceException("SVC4699", "Error: Component %1 is not highest certified", variables);
+ when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND)))
+ .thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+ String[] variables = {vfPrev.getName()};
+ ServiceException serviceException = new ServiceException("SVC4699",
+ "Error: Component %1 is not highest certified", variables);
ResponseFormat expected = new ResponseFormat(HttpStatus.BAD_REQUEST.value());
expected.setServiceException(serviceException);
- when(componentsUtils.getResponseFormat(eq(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED), eq(vfPrev.getName()))).thenReturn(expected);
+ when(componentsUtils
+ .getResponseFormat(eq(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED), eq(vfPrev.getName())))
+ .thenReturn(expected);
- Response response = buildAutomatedUpgradeCall(RESOURCE_ID_PREV).post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
+ Response response = buildAutomatedUpgradeCall(RESOURCE_ID_PREV)
+ .post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
ResponseFormat actual = response.readEntity(ResponseFormat.class);
@@ -254,7 +282,8 @@
// }
private Invocation.Builder buildAutomatedUpgradeCall(String id) {
- return target("/v1/catalog/resources/{id}/automatedupgrade").resolveTemplate("id", id).request(MediaType.APPLICATION_JSON).header(Constants.USER_ID_HEADER, USER_ID);
+ return target("/v1/catalog/resources/{id}/automatedupgrade").resolveTemplate("id", id)
+ .request(MediaType.APPLICATION_JSON).header(Constants.USER_ID_HEADER, USER_ID);
}
private void prepareComponents() {
@@ -265,7 +294,7 @@
private void createService() {
servicePrev = createService("service1", SERVICE_ID_PREV, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
-
+
ComponentInstance ci = new ComponentInstance();
ci.setComponentUid(RESOURCE_ID_PREV);
ci.setName("inst 1");
@@ -277,7 +306,7 @@
serviceNew.setComponentInstances(resourceInstances);
serviceNewCheckIn = createService("service1", SERVICE_ID_NEW, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
-
+
serviceNewCheckIn.setComponentInstances(resourceInstances);
istanceNew = new ComponentInstance();
@@ -285,14 +314,15 @@
istanceNew.setName("inst 1");
serviceProxy = createService("serviceProxy", SERVICE_ID_PROXY, LifecycleStateEnum.CERTIFIED);
- serviceProxyContainerPrev = createService("serviceProxyContainer", SERVICE_ID_PROXY_PREV, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- serviceProxyContainerNew = createService("serviceProxyContainer", SERVICE_ID_PROXY_NEW, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
-
+ serviceProxyContainerPrev = createService("serviceProxyContainer", SERVICE_ID_PROXY_PREV,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ serviceProxyContainerNew = createService("serviceProxyContainer", SERVICE_ID_PROXY_NEW,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
}
- private Service createService(String name, String id, LifecycleStateEnum state){
+ private Service createService(String name, String id, LifecycleStateEnum state) {
Service service = new Service();
service.setName(name);
service.setUniqueId(id);
@@ -300,6 +330,7 @@
service.setHighestVersion(true);
return service;
}
+
private void createVF() {
vfPrev = new Resource();
vfPrev.setName("vf1");
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 b49ed17..abe2544 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
@@ -7,9 +7,9 @@
* 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.
@@ -39,7 +39,6 @@
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
-import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@@ -48,8 +47,10 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -86,7 +87,7 @@
/**
* The test suite designed for test functionality of ComponentInstanceServlet class
*/
-public class ComponentInstanceServletTest extends JerseyTest {
+class ComponentInstanceServletTest extends JerseyTest {
private final static String USER_ID = "jh0003";
private static HttpServletRequest request;
@@ -105,7 +106,7 @@
private static ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
private static ConfigurationManager configurationManager;
- @BeforeClass
+ @BeforeAll
public static void setup() {
createMocks();
stubMethods();
@@ -118,47 +119,61 @@
ExternalConfiguration.setAppName("catalog-be");
}
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
@Test
- public void testGetRelationByIdSuccess(){
+ void testGetRelationByIdSuccess() {
String containerComponentType = "resources";
String componentId = "componentId";
String relationId = "relationId";
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
- Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either.left(new RequirementCapabilityRelDef());
- when(componentInstanceBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse);
+ Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either
+ .left(new RequirementCapabilityRelDef());
+ when(componentInstanceBusinessLogic
+ .getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(successResponse);
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get( Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
}
@Test
- public void testGetRelationByIdFailure(){
+ void testGetRelationByIdFailure() {
String containerComponentType = "unknown_type";
String componentId = "componentId";
String relationId = "relationId";
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400);
- when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType)))
+ .thenReturn(responseFormat);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get( Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
- assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400);
+ assertEquals(HttpStatus.BAD_REQUEST_400, response.getStatus());
}
@Test
- public void testBatchDeleteResourceInstancesSuccess() {
+ void testBatchDeleteResourceInstancesSuccess() {
String componentId = "componentId";
String containerComponentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
@@ -179,23 +194,23 @@
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
Either<String[], ResponseFormat> convertStatusEither = Either.left(delCompIds);
when(componentsUtils
- .convertJsonToObjectUsingObjectMapper(anyString(), any(User.class), ArgumentMatchers.<Class<String[]>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(convertStatusEither);
+ .convertJsonToObjectUsingObjectMapper(anyString(), any(User.class), ArgumentMatchers.<Class<String[]>>any(),
+ nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(convertStatusEither);
when(componentInstanceBusinessLogic
- .batchDeleteComponentInstance(eq(containerComponentType), eq(componentId), any(List.class),
- eq(USER_ID))).thenReturn(Mockito.mock(Map.class));
+ .batchDeleteComponentInstance(eq(containerComponentType), eq(componentId), any(List.class),
+ eq(USER_ID))).thenReturn(Mockito.mock(Map.class));
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .post(Entity.json(compInsts));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.json(compInsts));
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
- public void testBatchDeleteResourceInstancesFailure() {
+ void testBatchDeleteResourceInstancesFailure() {
String componentId = "componentId";
String containerComponentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
@@ -205,16 +220,16 @@
when(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(responseFormat);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .post(Entity.json(""));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.json(""));
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, response.getStatus());
}
@Test
- public void testBatchDissociateRIFromRISuccess() {
+ void testBatchDissociateRIFromRISuccess() {
String componentId = "componentId";
String containerComponentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
@@ -227,24 +242,24 @@
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
Either<RequirementCapabilityRelDef[], ResponseFormat> convertReqEither = Either.left(refs);
when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<RequirementCapabilityRelDef[]>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(convertReqEither);
+ ArgumentMatchers.<Class<RequirementCapabilityRelDef[]>>any(),
+ nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(convertReqEither);
RequirementCapabilityRelDef actionResponseEither = ref;
when(componentInstanceBusinessLogic
- .dissociateRIFromRI(componentId, USER_ID, ref, ComponentTypeEnum.findByParamName(containerComponentType)))
- .thenReturn(actionResponseEither);
+ .dissociateRIFromRI(componentId, USER_ID, ref, ComponentTypeEnum.findByParamName(containerComponentType)))
+ .thenReturn(actionResponseEither);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .put(Entity.json(refs));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.json(refs));
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
- public void testBatchDissociateRIFromRIFailure() {
+ void testBatchDissociateRIFromRIFailure() {
String componentId = "componentId";
String containerComponentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
@@ -254,10 +269,10 @@
when(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(responseFormat);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .put(Entity.json(""));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.json(""));
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, response.getStatus());
}
@@ -267,21 +282,21 @@
forceSet(TestProperties.CONTAINER_PORT, "0");
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
return new ResourceConfig(ComponentInstanceServlet.class)
- .register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- bind(userBusinessLogic).to(UserBusinessLogic.class);
- bind(groupBusinessLogic).to(GroupBusinessLogic.class);
- bind(componentInstanceBusinessLogic).to(ComponentInstanceBusinessLogic.class);
- bind(componentsUtils).to(ComponentsUtils.class);
- bind(servletUtils).to(ServletUtils.class);
- bind(resourceImportManager).to(ResourceImportManager.class);
- bind(serviceBusinessLogic).to(ServiceBusinessLogic.class);
- bind(componentNodeFilterBusinessLogic).to(ComponentNodeFilterBusinessLogic.class);
- }
- })
- .property("contextConfig", context);
+ .register(new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ bind(userBusinessLogic).to(UserBusinessLogic.class);
+ bind(groupBusinessLogic).to(GroupBusinessLogic.class);
+ bind(componentInstanceBusinessLogic).to(ComponentInstanceBusinessLogic.class);
+ bind(componentsUtils).to(ComponentsUtils.class);
+ bind(servletUtils).to(ServletUtils.class);
+ bind(resourceImportManager).to(ResourceImportManager.class);
+ bind(serviceBusinessLogic).to(ServiceBusinessLogic.class);
+ bind(componentNodeFilterBusinessLogic).to(ComponentNodeFilterBusinessLogic.class);
+ }
+ })
+ .property("contextConfig", context);
}
private static void createMocks() {
@@ -304,21 +319,23 @@
private static void stubMethods() {
when(request.getSession()).thenReturn(session);
when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(ComponentInstanceBusinessLogic.class)).thenReturn(componentInstanceBusinessLogic);
+ when(webApplicationContext.getBean(ComponentInstanceBusinessLogic.class))
+ .thenReturn(componentInstanceBusinessLogic);
when(request.getHeader("USER_ID")).thenReturn(USER_ID);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
}
@Test
- public void testUpdateResourceInstancePropertiesSuccess(){
+ void testUpdateResourceInstancePropertiesSuccess() {
String containerComponentType = "services";
String componentId = "componentId";
String resourceInstanceId = "resourceInstanceId";
- ComponentInstanceProperty [] properties = new ComponentInstanceProperty[1];
+ ComponentInstanceProperty[] properties = new ComponentInstanceProperty[1];
ComponentInstanceProperty property = new ComponentInstanceProperty();
property.setName("property");
property.setValue("value");
@@ -332,22 +349,25 @@
e.printStackTrace();
}
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" +
- resourceInstanceId + "/properties";
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(propertyJson, new User(), ComponentInstanceProperty[].class,
+ 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(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));
+ .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(){
+ void testUpdateResourceInstanceInputsSuccess() {
String containerComponentType = "services";
String componentId = "componentId";
@@ -366,27 +386,29 @@
e.printStackTrace();
}
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" +
- resourceInstanceId + "/inputs";
+ 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)));
+ 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));
+ .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(){
+ void testUpdateResourceInstancePropertiesFailure() {
String containerComponentType = "services";
String componentId = "componentId";
String resourceInstanceId = "resourceInstanceId";
- ComponentInstanceProperty [] properties = new ComponentInstanceProperty[1];
+ ComponentInstanceProperty[] properties = new ComponentInstanceProperty[1];
ComponentInstanceProperty property = new ComponentInstanceProperty();
property.setName("property");
property.setValue("value");
@@ -400,28 +422,30 @@
e.printStackTrace();
}
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" +
- resourceInstanceId + "/properties";
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(propertyJson, new User(), ComponentInstanceProperty[].class,
+ 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)),
+ 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)));
+ .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));
+ .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(){
+ void testUpdateResourceInstanceInputsFailure() {
String containerComponentType = "services";
String componentId = "componentId";
String resourceInstanceId = "resourceInstanceId";
- ComponentInstanceInput [] inputs = new ComponentInstanceInput[1];
+ ComponentInstanceInput[] inputs = new ComponentInstanceInput[1];
ComponentInstanceInput input = new ComponentInstanceInput();
input.setName("input");
input.setValue("value");
@@ -435,23 +459,24 @@
e.printStackTrace();
}
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/resourceInstance" + "/" +
- resourceInstanceId + "/inputs";
+ 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)),
+ 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)));
+ .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));
+ .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);
}
-
+
@Test
- public void testUpdateInstanceRequirement(){
+ void testUpdateInstanceRequirement() {
String containerComponentType = "services";
String componentId = "componentId";
@@ -467,19 +492,21 @@
e.printStackTrace();
}
String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/componentInstances/" +
- componentInstanceId + "/requirement/" + capabilityType + "/requirementName/" + requirementName;
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(eq(requirementJson), any(User.class), eq(RequirementDefinition.class),
- eq(AuditingActionEnum.GET_TOSCA_MODEL), eq(ComponentTypeEnum.SERVICE))).thenReturn(Either.left(requirementDefinition));
+ componentInstanceId + "/requirement/" + capabilityType + "/requirementName/" + requirementName;
+ when(componentsUtils
+ .convertJsonToObjectUsingObjectMapper(eq(requirementJson), any(User.class), eq(RequirementDefinition.class),
+ eq(AuditingActionEnum.GET_TOSCA_MODEL), eq(ComponentTypeEnum.SERVICE)))
+ .thenReturn(Either.left(requirementDefinition));
when(componentInstanceBusinessLogic.updateInstanceRequirement(ComponentTypeEnum.SERVICE,
- componentId, componentInstanceId, capabilityType, requirementName, requirementDefinition, USER_ID))
- .thenReturn(Either.left(requirementDefinition));
+ componentId, componentInstanceId, capabilityType, requirementName, requirementDefinition, USER_ID))
+ .thenReturn(Either.left(requirementDefinition));
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID).put(Entity.entity(requirementDefinition, MediaType.APPLICATION_JSON));
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID).put(Entity.entity(requirementDefinition, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
}
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServletTest.java
index 7674ea9..fac1586 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServletTest.java
@@ -25,9 +25,9 @@
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -35,12 +35,8 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import fj.data.Either;
import java.util.Arrays;
-import java.util.Collections;
import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
import java.util.Optional;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -53,18 +49,24 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentNodeFilterBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceImportManager;
import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction;
import org.openecomp.sdc.be.components.validation.UserValidations;
-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;
@@ -79,12 +81,11 @@
import org.openecomp.sdc.be.impl.ServletUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.ui.model.UIConstraint;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
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;
@@ -92,7 +93,10 @@
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-public class ComponentNodeFilterServletTest extends JerseyTest {
+@ExtendWith(MockitoExtension.class)
+@TestInstance(Lifecycle.PER_CLASS)
+class ComponentNodeFilterServletTest extends JerseyTest {
+
private static final String USER_ID = "jh0003";
private static final String servicePropertyName = "resourceType";
private static final String constraintOperator = "equal";
@@ -103,30 +107,47 @@
private static final String componentInstance = "dac65869-dfb4-40d2-aa20-084324659ec1.resource0";
private static final String componentType = "resources";
private static final String capabilityName = "MyCapabilityName";
+ private static final String V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ private static final String V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ private final UIConstraint uiConstraint = new UIConstraint("resourceType", "equal", "static", "static", "resourceTypeValue");
+ private final String constraint = new ConstraintConvertor().convert(uiConstraint);
+ private final String inputJson = buildConstraintDataJson(uiConstraint);
+ private final User user = new User("", "", USER_ID, "", Role.ADMIN.name(), null);
+ @Mock
+ private HttpServletRequest request;
+ @Mock
+ private HttpSession session;
+ @Mock
+ private ServletContext servletContext;
+ @Mock
+ private WebAppContextWrapper webAppContextWrapper;
+ @Mock
+ private WebApplicationContext webApplicationContext;
+ @Mock
+ private UserBusinessLogic userBusinessLogic;
+ @Mock
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private ServletUtils servletUtils;
+ @Mock
+ private ResourceImportManager resourceImportManager;
+ @Mock
+ private ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
+ @Mock
+ private ResponseFormat responseFormat;
+ @Mock
+ private UserValidations userValidations;
- private static HttpServletRequest request;
- private static HttpSession session;
- private static ServletContext servletContext;
- private static WebAppContextWrapper webAppContextWrapper;
- private static WebApplicationContext webApplicationContext;
- private static UserBusinessLogic userBusinessLogic;
- private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- private static ComponentsUtils componentsUtils;
- private static ServletUtils servletUtils;
- private static ResourceImportManager resourceImportManager;
- private static ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
- private static ResponseFormat responseFormat;
- private static UserValidations userValidations;
- private static ConfigurationManager configurationManager;
private CINodeFilterDataDefinition ciNodeFilterDataDefinition;
- private UIConstraint uiConstraint;
- private String constraint;
- private String inputJson;
- private User user;
+
+ public ComponentNodeFilterServletTest() throws JsonProcessingException {
+ }
@BeforeAll
- public static void initClass() {
- createMocks();
+ public void initClass() {
+ MockitoAnnotations.initMocks(this);
when(request.getSession()).thenReturn(session);
when(session.getServletContext()).thenReturn(servletContext);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
@@ -135,10 +156,10 @@
when(request.getHeader("USER_ID")).thenReturn(USER_ID);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- configurationManager = new ConfigurationManager(configurationSource);
- org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration();
+ final String appConfigDir = "src/test/resources/config/catalog-be";
+ final ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ final ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ final org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration();
configuration.setJanusGraphInMemoryGraph(true);
configurationManager.setConfiguration(configuration);
ExternalConfiguration.setAppName("catalog-be");
@@ -147,7 +168,6 @@
@BeforeEach
public void resetMock() throws Exception {
super.setUp();
- reset(componentNodeFilterBusinessLogic);
}
@AfterEach
@@ -156,17 +176,16 @@
}
@Test
- public void addNodeFilterPropertiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ void addNodeFilterPropertiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME);
- when(userValidations.validateUserExists(user)).thenReturn(user);
- when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
+ doReturn(user).when(componentNodeFilterBusinessLogic).validateUser(USER_ID);
+ doReturn(HttpStatus.OK_200).when(responseFormat).getStatus();
+ doReturn(responseFormat).when(componentsUtils).getResponseFormat(ActionStatus.OK);
+ doReturn(componentsUtils).when(servletUtils).getComponentsUtils();
assertNotNull(uiConstraint);
assertThat(servicePropertyName).isEqualToIgnoringCase(uiConstraint.getServicePropertyName());
assertThat(constraintOperator).isEqualToIgnoringCase(uiConstraint.getConstraintOperator());
@@ -174,18 +193,18 @@
assertThat(sourceName).isEqualToIgnoringCase(uiConstraint.getSourceName());
assertThat(propertyValue).isEqualToIgnoringCase(uiConstraint.getValue().toString());
- when(componentsUtils.parseToConstraint(anyString(), any(User.class), ArgumentMatchers.any(ComponentTypeEnum.class)))
- .thenReturn(Optional.of(uiConstraint));
+ doReturn(Optional.of(uiConstraint)).when(componentsUtils)
+ .parseToConstraint(anyString(), any(User.class), ArgumentMatchers.any(ComponentTypeEnum.class));
assertNotNull(constraint);
assertNotNull(ciNodeFilterDataDefinition);
assertThat(ciNodeFilterDataDefinition.getProperties().getListToscaDataDefinition()).hasSize(1);
assertThat("resourceType: {equal: resourceTypeValue}\n").isEqualToIgnoringCase(constraint);
- when(componentNodeFilterBusinessLogic
+
+ doReturn(Optional.of(ciNodeFilterDataDefinition)).when(componentNodeFilterBusinessLogic)
.addNodeFilter(componentId, componentInstance, NodeFilterConstraintAction.ADD,
uiConstraint.getServicePropertyName(), constraint, true, ComponentTypeEnum.RESOURCE,
- NodeFilterConstraintType.PROPERTIES, ""))
- .thenReturn(Optional.of(ciNodeFilterDataDefinition));
+ NodeFilterConstraintType.PROPERTIES, "");
final Response response = target()
.path(path)
@@ -199,24 +218,26 @@
ArgumentMatchers.any(NodeFilterConstraintType.class), anyString());
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void addNodeFilterCapabilitiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ void addNodeFilterCapabilitiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.CAPABILITIES_PARAM_NAME);
-
- final UIConstraint uiConstraint1 = uiConstraint;
- when(userValidations.validateUserExists(user)).thenReturn(user);
+ final UIConstraint uiConstraint1 = new UIConstraint(uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator(),
+ uiConstraint.getSourceType(), uiConstraint.getSourceName(), uiConstraint.getValue());
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
- when(componentsUtils.parseToConstraint(anyString(), any(User.class),ArgumentMatchers.any(ComponentTypeEnum.class)))
- .thenReturn(Optional.of(uiConstraint));
-
+ doReturn(componentsUtils).when(servletUtils).getComponentsUtils();
uiConstraint1.setCapabilityName(capabilityName);
+
+ when(componentsUtils.parseToConstraint(anyString(), any(User.class), ArgumentMatchers.any(ComponentTypeEnum.class)))
+ .thenReturn(Optional.of(uiConstraint1));
+
assertThat(ciNodeFilterDataDefinition.getProperties().getListToscaDataDefinition()).hasSize(1);
when(componentNodeFilterBusinessLogic
.addNodeFilter(componentId, componentInstance, NodeFilterConstraintAction.ADD,
@@ -236,29 +257,17 @@
ArgumentMatchers.any(NodeFilterConstraintType.class), anyString());
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void addNodeFilterFailTest() throws BusinessLogicException, JsonProcessingException {
+ void addNodeFilterFailTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR_500);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<UIConstraint>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class))).thenReturn(Either.left(uiConstraint));
-
- when(componentNodeFilterBusinessLogic
- .addNodeFilter(componentId, componentInstance, NodeFilterConstraintAction.ADD,
- uiConstraint.getServicePropertyName(), constraint, true, ComponentTypeEnum.RESOURCE,
- NodeFilterConstraintType.PROPERTIES, ""))
- .thenReturn(Optional.empty());
final Response response = target()
.path(path)
@@ -267,25 +276,17 @@
.post(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void addNodeFilterFailConstraintParseTest() throws JsonProcessingException {
+ void addNodeFilterFailConstraintParseTest() throws JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance, NodeFilterConstraintType.PROPERTIES_PARAM_NAME);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR_500);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<UIConstraint>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class)))
- .thenReturn(Either.right(new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR_500)));
-
final Response response = target()
.path(path)
.request(MediaType.APPLICATION_JSON)
@@ -293,26 +294,18 @@
.post(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void addNodeFilterFailConvertTest() throws JsonProcessingException {
+ void addNodeFilterFailConvertTest() throws JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES.getType());
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR_500);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<UIConstraint>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class)))
- .thenReturn(Either.left(null));
-
final Response response = target()
.path(path)
.request(MediaType.APPLICATION_JSON)
@@ -320,26 +313,23 @@
.post(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void updateNodeFilterPropertiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ void updateNodeFilterPropertiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<List>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class)))
- .thenReturn(Either.left(Arrays.asList(new ObjectMapper().convertValue(uiConstraint, Map.class))));
-
+ doReturn(componentsUtils).when(servletUtils).getComponentsUtils();
+ doReturn(Optional.of(uiConstraint)).when(componentsUtils)
+ .parseToConstraint(anyString(), any(User.class), eq(ComponentTypeEnum.RESOURCE));
when(componentNodeFilterBusinessLogic
.updateNodeFilter(componentId, componentInstance, uiConstraint, ComponentTypeEnum.RESOURCE,
NodeFilterConstraintType.PROPERTIES, 0)).thenReturn(Optional.of(ciNodeFilterDataDefinition));
@@ -349,49 +339,25 @@
.header(USER_ID_HEADER, USER_ID)
.put(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
- verify(componentNodeFilterBusinessLogic, times(1))
- .updateNodeFilter(anyString(), anyString(), ArgumentMatchers.any(UIConstraint.class),
- ArgumentMatchers.any(ComponentTypeEnum.class), ArgumentMatchers.any(NodeFilterConstraintType.class),
- anyInt());
-
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void updateNodeFilterCapabilitiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ void updateNodeFilterCapabilitiesSuccessTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.CAPABILITIES_PARAM_NAME, 0);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
when(componentsUtils.parseToConstraint(anyString(), any(User.class), ArgumentMatchers.any(ComponentTypeEnum.class)))
.thenReturn(Optional.of(uiConstraint));
-
+ doReturn(componentsUtils).when(servletUtils).getComponentsUtils();
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
- when(componentsUtils.validateAndParseConstraint(ArgumentMatchers.any(ComponentTypeEnum.class), anyString(), any(User.class)))
- .thenReturn(Collections.singletonList(uiConstraint));
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<List>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class)))
- .thenReturn(Either.left(Arrays.asList(new ObjectMapper().convertValue(uiConstraint, Map.class))));
-
- when(componentNodeFilterBusinessLogic.deleteNodeFilter(componentId, componentInstance,
- NodeFilterConstraintAction.DELETE, null, 0, true, ComponentTypeEnum.RESOURCE,
- NodeFilterConstraintType.PROPERTIES))
- .thenReturn(Optional.of(ciNodeFilterDataDefinition));
-
- when(componentNodeFilterBusinessLogic
- .addNodeFilter(componentId, componentInstance, NodeFilterConstraintAction.ADD,
- uiConstraint.getServicePropertyName(), constraint, true, ComponentTypeEnum.RESOURCE,
- NodeFilterConstraintType.PROPERTIES, ""))
- .thenReturn(Optional.of(ciNodeFilterDataDefinition));
-
when(componentNodeFilterBusinessLogic
.updateNodeFilter(componentId, componentInstance, uiConstraint,
ComponentTypeEnum.RESOURCE, NodeFilterConstraintType.CAPABILITIES, 0))
@@ -409,55 +375,18 @@
anyInt());
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void updateNodeFilterFailTest() throws BusinessLogicException, JsonProcessingException {
+ void updateNodeFilterFailTest() throws BusinessLogicException, JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.validateAndParseConstraint(ArgumentMatchers.any(ComponentTypeEnum.class), anyString(), any(User.class)))
- .thenReturn(Collections.singletonList(uiConstraint));
-
- when(componentNodeFilterBusinessLogic
- .updateNodeFilter(componentId, componentInstance, uiConstraint,
- ComponentTypeEnum.RESOURCE, NodeFilterConstraintType.PROPERTIES, 0))
- .thenReturn(Optional.empty());
- final Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header(USER_ID_HEADER, USER_ID)
- .put(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
-
- verify(componentNodeFilterBusinessLogic, times(1))
- .updateNodeFilter(anyString(), anyString(), ArgumentMatchers.any(UIConstraint.class),
- ArgumentMatchers.any(ComponentTypeEnum.class), ArgumentMatchers.any(NodeFilterConstraintType.class),
- anyInt());
-
- assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
- }
-
- @Test
- public void updateNodeFilterFailConstraintParseTest() throws JsonProcessingException {
- initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
- final String path = String.format(pathFormat, componentType, componentId, componentInstance,
- NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
-
- when(userValidations.validateUserExists(user)).thenReturn(user);
- when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.validateAndParseConstraint(ArgumentMatchers.any(ComponentTypeEnum.class), anyString(), any(User.class)))
- .thenReturn(Collections.emptyList());
-
final Response response = target()
.path(path)
.request(MediaType.APPLICATION_JSON)
@@ -465,23 +394,17 @@
.put(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void updateNodeFilterFailConvertTest() throws JsonProcessingException {
+ void updateNodeFilterFailConstraintParseTest() throws JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
-
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(anyString(), any(User.class),
- ArgumentMatchers.<Class<List>>any(),
- nullable(AuditingActionEnum.class), nullable(ComponentTypeEnum.class)))
- .thenReturn(Either.left(null));
final Response response = target()
.path(path)
@@ -490,18 +413,37 @@
.put(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void deleteNodeFilterSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ void updateNodeFilterFailConvertTest() throws JsonProcessingException {
initComponentData();
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
- when(userValidations.validateUserExists(user)).thenReturn(user);
when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
+ final Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header(USER_ID_HEADER, USER_ID)
+ .put(Entity.entity(inputJson, MediaType.APPLICATION_JSON));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
+ }
+
+ @Test
+ void deleteNodeFilterSuccessTest() throws BusinessLogicException, JsonProcessingException {
+ initComponentData();
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
+ final String path = String.format(pathFormat, componentType, componentId, componentInstance,
+ NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
+
+ when(componentNodeFilterBusinessLogic.validateUser(USER_ID)).thenReturn(user);
+ doReturn(componentsUtils).when(servletUtils).getComponentsUtils();
when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
@@ -523,11 +465,12 @@
ArgumentMatchers.any(NodeFilterConstraintType.class));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
+ verify(componentNodeFilterBusinessLogic,times(1)).validateUser(USER_ID);
}
@Test
- public void deleteNodeFilterFailTest() {
- final String pathFormat = "/v1/catalog/%s/%s/componentInstance/%s/%s/%s/nodeFilter";
+ void deleteNodeFilterFailTest() {
+ final String pathFormat = V_1_CATALOG_S_S_COMPONENT_INSTANCE_S_S_S_NODE_FILTER;
final String path = String.format(pathFormat, componentType, componentId, componentInstance,
NodeFilterConstraintType.PROPERTIES_PARAM_NAME, 0);
final Response response = target()
@@ -540,23 +483,6 @@
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
}
- private static void createMocks() {
- request = mock(HttpServletRequest.class);
- userBusinessLogic = mock(UserBusinessLogic.class);
- componentInstanceBusinessLogic = mock(ComponentInstanceBusinessLogic.class);
- componentsUtils = mock(ComponentsUtils.class);
- servletUtils = mock(ServletUtils.class);
- resourceImportManager = mock(ResourceImportManager.class);
- componentNodeFilterBusinessLogic = mock(ComponentNodeFilterBusinessLogic.class);
-
- session = mock(HttpSession.class);
- servletContext = mock(ServletContext.class);
- webAppContextWrapper = mock(WebAppContextWrapper.class);
- webApplicationContext = mock(WebApplicationContext.class);
- responseFormat = mock(ResponseFormat.class);
- userValidations = mock(UserValidations.class);
- }
-
@Override
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
@@ -578,10 +504,6 @@
}
private void initComponentData() throws JsonProcessingException {
- uiConstraint = new UIConstraint("resourceType", "equal", "static", "static", "resourceTypeValue");
- constraint = new ConstraintConvertor().convert(uiConstraint);
- inputJson = buildConstraintDataJson(uiConstraint);
-
final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition =
new RequirementNodeFilterPropertyDataDefinition();
requirementNodeFilterPropertyDataDefinition.setName(uiConstraint.getServicePropertyName());
@@ -603,9 +525,6 @@
ciNodeFilterDataDefinition.setCapabilities(capabilityDataDefinitionList);
ciNodeFilterDataDefinition.setID("NODE_FILTER_UID");
- user = new User();
- user.setUserId(USER_ID);
- user.setRole(Role.ADMIN.name());
}
private String buildConstraintDataJson(final UIConstraint uiConstraint) throws JsonProcessingException {
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 5b2c9cb..e455896 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,17 +20,24 @@
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 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;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -41,16 +48,9 @@
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;
+@ExtendWith(MockitoExtension.class)
+class ComponentPropertyServletTest extends JerseySpringBaseTest {
-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
private static HttpSession session;
@Mock
@@ -73,32 +73,35 @@
private static final String INVALID_PROPERTY_NAME = "invalid_name_$.&";
private static final String STRING_TYPE = "string";
- @Before
- public void initClass() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
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);
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
}
@Test
- public void testCreatePropertyOnService_success() {
+ void testCreatePropertyOnService_success() {
PropertyDefinition property = new PropertyDefinition();
property.setName(VALID_PROPERTY_NAME);
property.setType(STRING_TYPE);
EntryData<String, PropertyDefinition> propertyEntry = new EntryData<>(VALID_PROPERTY_NAME, property);
- when(propertyBl.addPropertyToComponent(eq(SERVICE_ID), any(), any(), any())).thenReturn(Either.left(propertyEntry));
+ when(propertyBl.addPropertyToComponent(eq(SERVICE_ID), any(), any(), any()))
+ .thenReturn(Either.left(propertyEntry));
Response propertyInService =
- componentPropertyServlet.createPropertyInService(SERVICE_ID, getValidProperty(), request, USER_ID);
+ componentPropertyServlet.createPropertyInService(SERVICE_ID, getValidProperty(), request, USER_ID);
Assert.assertEquals(HttpStatus.OK_200.getStatusCode(), propertyInService.getStatus());
}
@Test
- public void testCreatePropertyInvalidName_failure() {
+ void testCreatePropertyInvalidName_failure() {
PropertyDefinition property = new PropertyDefinition();
property.setName(INVALID_PROPERTY_NAME);
property.setType(STRING_TYPE);
@@ -107,38 +110,41 @@
responseFormat.setStatus(HttpStatus.BAD_REQUEST_400.getStatusCode());
when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_PROPERTY_NAME))).thenReturn(responseFormat);
-
+ 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);
Response propertyInService =
- componentPropertyServlet.createPropertyInService(SERVICE_ID, getInvalidProperty(), request, USER_ID);
+ componentPropertyServlet.createPropertyInService(SERVICE_ID, getInvalidProperty(), request, USER_ID);
Assert.assertEquals(HttpStatus.BAD_REQUEST_400.getStatusCode(), propertyInService.getStatus());
}
private String getValidProperty() {
return "{\n"
- + " \"valid_name_123\": {\n"
- + " \"schema\": {\n"
- + " \"property\": {\n"
- + " \"type\": \"\"\n"
- + " }\n" + " },\n"
- + " \"type\": \"string\",\n"
- + " \"name\": \"valid_name_123\"\n"
- + " }\n"
- + "}";
+ + " \"valid_name_123\": {\n"
+ + " \"schema\": {\n"
+ + " \"property\": {\n"
+ + " \"type\": \"\"\n"
+ + " }\n" + " },\n"
+ + " \"type\": \"string\",\n"
+ + " \"name\": \"valid_name_123\"\n"
+ + " }\n"
+ + "}";
}
private String getInvalidProperty() {
return "{\n"
- + " \"invalid_name_$.&\": {\n"
- + " \"schema\": {\n"
- + " \"property\": {\n"
- + " \"type\": \"\"\n"
- + " }\n" + " },\n"
- + " \"type\": \"string\",\n"
- + " \"name\": \"invalid_name_$.&\"\n"
- + " }\n"
- + "}";
+ + " \"invalid_name_$.&\": {\n"
+ + " \"schema\": {\n"
+ + " \"property\": {\n"
+ + " \"type\": \"\"\n"
+ + " }\n" + " },\n"
+ + " \"type\": \"string\",\n"
+ + " \"name\": \"invalid_name_$.&\"\n"
+ + " }\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 77b90ad..2b0ffe9 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,13 +20,25 @@
package org.openecomp.sdc.be.servlets;
+import static java.util.Arrays.asList;
+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 fj.data.Either;
+import java.util.Collections;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
import org.json.JSONArray;
import org.json.JSONObject;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
@@ -37,19 +49,7 @@
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Collections;
-
-import static java.util.Arrays.asList;
-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;
-
-public class ComponentServletTest extends JerseySpringBaseTest{
+class ComponentServletTest extends JerseySpringBaseTest {
private static final String USER_ID = "userId";
private static final String RESOURCE_ID = "resourceId";
@@ -57,39 +57,47 @@
private PolicyDefinition policy1, policy2;
@Override
- @Before
+ @BeforeEach
public void setUp() throws Exception {
super.setUp();
policy1 = buildPolicy("p1");
policy2 = buildPolicy("p2");
}
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
resourceBusinessLogic = mock(ResourceBusinessLogic.class);
UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class);
ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
- ComponentServlet componentServlet = new ComponentServlet(userBusinessLogic, componentsUtils, new ComponentBusinessLogicProvider(resourceBusinessLogic, null, null));
+ ComponentServlet componentServlet = new ComponentServlet(userBusinessLogic, componentsUtils,
+ new ComponentBusinessLogicProvider(resourceBusinessLogic, null, null));
return super.configure().register(componentServlet);
}
@Test
- public void filterDataByParam_getPolicies_returnOnlyNameTargetsAndIdFields() {
+ void filterDataByParam_getPolicies_returnOnlyNameTargetsAndIdFields() {
UiComponentDataTransfer dataTransfer = buildDataTransferWithPolicies();
- when(resourceBusinessLogic.getComponentDataFilteredByParams(eq(RESOURCE_ID.toLowerCase()), any(User.class), eq(Collections.singletonList("policies")))).thenReturn(Either.left(dataTransfer));
+ when(resourceBusinessLogic.getComponentDataFilteredByParams(eq(RESOURCE_ID.toLowerCase()), any(User.class),
+ eq(Collections.singletonList("policies")))).thenReturn(Either.left(dataTransfer));
UiComponentDataTransfer uiComponentDataTransfer = buildGetPolicyTypesCall().get(UiComponentDataTransfer.class);
assertThat(uiComponentDataTransfer.getPolicies())
- .usingElementComparatorOnFields("name", "uniqueId", "targets")
- .containsExactlyInAnyOrder(policy1, policy2)
- .extracting("properties")//properties is not returned in the response
- .containsExactly(null, null);
+ .usingElementComparatorOnFields("name", "uniqueId", "targets")
+ .containsExactlyInAnyOrder(policy1, policy2)
+ .extracting("properties")//properties is not returned in the response
+ .containsExactly(null, null);
}
@Test
- public void filterDataByParam_getPolicies_policyTypeNameFieldShouldReturnAsType() {
+ void filterDataByParam_getPolicies_policyTypeNameFieldShouldReturnAsType() {
UiComponentDataTransfer dataTransfer = buildDataTransferWithPolicies();
- when(resourceBusinessLogic.getComponentDataFilteredByParams(eq(RESOURCE_ID.toLowerCase()), any(User.class), eq(Collections.singletonList("policies")))).thenReturn(Either.left(dataTransfer));
+ when(resourceBusinessLogic.getComponentDataFilteredByParams(eq(RESOURCE_ID.toLowerCase()), any(User.class),
+ eq(Collections.singletonList("policies")))).thenReturn(Either.left(dataTransfer));
Response uiComponentDataTransfer = buildGetPolicyTypesCall().get();
verifyPolicyTypeFieldUsingJsonResponse(uiComponentDataTransfer);
}
@@ -112,22 +120,22 @@
private PolicyDefinition buildPolicy(String id) {
return PolicyDefinitionBuilder.create()
- .setUniqueId(id)
- .setName("name" + id)
- .setType("type" + id)
- .addGroupTarget("group1")
- .addGroupTarget("group2")
- .addComponentInstanceTarget("inst1")
- .addComponentInstanceTarget("inst2")
- .addProperty("prop1")
- .build();
+ .setUniqueId(id)
+ .setName("name" + id)
+ .setType("type" + id)
+ .addGroupTarget("group1")
+ .addGroupTarget("group2")
+ .addComponentInstanceTarget("inst1")
+ .addComponentInstanceTarget("inst2")
+ .addProperty("prop1")
+ .build();
}
private Invocation.Builder buildGetPolicyTypesCall() {
return target("/v1/catalog/resources/{id}/filteredDataByParams")
- .queryParam("include", "policies")
- .resolveTemplate("id", RESOURCE_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .queryParam("include", "policies")
+ .resolveTemplate("id", RESOURCE_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
}
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 af7199c..cd8c0c5 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,16 +22,34 @@
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.eq;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+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 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;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -70,1002 +88,1020 @@
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.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+class ElementServletTest extends JerseyTest {
-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.reset;
-import static org.mockito.Mockito.when;
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ 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);
+ public static final ArtifactsBusinessLogic artifactsBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
-public class ElementServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- 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);
- public static final ArtifactsBusinessLogic artifactsBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
+ private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
+ private static final ComponentsCleanBusinessLogic componentsCleanBusinessLogic = Mockito
+ .mock(ComponentsCleanBusinessLogic.class);
+ private static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
- private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
- private static final ComponentsCleanBusinessLogic componentsCleanBusinessLogic = Mockito.mock(ComponentsCleanBusinessLogic.class);
- private static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
+ private static final ResponseFormat okResponseFormat = new ResponseFormat(HttpStatus.SC_OK);
+ private static final ResponseFormat conflictResponseFormat = new ResponseFormat(HttpStatus.SC_CONFLICT);
+ private static final ResponseFormat generalErrorResponseFormat = new ResponseFormat(
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ private static final ResponseFormat createdResponseFormat = new ResponseFormat(HttpStatus.SC_CREATED);
+ private static final ResponseFormat noContentResponseFormat = new ResponseFormat(HttpStatus.SC_NO_CONTENT);
+ private static final ResponseFormat unauthorizedResponseFormat = Mockito.mock(ResponseFormat.class);
+ private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class);
+ private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class);
+ private static final String EMPTY_JSON = "{}";
+ private static final String COMPONENT_TYPE = "componentType";
+ private static final String CATEGORY_UNIQUE_ID = "categoryUniqueId";
+ private static final String CATEGORY_ID = "categoryId";
+ private static final String SUB_CATEGORY_UNIQUE_ID = "subCategoryUniqueId";
+ private static final String SUB_CATEGORY_ID = "subCategoryId";
+ private static final String GROUPING_UNIQUE_ID = "groupingUniqueId";
- private static final ResponseFormat okResponseFormat = new ResponseFormat(HttpStatus.SC_OK);
- private static final ResponseFormat conflictResponseFormat = new ResponseFormat(HttpStatus.SC_CONFLICT);
- private static final ResponseFormat generalErrorResponseFormat = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- private static final ResponseFormat createdResponseFormat = new ResponseFormat(HttpStatus.SC_CREATED);
- private static final ResponseFormat noContentResponseFormat = new ResponseFormat(HttpStatus.SC_NO_CONTENT);
- private static final ResponseFormat unauthorizedResponseFormat = Mockito.mock(ResponseFormat.class);
- private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class);
- private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class);
- private static final String EMPTY_JSON = "{}";
- private static final String COMPONENT_TYPE = "componentType";
- private static final String CATEGORY_UNIQUE_ID = "categoryUniqueId";
- private static final String CATEGORY_ID = "categoryId";
- private static final String SUB_CATEGORY_UNIQUE_ID = "subCategoryUniqueId";
- private static final String SUB_CATEGORY_ID = "subCategoryId";
- private static final String GROUPING_UNIQUE_ID = "groupingUniqueId";
+ /* Users */
+ private static User designerUser = new User("designer", "designer", "designer", "designer@email.com",
+ Role.DESIGNER.name(), System
+ .currentTimeMillis());
- /* Users */
- private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System
- .currentTimeMillis());
+ private static ConfigurationManager configurationManager;
- private static ConfigurationManager configurationManager;
+ @BeforeAll
+ public static void setup() {
- @BeforeClass
- public static void setup() {
+ //Needed for User Authorization
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+ when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION))
+ .thenReturn(unauthorizedResponseFormat);
+ when(unauthorizedResponseFormat.getStatus()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
- //Needed for User Authorization
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
- when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
- when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(unauthorizedResponseFormat);
- when(unauthorizedResponseFormat.getStatus()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
+ when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(createdResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(noContentResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(badRequestResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(generalErrorResponseFormat);
+ when(componentUtils.getResponseFormat(any(ComponentException.class)))
+ .thenReturn(generalErrorResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.OK)) .thenReturn(okResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(createdResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(noContentResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(badRequestResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)) .thenReturn(generalErrorResponseFormat);
- when(componentUtils.getResponseFormat(any(ComponentException.class)))
- .thenReturn(generalErrorResponseFormat);
+ ByResponseFormatComponentException ce = Mockito.mock(ByResponseFormatComponentException.class);
+ when(ce.getResponseFormat()).thenReturn(unauthorizedResponseFormat);
- ByResponseFormatComponentException ce = Mockito.mock(ByResponseFormatComponentException.class);
- when(ce.getResponseFormat()).thenReturn(unauthorizedResponseFormat);
+ //Needed for error configuration
+ when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.SC_NOT_FOUND);
+ when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.SC_BAD_REQUEST);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), any()))
+ .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), any()))
+ .thenReturn(notFoundResponseFormat);
+ 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);
- //Needed for error configuration
- when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.SC_NOT_FOUND);
- when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.SC_BAD_REQUEST);
- when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), any())).thenReturn(notFoundResponseFormat);
- when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), any())).thenReturn(notFoundResponseFormat);
- 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);
- Either<User, ActionStatus> designerEither = Either.left(designerUser);
+ when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser);
- when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser);
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- 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);
- 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");
- configurationManager.setConfiguration(configuration);
- ExternalConfiguration.setAppName("catalog-be");
+ }
- }
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ reset(elementBusinessLogic);
+ }
- @Before
- public void resetSomeMocks() {
- reset(elementBusinessLogic);
- }
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- @Test
- public void getComponentCategoriesNoCategoryFoundTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ @Test
+ void getComponentCategoriesNoCategoryFoundTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- String formatEndpoint = "/v1/categories/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/categories/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
- Either<List<CategoryDefinition>, ResponseFormat> getAllCategoriesEither = Either.right(notFoundResponseFormat);
+ ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
+ Either<List<CategoryDefinition>, ResponseFormat> getAllCategoriesEither = Either.right(notFoundResponseFormat);
- when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
- .thenReturn(getAllCategoriesEither);
+ when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
+ .thenReturn(getAllCategoriesEither);
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
+ }
- @Test
- public void getComponentCategoriesExceptionDuringProcessingTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ @Test
+ void getComponentCategoriesExceptionDuringProcessingTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- String formatEndpoint = "/v1/categories/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/categories/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: getComponentCategories"));
+ when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: getComponentCategories"));
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- @Test
- public void getComponentCategoriesTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ @Test
+ void getComponentCategoriesTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- String formatEndpoint = "/v1/categories/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/categories/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- Either<List<CategoryDefinition>, ResponseFormat> getAllCategoriesEither = Either.left(new ArrayList<>());
+ Either<List<CategoryDefinition>, ResponseFormat> getAllCategoriesEither = Either.left(new ArrayList<>());
- when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
- .thenReturn(getAllCategoriesEither);
+ when(elementBusinessLogic.getAllCategories(componentType, designerUser.getUserId()))
+ .thenReturn(getAllCategoriesEither);
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- @Test
- public void getAllCategoriesNoCategoryFoundTest() {
- String path = "/v1/categories";
+ @Test
+ void getAllCategoriesNoCategoryFoundTest() {
+ String path = "/v1/categories";
- ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
- Either<UiCategories, ResponseFormat> getAllCategoriesEither = Either.right(notFoundResponseFormat);
+ ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
+ Either<UiCategories, ResponseFormat> getAllCategoriesEither = Either.right(notFoundResponseFormat);
- when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
- .thenReturn(getAllCategoriesEither);
+ when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
+ .thenReturn(getAllCategoriesEither);
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
+ }
- @Test
- public void getAllCategoriesExceptionDuringProcessingTest() {
- String path = "/v1/setup/ui";
- when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: getAllCategories"));
+ @Test
+ void getAllCategoriesExceptionDuringProcessingTest() {
+ String path = "/v1/setup/ui";
+ when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: getAllCategories"));
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- @Test
- public void getAllCategoriesTest() {
- 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.getResourceTypesMap()).thenReturn(Either.left(new HashMap<String, String>()));
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenReturn(otherEither);
+ @Test
+ void getAllCategoriesTest() {
+ 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.getResourceTypesMap()).thenReturn(Either.left(new HashMap<String, String>()));
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenReturn(otherEither);
+ when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
+ .thenReturn(getAllCategoriesEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- when(elementBusinessLogic.getAllCategories(designerUser.getUserId()))
- .thenReturn(getAllCategoriesEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ @Test
+ void createComponentCategoryCreationFailedTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
+ String formatEndpoint = "/v1/category/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentCategoryCreationFailedTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ Either<CategoryDefinition, ResponseFormat> createComponentCategoryEither = Either.right(conflictResponseFormat);
- String formatEndpoint = "/v1/category/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(createComponentCategoryEither);
- Either<CategoryDefinition, ResponseFormat> createComponentCategoryEither = Either.right(conflictResponseFormat);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(createComponentCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void createComponentCategoryExceptionDuringCreationTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
- }
+ String formatEndpoint = "/v1/category/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentCategoryExceptionDuringCreationTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
+ .thenThrow(new RuntimeException("Test exception: createComponentCategory"));
- String formatEndpoint = "/v1/category/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
- .thenThrow(new RuntimeException("Test exception: createComponentCategory"));
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void createComponentCategoryTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ String formatEndpoint = "/v1/category/{componentType}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentCategoryTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
+ Either<CategoryDefinition, ResponseFormat> createComponentCategoryEither = Either
+ .left(new CategoryDefinition());
- String formatEndpoint = "/v1/category/{componentType}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(createComponentCategoryEither);
- Either<CategoryDefinition, ResponseFormat> createComponentCategoryEither = Either.left(new CategoryDefinition());
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createCategory(any(), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(createComponentCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void deleteComponentCategoryNoCategoryFoundTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void deleteComponentCategoryNoCategoryFoundTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
+ Either<CategoryDefinition, ResponseFormat> deleteComponentCategoryEither = Either.right(notFoundResponseFormat);
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
+ .thenReturn(deleteComponentCategoryEither);
- ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
- Either<CategoryDefinition, ResponseFormat> deleteComponentCategoryEither = Either.right(notFoundResponseFormat);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
- .thenReturn(deleteComponentCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ @Test
+ void deleteComponentCategoryExceptionDuringProcessingTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void deleteComponentCategoryExceptionDuringProcessingTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: deleteComponentCategory"));
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: deleteComponentCategory"));
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ @Test
+ void deleteComponentCategoryTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void deleteComponentCategoryTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ Either<CategoryDefinition, ResponseFormat> deleteComponentCategoryEither = Either
+ .left(new CategoryDefinition());
+ when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
+ .thenReturn(deleteComponentCategoryEither);
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- Either<CategoryDefinition, ResponseFormat> deleteComponentCategoryEither = Either.left(new CategoryDefinition());
- when(elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, designerUser.getUserId()))
- .thenReturn(deleteComponentCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ @Test
+ void createComponentSubCategoryCreationFailedTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentSubCategoryCreationFailedTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
+ Either<SubCategoryDefinition, ResponseFormat> createComponentSubCategoryEither = Either
+ .right(conflictResponseFormat);
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic
+ .createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
+ .thenReturn(createComponentSubCategoryEither);
- Either<SubCategoryDefinition, ResponseFormat> createComponentSubCategoryEither = Either.right(conflictResponseFormat);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
- .thenReturn(createComponentSubCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void createComponentSubCategoryExceptionDuringCreationTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentSubCategoryExceptionDuringCreationTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
+ when(elementBusinessLogic
+ .createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
+ .thenThrow(new RuntimeException("Test exception: createComponentSubCategory"));
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
- .thenThrow(new RuntimeException("Test exception: createComponentSubCategory"));
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void createComponentSubCategoryTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void createComponentSubCategoryTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
+ Either<SubCategoryDefinition, ResponseFormat> createComponentSubCategoryEither = Either
+ .left(new SubCategoryDefinition());
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic
+ .createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
+ .thenReturn(createComponentSubCategoryEither);
- Either<SubCategoryDefinition, ResponseFormat> createComponentSubCategoryEither = Either.left(new SubCategoryDefinition());
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- when(elementBusinessLogic.createSubCategory(any(), eq(componentType), eq(categoryId), eq(designerUser.getUserId())))
- .thenReturn(createComponentSubCategoryEither);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
+ }
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ @Test
+ void deleteComponentSubCategoryCreationFailedTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
- }
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- @Test
- public void deleteComponentSubCategoryCreationFailedTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ Either<SubCategoryDefinition, ResponseFormat> deleteComponentSubCategoryEither = Either
+ .right(conflictResponseFormat);
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic
+ .deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(deleteComponentSubCategoryEither);
- Either<SubCategoryDefinition, ResponseFormat> deleteComponentSubCategoryEither = Either.right(conflictResponseFormat);
-
- when(elementBusinessLogic.deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(deleteComponentSubCategoryEither);
-
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
+ }
- @Test
- public void deleteComponentSubCategoryExceptionDuringCreationTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ @Test
+ void deleteComponentSubCategoryExceptionDuringCreationTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- when(elementBusinessLogic.deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenThrow(new RuntimeException("Test exception: deleteComponentSubCategory"));
+ when(elementBusinessLogic
+ .deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenThrow(new RuntimeException("Test exception: deleteComponentSubCategory"));
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- @Test
- public void deleteComponentSubCategoryTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ @Test
+ void deleteComponentSubCategoryTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- Either<SubCategoryDefinition, ResponseFormat> deleteComponentSubCategoryEither = Either.left(new SubCategoryDefinition());
+ Either<SubCategoryDefinition, ResponseFormat> deleteComponentSubCategoryEither = Either
+ .left(new SubCategoryDefinition());
- when(elementBusinessLogic.deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(deleteComponentSubCategoryEither);
+ when(elementBusinessLogic
+ .deleteSubCategory(eq(subCategoryUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(deleteComponentSubCategoryEither);
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- @Test
- public void createComponentGroupingCreationFailedTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryUniqueId";
- String subCategoryId = "subCategoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
- parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
+ @Test
+ void createComponentGroupingCreationFailedTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryUniqueId";
+ String subCategoryId = "subCategoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
+ parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- Either<GroupingDefinition, ResponseFormat> createComponentGroupingEither = Either.right(conflictResponseFormat);
+ Either<GroupingDefinition, ResponseFormat> createComponentGroupingEither = Either.right(conflictResponseFormat);
- when(elementBusinessLogic.createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
- .thenReturn(createComponentGroupingEither);
+ when(elementBusinessLogic
+ .createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
+ .thenReturn(createComponentGroupingEither);
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
- }
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
+ }
- @Test
- public void createComponentGroupingExceptionDuringCreationTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryUniqueId";
- String subCategoryId = "subCategoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
- parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
+ @Test
+ void createComponentGroupingExceptionDuringCreationTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryUniqueId";
+ String subCategoryId = "subCategoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
+ parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
+ when(elementBusinessLogic
+ .createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
+ .thenThrow(new RuntimeException("Test exception: createComponentGrouping"));
- when(elementBusinessLogic.createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
- .thenThrow(new RuntimeException("Test exception: createComponentGrouping"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void createComponentGroupingTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryId = "categoryUniqueId";
+ String subCategoryId = "subCategoryId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_ID, categoryId);
+ parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
- @Test
- public void createComponentGroupingTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryId = "categoryUniqueId";
- String subCategoryId = "subCategoryId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_ID, categoryId);
- parametersMap.put(SUB_CATEGORY_ID, subCategoryId);
+ String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- String formatEndpoint = "/v1/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Either<GroupingDefinition, ResponseFormat> createComponentGroupingEither = Either
+ .left(new GroupingDefinition());
- Either<GroupingDefinition, ResponseFormat> createComponentGroupingEither = Either.left(new GroupingDefinition());
+ when(elementBusinessLogic
+ .createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
+ .thenReturn(createComponentGroupingEither);
- when(elementBusinessLogic.createGrouping(any(), eq(componentType), eq(categoryId), eq(subCategoryId), eq(designerUser.getUserId())))
- .thenReturn(createComponentGroupingEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .post(Entity.json(EMPTY_JSON));
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .post(Entity.json(EMPTY_JSON));
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
- }
+ @Test
+ void deleteComponentGroupingCreationFailedTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ String groupingUniqueId = "groupingUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
- @Test
- public void deleteComponentGroupingCreationFailedTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- String groupingUniqueId = "groupingUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Either<GroupingDefinition, ResponseFormat> deleteComponentGroupingEither = Either.right(conflictResponseFormat);
- Either<GroupingDefinition, ResponseFormat> deleteComponentGroupingEither = Either.right(conflictResponseFormat);
+ when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(deleteComponentGroupingEither);
- when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(deleteComponentGroupingEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CONFLICT);
- }
+ @Test
+ void deleteComponentGroupingExceptionDuringCreationTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ String groupingUniqueId = "groupingUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
- @Test
- public void deleteComponentGroupingExceptionDuringCreationTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- String groupingUniqueId = "groupingUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenThrow(new RuntimeException("Test exception: deleteComponentGrouping"));
- when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenThrow(new RuntimeException("Test exception: deleteComponentGrouping"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void deleteComponentGroupingTest() {
+ String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ String categoryUniqueId = "categoryUniqueId";
+ String subCategoryUniqueId = "subCategoryUniqueId";
+ String groupingUniqueId = "groupingUniqueId";
+ Map<String, String> parametersMap = new HashMap<>();
+ parametersMap.put(COMPONENT_TYPE, componentType);
+ parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
+ parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
+ parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
- @Test
- public void deleteComponentGroupingTest() {
- String componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- String categoryUniqueId = "categoryUniqueId";
- String subCategoryUniqueId = "subCategoryUniqueId";
- String groupingUniqueId = "groupingUniqueId";
- Map<String,String> parametersMap = new HashMap<>();
- parametersMap.put(COMPONENT_TYPE, componentType);
- parametersMap.put(CATEGORY_UNIQUE_ID, categoryUniqueId);
- parametersMap.put(SUB_CATEGORY_UNIQUE_ID, subCategoryUniqueId);
- parametersMap.put(GROUPING_UNIQUE_ID, groupingUniqueId);
+ String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
- String formatEndpoint = "/v1/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ Either<GroupingDefinition, ResponseFormat> deleteComponentGroupingEither = Either
+ .left(new GroupingDefinition());
- Either<GroupingDefinition, ResponseFormat> deleteComponentGroupingEither = Either.left(new GroupingDefinition());
+ when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
+ .thenReturn(deleteComponentGroupingEither);
- when(elementBusinessLogic.deleteGrouping(eq(groupingUniqueId), eq(componentType), eq(designerUser.getUserId())))
- .thenReturn(deleteComponentGroupingEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .delete();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .delete();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ @Test
+ void tagsNoTagsFoundTest() {
+ String path = "/v1/tags";
+ Either<List<Tag>, ActionStatus> tagsEither = Either.right(ActionStatus.NO_CONTENT);
- @Test
- public void tagsNoTagsFoundTest() {
- String path = "/v1/tags";
- Either<List<Tag>, ActionStatus> tagsEither = Either.right(ActionStatus.NO_CONTENT);
+ when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
+ .thenReturn(tagsEither);
- when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
- .thenReturn(tagsEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ @Test
+ void tagsExceptionDuringProcessingTest() {
+ String path = "/v1/tags";
+ when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: tags"));
- @Test
- public void tagsExceptionDuringProcessingTest() {
- String path = "/v1/tags";
- when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: tags"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void tagsTest() {
+ String path = "/v1/tags";
+ Either<List<Tag>, ActionStatus> tagsEither = Either.left(new ArrayList<>());
+ when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
+ .thenReturn(tagsEither);
- @Test
- public void tagsTest() {
- String path = "/v1/tags";
- Either<List<Tag>, ActionStatus> tagsEither = Either.left(new ArrayList<>());
- when(elementBusinessLogic.getAllTags(designerUser.getUserId()))
- .thenReturn(tagsEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
+ @Test
+ void propertyScopesNoPropertyScopesFoundTest() {
+ String path = "/v1/propertyScopes";
+ Either<List<PropertyScope>, ActionStatus> propertyScopesEither = Either.right(ActionStatus.NO_CONTENT);
- @Test
- public void propertyScopesNoPropertyScopesFoundTest() {
- String path = "/v1/propertyScopes";
- Either<List<PropertyScope>, ActionStatus> propertyScopesEither = Either.right(ActionStatus.NO_CONTENT);
+ when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
+ .thenReturn(propertyScopesEither);
- when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
- .thenReturn(propertyScopesEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ @Test
+ void propertyScopesExceptionDuringProcessingTest() {
+ String path = "/v1/propertyScopes";
+ when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: propertyScopes"));
- @Test
- public void propertyScopesExceptionDuringProcessingTest() {
- String path = "/v1/propertyScopes";
- when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: propertyScopes"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void propertyScopesTest() {
+ String path = "/v1/propertyScopes";
+ Either<List<PropertyScope>, ActionStatus> propertyScopesEither = Either.left(new ArrayList<>());
+ when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
+ .thenReturn(propertyScopesEither);
- @Test
- public void propertyScopesTest() {
- String path = "/v1/propertyScopes";
- Either<List<PropertyScope>, ActionStatus> propertyScopesEither = Either.left(new ArrayList<>());
- when(elementBusinessLogic.getAllPropertyScopes(designerUser.getUserId()))
- .thenReturn(propertyScopesEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
+ @Test
+ void artifactTypesNoartifactTypesFoundTest() {
+ String path = "/v1/artifactTypes";
+ Either<List<ArtifactType>, ActionStatus> artifactTypesEither = Either.right(ActionStatus.NO_CONTENT);
- @Test
- public void artifactTypesNoartifactTypesFoundTest() {
- String path = "/v1/artifactTypes";
- Either<List<ArtifactType>, ActionStatus> artifactTypesEither = Either.right(ActionStatus.NO_CONTENT);
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenReturn(artifactTypesEither);
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenReturn(artifactTypesEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
- }
+ @Test
+ void artifactTypesExceptionDuringProcessingTest() {
+ String path = "/v1/artifactTypes";
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: artifactTypes"));
- @Test
- public void artifactTypesExceptionDuringProcessingTest() {
- String path = "/v1/artifactTypes";
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: artifactTypes"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void artifactTypesTest() {
+ String path = "/v1/artifactTypes";
+ Either<List<ArtifactType>, ActionStatus> artifactTypesEither = Either.left(new ArrayList<>());
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenReturn(artifactTypesEither);
- @Test
- public void artifactTypesTest() {
- String path = "/v1/artifactTypes";
- Either<List<ArtifactType>, ActionStatus> artifactTypesEither = Either.left(new ArrayList<>());
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenReturn(artifactTypesEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
+ @Test
+ void configurationNoConfigurationFoundTest() {
+ String path = "/v1/setup/ui";
- @Test
- public void configurationNoConfigurationFoundTest() {
- String path = "/v1/setup/ui";
+ Either<List<ArtifactType>, ActionStatus> otherEither = Either.left(new ArrayList<>());
+ Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new Configuration.HeatDeploymentArtifactTimeout();
+ heatDeploymentArtifactTimeout.setDefaultMinutes(1);
+ Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> defaultHeatTimeoutEither = Either
+ .left(heatDeploymentArtifactTimeout);
+ Either<Map<String, String>, ActionStatus> resourceTypesMapEither = Either.left(new HashMap<>());
- Either<List<ArtifactType>, ActionStatus> otherEither = Either.left(new ArrayList<>());
- Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new Configuration.HeatDeploymentArtifactTimeout();
- heatDeploymentArtifactTimeout.setDefaultMinutes(1);
- Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> defaultHeatTimeoutEither = Either.left(heatDeploymentArtifactTimeout);
- Either<Map<String, String>, ActionStatus> resourceTypesMapEither = Either.left(new HashMap<>());
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenReturn(otherEither);
+ when(elementBusinessLogic.getDefaultHeatTimeout())
+ .thenReturn(defaultHeatTimeoutEither);
+ when(elementBusinessLogic.getResourceTypesMap())
+ .thenReturn(resourceTypesMapEither);
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenReturn(otherEither);
- when(elementBusinessLogic.getDefaultHeatTimeout())
- .thenReturn(defaultHeatTimeoutEither);
- when(elementBusinessLogic.getResourceTypesMap())
- .thenReturn(resourceTypesMapEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void configurationExceptionDuringProcessingTest() {
+ String path = "/v1/setup/ui";
+ when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
+ .thenThrow(new RuntimeException("Test exception: artifactTypes"));
- @Test
- public void configurationExceptionDuringProcessingTest() {
- String path = "/v1/setup/ui";
- when(elementBusinessLogic.getAllArtifactTypes(designerUser.getUserId()))
- .thenThrow(new RuntimeException("Test exception: artifactTypes"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void screenNoCatalogComponentsFoundTest() {
+ String path = "/v1/screen";
- @Test
- public void screenNoCatalogComponentsFoundTest() {
- String path = "/v1/screen";
+ Either<Map<String, List<CatalogComponent>>, ResponseFormat> screenEither = Either
+ .right(badRequestResponseFormat);
+ when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
+ .thenReturn(screenEither);
- Either<Map<String, List<CatalogComponent>>, ResponseFormat> screenEither = Either.right(badRequestResponseFormat);
- when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
- .thenReturn(screenEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
- }
+ @Test
+ void screenExceptionDuringProcessingTest() {
+ String path = "/v1/screen";
- @Test
- public void screenExceptionDuringProcessingTest() {
- String path = "/v1/screen";
+ when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
+ .thenThrow(new RuntimeException("Test exception: screen"));
- when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
- .thenThrow(new RuntimeException("Test exception: screen"));
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
+ @Test
+ void screenTest() {
+ String path = "/v1/screen";
- @Test
- public void screenTest() {
- String path = "/v1/screen";
+ Either<Map<String, List<CatalogComponent>>, ResponseFormat> screenEither = Either.left(new HashMap<>());
+ when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
+ .thenReturn(screenEither);
- Either<Map<String, List<CatalogComponent>>, ResponseFormat> screenEither = Either.left(new HashMap<>());
- when(elementBusinessLogic.getCatalogComponents(eq(designerUser.getUserId()), any()))
- .thenReturn(screenEither);
+ Response response = target()
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, designerUser.getUserId())
+ .get();
- Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, designerUser.getUserId())
- .get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
+ }
- assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
- }
-
- @Override
- protected Application configure() {
- ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
forceSet(TestProperties.CONTAINER_PORT, "0");
- return new ResourceConfig(ElementServlet.class)
- .register(new AbstractBinder() {
+ return new ResourceConfig(ElementServlet.class)
+ .register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- bind(userBusinessLogic).to(UserBusinessLogic.class);
- bind(componentUtils).to(ComponentsUtils.class);
- bind(componentsCleanBusinessLogic).to(ComponentsCleanBusinessLogic.class);
- bind(elementBusinessLogic).to(ElementBusinessLogic.class);
- bind(artifactsBusinessLogic).to(ArtifactsBusinessLogic.class);
- }
- })
- .property("contextConfig", context);
- }
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ bind(userBusinessLogic).to(UserBusinessLogic.class);
+ bind(componentUtils).to(ComponentsUtils.class);
+ bind(componentsCleanBusinessLogic).to(ComponentsCleanBusinessLogic.class);
+ bind(elementBusinessLogic).to(ElementBusinessLogic.class);
+ bind(artifactsBusinessLogic).to(ArtifactsBusinessLogic.class);
+ }
+ })
+ .property("contextConfig", context);
+ }
}
\ No newline at end of file
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
index 34ff686..cdd5965 100644
--- 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
@@ -20,27 +20,28 @@
package org.openecomp.sdc.be.servlets;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
+import javax.ws.rs.core.Response;
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.glassfish.jersey.test.TestProperties;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.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 {
+class ExceptionHandlerEndpointTest extends JerseySpringBaseTest {
private static ComponentsUtils componentUtils;
@@ -54,10 +55,20 @@
}
}
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected void configureClient(ClientConfig config) {
final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
- .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
}
@@ -67,12 +78,13 @@
componentUtils = mock(ComponentsUtils.class);
return super.configure(ExceptionHandlerConfig.class)
- .register(ExceptionHandlerEndpoint.class);
+ .register(ExceptionHandlerEndpoint.class);
}
@Test
- public void getHandleException() {
- when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR));
+ 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 957fba2..c7886e3 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,8 +20,28 @@
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.ArgumentMatchers.isA;
+import static org.mockito.Mockito.anyList;
+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;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+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.assertj.core.api.AssertionsForClassTypes;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
@@ -29,9 +49,10 @@
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogicNew;
@@ -60,28 +81,7 @@
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
-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.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-
-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.ArgumentMatchers.isA;
-import static org.mockito.Mockito.anyList;
-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 {
+class GroupEndpointTest extends JerseySpringBaseTest {
private static final String VALID_USER = "ab001";
private static final String INVALID_USER = "ab002";
@@ -119,11 +119,12 @@
}
}
- @BeforeClass
+ @BeforeAll
public static void initClass() {
ExternalConfiguration.setAppName("catalog-be");
String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
//ComponentsUtils needs configuration singleton to be set
componentValidations = mock(ComponentValidations.class);
@@ -136,7 +137,7 @@
@Override
protected void configureClient(ClientConfig config) {
final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
- .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
}
@@ -144,12 +145,13 @@
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
return super.configure(GroupEndpointTestConfig.class)
- .register(GroupEndpoint.class)
- .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
+ .register(GroupEndpoint.class)
+ .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
}
- @Before
- public void init() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
cr = new Resource();
cr.setSystemName("CR1");
g1 = new GroupDefinition();
@@ -167,20 +169,33 @@
unhappyScenarioSetup();
}
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
private void unhappyScenarioSetup() {
- when(accessValidations.validateUserCanWorkOnComponent(eq(INVALID_COMPONENT_ID), eq(ComponentTypeEnum.RESOURCE), eq(VALID_USER), anyString())).thenThrow(new StorageException(NOT_FOUND, INVALID_COMPONENT_ID));
+ when(accessValidations
+ .validateUserCanWorkOnComponent(eq(INVALID_COMPONENT_ID), eq(ComponentTypeEnum.RESOURCE), eq(VALID_USER),
+ anyString())).thenThrow(new StorageException(NOT_FOUND, INVALID_COMPONENT_ID));
when(componentValidations.getComponentInstance(cr, A)).thenReturn(Optional.of(ci));
}
-
private void happyScenarioSetup() {
- when(accessValidations.validateUserCanWorkOnComponent(eq(VALID_COMPONENT_ID), any(ComponentTypeEnum.class), eq(VALID_USER), anyString())).thenReturn(cr);
- when(accessValidations.validateUserCanRetrieveComponentData(eq(VALID_COMPONENT_ID), eq("resources"), eq(VALID_USER), anyString()))
- .thenReturn(cr);
+ when(accessValidations
+ .validateUserCanWorkOnComponent(eq(VALID_COMPONENT_ID), any(ComponentTypeEnum.class), eq(VALID_USER),
+ anyString())).thenReturn(cr);
+ 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), any(PromoteVersionEnum.class));
- when(groupOperation.validateAndUpdatePropertyValue(isA(GroupProperty.class))).thenReturn(StorageOperationStatus.OK);
- when(groupsOperation.updateGroupPropertiesOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), anyList(), any(PromoteVersionEnum.class))).thenAnswer(new Answer<Either>() {
+ 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(),
+ any(PromoteVersionEnum.class))).thenAnswer(new Answer<Either>() {
@Override
public Either answer(InvocationOnMock invocationOnMock) throws Throwable {
Object[] args = invocationOnMock.getArguments();
@@ -190,44 +205,44 @@
}
@Test
- public void updateGroupMembers_success() {
+ void updateGroupMembers_success() {
List<String> ids = Arrays.asList(A);
List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
- });
+ .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
+ });
assertThat(updatedIds.size()).isEqualTo(ids.size());
assertThat(updatedIds).containsExactlyInAnyOrder(ids.toArray(new String[ids.size()]));
}
@Test
- public void updateGroupMembersWith2IdenticalMembers_success() {
+ void updateGroupMembersWith2IdenticalMembers_success() {
List<String> ids = Arrays.asList(A, A);
List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
- });
+ .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
+ });
assertThat(updatedIds.size()).isEqualTo(1);
assertThat(updatedIds).containsExactlyInAnyOrder(String.valueOf(A));
}
@Test
- public void updateGroupMembersWithEmptyList_success() {
+ void updateGroupMembersWithEmptyList_success() {
List<String> ids = new ArrayList<>();
List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
- });
- assertThat(updatedIds.size()).isEqualTo(0);
+ .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
+ });
+ assertThat(updatedIds.size()).isZero();
}
@Test
- public void updateGroupMember_InvalidComponentId_failure() {
+ void updateGroupMember_InvalidComponentId_failure() {
List<String> ids = new ArrayList<>();
Response response = buildUpdateGroupMembersCall(INVALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .post(Entity.entity(ids, MediaType.APPLICATION_JSON), Response.class);
+ .post(Entity.entity(ids, MediaType.APPLICATION_JSON), Response.class);
AssertionsForClassTypes.assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
- public void updateGroupProperty_success() {
+ void updateGroupProperty_success() {
GroupProperty property = new GroupProperty();
property.setValue("value1");
property.setName("prop");
@@ -239,31 +254,33 @@
// });
// assertThat(updatedProperties.size()).isEqualTo(1);
Response response = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .put(Entity.entity(propertyStr, MediaType.APPLICATION_JSON));
+ .put(Entity.entity(propertyStr, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
}
@Test
- public void getGroupProperties_success() {
- List<PropertyDataDefinition> properties = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
- .get(new GenericType<List<PropertyDataDefinition>>(){});
+ void getGroupProperties_success() {
+ List<PropertyDataDefinition> properties = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID,
+ VALID_USER)
+ .get(new GenericType<List<PropertyDataDefinition>>() {
+ });
assertThat(properties.size()).isEqualTo(1);
assertThat(properties.get(0).getValue()).isEqualTo(OLD_VALUE);
}
private Invocation.Builder buildUpdateGroupMembersCall(String componentId, String groupId, String userId) {
return target("/v1/catalog/resources/" + componentId + "/groups/" + groupId + "/members")
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId);
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
}
private Invocation.Builder buildUpdateGroupPropertiesCall(String componentId, String groupId, String userId) {
return target("/v1/catalog/resources/" + componentId + "/groups/" + groupId + "/properties")
- .request(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId);
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
}
-
+
}
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 00e7768..1e4e56c 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,18 +20,34 @@
package org.openecomp.sdc.be.servlets;
+import static java.util.Arrays.asList;
+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 com.fasterxml.jackson.databind.DeserializationFeature;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import fj.data.Either;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
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.glassfish.jersey.test.TestProperties;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
import org.openecomp.sdc.be.components.utils.GroupTypeBuilder;
import org.openecomp.sdc.be.components.validation.UserValidations;
@@ -58,23 +74,7 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.core.GenericType;
-import javax.ws.rs.core.MediaType;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Stream;
-
-import static java.util.Arrays.asList;
-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;
-
-public class GroupTypesEndpointTest extends JerseySpringBaseTest {
+class GroupTypesEndpointTest extends JerseySpringBaseTest {
private static final String USER_ID = "a001";
private static final GroupTypeDefinition EMPTY_GROUP_TYPE = new GroupTypeDefinition();
@@ -92,7 +92,8 @@
private static OperationUtils operationUtils;
private static User user;
- static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
+ static ConfigurationSource configurationSource = new FSConfigurationSource(
+ ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
@org.springframework.context.annotation.Configuration
@@ -113,11 +114,12 @@
@Bean
GroupTypeOperation groupTypeOperation() {
- return new GroupTypeOperation(janusGraphGenericDao, propertyOperation, capabilityTypeOperation, capabilityOperation, derivedFromOperation, operationUtils);
+ return new GroupTypeOperation(janusGraphGenericDao, propertyOperation, capabilityTypeOperation,
+ capabilityOperation, derivedFromOperation, operationUtils);
}
}
- @BeforeClass
+ @BeforeAll
public static void initClass() {
componentsUtils = mock(ComponentsUtils.class);
propertyOperation = mock(PropertyOperation.class);
@@ -129,15 +131,24 @@
user = mock(User.class);
}
- @Before
- public void init() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
when(userValidations.validateUserExists(eq(USER_ID))).thenReturn(user);
- when(janusGraphGenericDao.getByCriteriaWithPredicate(eq(NodeTypeEnum.GroupType), any(), eq(GroupTypeData.class))).thenReturn(Either.left(buildGroupTypeDataList()));
+ when(
+ janusGraphGenericDao.getByCriteriaWithPredicate(eq(NodeTypeEnum.GroupType), any(), eq(GroupTypeData.class)))
+ .thenReturn(Either.left(buildGroupTypeDataList()));
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
}
@Override
protected void configureClient(ClientConfig config) {
- final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
}
@@ -145,81 +156,88 @@
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
return super.configure(GroupTypesTestConfig.class)
- .register(GroupTypesEndpoint.class);
+ .register(GroupTypesEndpoint.class);
}
@Test
- public void verifyExclusionMapIsCaseInsensitive() {
- Map<String, Set<String>> excludedGroupTypesMapping = configurationManager.getConfiguration().getExcludedGroupTypesMapping();
- assertThat(excludedGroupTypesMapping.get(COMPONENT_TYPE)).hasSameElementsAs(excludedGroupTypesMapping.get(COMPONENT_TYPE.toLowerCase()));
+ void verifyExclusionMapIsCaseInsensitive() {
+ Map<String, Set<String>> excludedGroupTypesMapping = configurationManager.getConfiguration()
+ .getExcludedGroupTypesMapping();
+ assertThat(excludedGroupTypesMapping.get(COMPONENT_TYPE))
+ .hasSameElementsAs(excludedGroupTypesMapping.get(COMPONENT_TYPE.toLowerCase()));
}
@Test
- public void getGroupTypes_validUser_Success() {
+ void getGroupTypes_validUser_Success() {
List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList();
- List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCall(USER_ID, COMPONENT_TYPE).get(new GenericType<List<GroupTypeDefinition>>(){});
+ List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCall(USER_ID, COMPONENT_TYPE)
+ .get(new GenericType<List<GroupTypeDefinition>>() {
+ });
verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes);
}
@Test
- public void getGroupTypes_whenNoInteranlComponentType_passEmptyAsExcludedTypes() {
+ void getGroupTypes_whenNoInteranlComponentType_passEmptyAsExcludedTypes() {
List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList();
- List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCallNoInternalComponent(USER_ID).get(new GenericType<List<GroupTypeDefinition>>(){});
+ List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCallNoInternalComponent(USER_ID)
+ .get(new GenericType<List<GroupTypeDefinition>>() {
+ });
verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes);
}
- private void verifyGroupTypesList(List<GroupTypeDefinition> groupTypes, List<GroupTypeDefinition> fetchedGroupTypes) {
+ private void verifyGroupTypesList(List<GroupTypeDefinition> groupTypes,
+ List<GroupTypeDefinition> fetchedGroupTypes) {
String[] expectedReturnFields = {"version", "type", "uniqueId", "name", "icon"};
assertThat(fetchedGroupTypes)
- .usingElementComparatorOnFields(expectedReturnFields)
- .isEqualTo(groupTypes);
+ .usingElementComparatorOnFields(expectedReturnFields)
+ .isEqualTo(groupTypes);
verifyOnlySpecificFieldsInResponse(fetchedGroupTypes, expectedReturnFields);
}
- private void verifyOnlySpecificFieldsInResponse(List<GroupTypeDefinition> fetchedGroupTypes, String ... fields) {
+ private void verifyOnlySpecificFieldsInResponse(List<GroupTypeDefinition> fetchedGroupTypes, String... fields) {
assertThat(fetchedGroupTypes)
- .usingElementComparatorIgnoringFields(fields)
- .containsOnly(EMPTY_GROUP_TYPE);
+ .usingElementComparatorIgnoringFields(fields)
+ .containsOnly(EMPTY_GROUP_TYPE);
}
private Invocation.Builder buildGetGroupTypesCall(String userId, String componentType) {
return target("/v1/catalog/groupTypes")
- .queryParam("internalComponentType", componentType)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId);
+ .queryParam("internalComponentType", componentType)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
}
private Invocation.Builder buildGetGroupTypesCallNoInternalComponent(String userId) {
return target("/v1/catalog/groupTypes")
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId);
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
}
private Map<String, Set<String>> buildExcludeGroupTypesMap() {
return new ImmutableMap.Builder<String, Set<String>>()
- .put("CR", Sets.newHashSet("VFModule", "Root", "Heat"))
- .put(COMPONENT_TYPE, EXCLUDED_TYPES)
- .build();
+ .put("CR", Sets.newHashSet("VFModule", "Root", "Heat"))
+ .put(COMPONENT_TYPE, EXCLUDED_TYPES)
+ .build();
}
private List<GroupTypeDefinition> buildGroupTypesList() {
GroupTypeDefinition type1 = GroupTypeBuilder.create()
- .setDerivedFrom("root")
- .setType("org.openecomp.groups.VfModule")
- .setUniqueId("id1")
- .setVersion("1.0")
- .setName("vf module")
- .setIcon("vf module icon")
- .build();
+ .setDerivedFrom("root")
+ .setType("org.openecomp.groups.VfModule")
+ .setUniqueId("id1")
+ .setVersion("1.0")
+ .setName("vf module")
+ .setIcon("vf module icon")
+ .build();
GroupTypeDefinition type2 = GroupTypeBuilder.create()
- .setDerivedFrom("root")
- .setType("org.openecomp.groups.NetworkCollection")
- .setUniqueId("id2")
- .setVersion("1.0")
- .setName("network collection")
- .setIcon("network collection icon")
- .build();
+ .setDerivedFrom("root")
+ .setType("org.openecomp.groups.NetworkCollection")
+ .setUniqueId("id2")
+ .setVersion("1.0")
+ .setName("network collection")
+ .setIcon("network collection icon")
+ .build();
return asList(type1, type2);
}
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 9b8b984..bd20471 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
@@ -20,15 +20,39 @@
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.eq;
+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;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+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 org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -66,31 +90,7 @@
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;
-import java.util.Collections;
-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;
-import static org.mockito.ArgumentMatchers.eq;
-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 {
+class InputsServletTest extends JerseyTest {
/* Constants */
private static final String RESOURCE_ID = "serviceId";
@@ -120,10 +120,11 @@
private static HttpServletRequest request;
String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- @BeforeClass
+ @BeforeAll
public static void configureMocks() {
request = mock(HttpServletRequest.class);
userBusinessLogic = mock(UserBusinessLogic.class);
@@ -141,8 +142,9 @@
}
- @Before
- public void resetMocks() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
Mockito.reset(resourceImportManager);
Mockito.reset(servletUtils);
Mockito.reset(componentsUtils);
@@ -160,10 +162,16 @@
when(httpSession.getServletContext()).thenReturn(servletContext);
when(servletContext.getAttribute(
Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(new WebAppContextWrapper());
- when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(webApplicationContext);
+ when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
+ .thenReturn(webApplicationContext);
when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
}
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected Application configure() {
InputsServlet inputsServlet = new InputsServlet(userBusinessLogic, inputsBusinessLogic,
@@ -185,18 +193,15 @@
return resourceConfig;
}
-
-
-
private InputDefinition setUpListInput() {
InputDefinition listInput = new InputDefinition();
listInput.setName(LISTINPUT_NAME);
listInput.setType("list");
SchemaDefinition listInputSchema = new SchemaDefinition();
listInputSchema.setProperty(new PropertyDataDefinitionBuilder()
- .setType(LISTINPUT_SCHEMA_TYPE)
- .setIsRequired(false)
- .build()
+ .setType(LISTINPUT_SCHEMA_TYPE)
+ .setIsRequired(false)
+ .build()
);
listInput.setSchema(listInputSchema);
return listInput;
@@ -233,15 +238,17 @@
}
@Test
- public void test_createListInput_success() throws Exception {
+ void test_createListInput_success() throws Exception {
ComponentInstListInput requestBodyObj = setUpCreateListInputParams();
Entity<ComponentInstListInput> entity = Entity.entity(requestBodyObj, MediaType.APPLICATION_JSON);
- doReturn(Either.left(requestBodyObj)).when(componentsUtils).convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstListInput.class),
- eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE));
+ doReturn(Either.left(requestBodyObj)).when(componentsUtils)
+ .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstListInput.class),
+ eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE));
- doReturn(Either.left(Collections.emptyList())).when(inputsBusinessLogic).createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
- any(), eq(true), eq(false));
+ doReturn(Either.left(Collections.emptyList())).when(inputsBusinessLogic)
+ .createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
+ any(), eq(true), eq(false));
ResponseFormat responseFormat = new ResponseFormat(HttpStatus.OK_200.getStatusCode());
doReturn(responseFormat).when(componentsUtils).getResponseFormat(ActionStatus.OK);
@@ -249,72 +256,76 @@
Response response = buildCreateListInputCall().post(entity);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200.getStatusCode());
verify(inputsBusinessLogic, times(1)).createListInput(USER_ID, RESOURCE_ID,
- ComponentTypeEnum.SERVICE, requestBodyObj, true, false);
+ ComponentTypeEnum.SERVICE, requestBodyObj, true, false);
}
@Test
- public void test_createListInput_fail_parse() throws Exception {
+ void test_createListInput_fail_parse() throws Exception {
ComponentInstListInput requestBodyObj = setUpCreateListInputParams();
Entity<ComponentInstListInput> entity = Entity.entity(requestBodyObj, MediaType.APPLICATION_JSON);
// for parseToComponentInstListInput
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(any(), userCaptor.capture(), eq(ComponentInstListInput.class),
+ when(componentsUtils
+ .convertJsonToObjectUsingObjectMapper(any(), userCaptor.capture(), eq(ComponentInstListInput.class),
eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE)))
- .thenReturn(Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode())));
+ .thenReturn(Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode())));
when(inputsBusinessLogic.createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
- any(), eq(true), eq(false)))
- .thenReturn(Either.left(Collections.emptyList()));
+ any(), eq(true), eq(false)))
+ .thenReturn(Either.left(Collections.emptyList()));
Response response = buildCreateListInputCall().post(entity);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode());
verify(componentsUtils, times(1))
- .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstListInput.class),
+ .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstListInput.class),
eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE));
assertThat(userCaptor.getValue().getUserId()).isEqualTo(USER_ID);
verify(inputsBusinessLogic, never()).createListInput(USER_ID, RESOURCE_ID,
- ComponentTypeEnum.SERVICE, requestBodyObj, true, false);
+ ComponentTypeEnum.SERVICE, requestBodyObj, true, false);
}
@Test
- public void test_createListInput_fail_createInput() throws Exception {
+ void test_createListInput_fail_createInput() throws Exception {
ComponentInstListInput requestBodyObj = setUpCreateListInputParams();
Entity<ComponentInstListInput> entity = Entity.entity(requestBodyObj, MediaType.APPLICATION_JSON);
// for parseToComponentInstListInput
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(any(), userCaptor.capture(), eq(ComponentInstListInput.class),
+ when(componentsUtils
+ .convertJsonToObjectUsingObjectMapper(any(), userCaptor.capture(), eq(ComponentInstListInput.class),
eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE)))
- .thenReturn(Either.left(requestBodyObj));
+ .thenReturn(Either.left(requestBodyObj));
when(inputsBusinessLogic.createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
- any(), eq(true), eq(false)))
- .thenReturn(Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode())));
+ any(), eq(true), eq(false)))
+ .thenReturn(Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode())));
Response response = buildCreateListInputCall().post(entity);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode());
verify(inputsBusinessLogic, times(1))
- .createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
- any(), eq(true), eq(false));
+ .createListInput(eq(USER_ID), eq(RESOURCE_ID), eq(ComponentTypeEnum.SERVICE),
+ any(), eq(true), eq(false));
}
@Test
- public void test_createListInput_fail_exception() throws Exception {
+ void test_createListInput_fail_exception() throws Exception {
ComponentInstListInput requestBodyObj = setUpCreateListInputParams();
Entity<ComponentInstListInput> entity = Entity.entity(requestBodyObj, MediaType.APPLICATION_JSON);
- when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
+ when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR))
+ .thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
Response response = buildCreateListInputCall().post(entity);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode());
}
@Test
- public void test_getDataType_success() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID),eq(LISTINPUT_SCHEMA_TYPE))).thenReturn(Either.left(new DataTypeDefinition()));
+ void test_getDataType_success() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID), eq(LISTINPUT_SCHEMA_TYPE)))
+ .thenReturn(Either.left(new DataTypeDefinition()));
ResponseFormat responseFormat = new ResponseFormat();
responseFormat.setStatus(HttpStatus.OK_200.getStatusCode());
@@ -325,12 +336,14 @@
}
@Test
- public void test_getDataType_fail() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID),eq(LISTINPUT_SCHEMA_TYPE))).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
+ void test_getDataType_fail() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID), eq(LISTINPUT_SCHEMA_TYPE)))
+ .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
ResponseFormat responseFormat = new ResponseFormat();
responseFormat.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500.getStatusCode());
- when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.BAD_REQUEST))).thenReturn(ActionStatus.GENERAL_ERROR);
+ when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.BAD_REQUEST)))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR))).thenReturn(responseFormat);
Response response = buildGetDataTypeCall().get();
@@ -338,17 +351,20 @@
}
@Test
- public void test_getDataType_fail_exception() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID),eq(LISTINPUT_SCHEMA_TYPE))).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR))).thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
+ void test_getDataType_fail_exception() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID), eq(LISTINPUT_SCHEMA_TYPE)))
+ .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR)))
+ .thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
Response response = buildGetDataTypeCall().get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode());
}
@Test
- public void test_getDataTypes_success() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataTypes(eq(RESOURCE_ID))).thenReturn(Either.left(Collections.emptyList()));
+ void test_getDataTypes_success() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataTypes(eq(RESOURCE_ID)))
+ .thenReturn(Either.left(Collections.emptyList()));
ResponseFormat responseFormat = new ResponseFormat();
responseFormat.setStatus(HttpStatus.OK_200.getStatusCode());
@@ -359,12 +375,14 @@
}
@Test
- public void test_getDataTypes_fail() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataTypes(eq(RESOURCE_ID))).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
+ void test_getDataTypes_fail() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataTypes(eq(RESOURCE_ID)))
+ .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
ResponseFormat responseFormat = new ResponseFormat();
responseFormat.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500.getStatusCode());
- when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.BAD_REQUEST))).thenReturn(ActionStatus.GENERAL_ERROR);
+ when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.BAD_REQUEST)))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR))).thenReturn(responseFormat);
Response response = buildGetDataTypesCall().get();
@@ -372,101 +390,109 @@
}
@Test
- public void test_getDataTypes_fail_exception() throws Exception {
- when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID),eq(LISTINPUT_SCHEMA_TYPE))).thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
- when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR))).thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
+ void test_getDataTypes_fail_exception() throws Exception {
+ when(dataTypeBusinessLogic.getPrivateDataType(eq(RESOURCE_ID), eq(LISTINPUT_SCHEMA_TYPE)))
+ .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.GENERAL_ERROR)))
+ .thenReturn(new ResponseFormat(HttpStatus.BAD_REQUEST_400.getStatusCode()));
Response response = buildGetDataTypesCall().get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400.getStatusCode());
}
-
@Test
- public void test_deleteDataType_success() throws Exception {
- when(dataTypeBusinessLogic.deletePrivateDataType(RESOURCE_ID, LISTINPUT_SCHEMA_TYPE)).thenReturn(Either.left(new DataTypeDefinition()));
+ void test_deleteDataType_success() throws Exception {
+ when(dataTypeBusinessLogic.deletePrivateDataType(RESOURCE_ID, LISTINPUT_SCHEMA_TYPE))
+ .thenReturn(Either.left(new DataTypeDefinition()));
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
+ when(componentsUtils.getResponseFormat(ActionStatus.OK))
+ .thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
Response response = buildGetDataTypeCall().delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200.getStatusCode());
}
@Test
- public void test_deleteDataType_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.INTERNAL_SERVER_ERROR_500.getStatusCode()));
+ void test_deleteDataType_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.INTERNAL_SERVER_ERROR_500.getStatusCode()));
Response response = buildGetDataTypeCall().delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500.getStatusCode());
verify(componentsUtils, never()).getResponseFormat(ActionStatus.OK);
}
@Test
- public void test_deleteDataType_failure_notFound() throws Exception {
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
- when(dataTypeBusinessLogic.deletePrivateDataType(RESOURCE_ID, LISTINPUT_SCHEMA_TYPE)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)).thenReturn(ActionStatus.ARTIFACT_NOT_FOUND);
- when(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND)).thenReturn(new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode()));
+ void test_deleteDataType_failure_notFound() throws Exception {
+ when(componentsUtils.getResponseFormat(ActionStatus.OK))
+ .thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
+ when(dataTypeBusinessLogic.deletePrivateDataType(RESOURCE_ID, LISTINPUT_SCHEMA_TYPE))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND))
+ .thenReturn(ActionStatus.ARTIFACT_NOT_FOUND);
+ when(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND))
+ .thenReturn(new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode()));
Response response = buildGetDataTypeCall().delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND_404.getStatusCode());
verify(componentsUtils, never()).getResponseFormat(ActionStatus.OK);
}
@Test
- public void test_deleteInput_success() throws Exception {
+ void test_deleteInput_success() throws Exception {
when(inputsBusinessLogic.deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME))
- .thenReturn(new InputDefinition());
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
+ .thenReturn(new InputDefinition());
+ when(componentsUtils.getResponseFormat(ActionStatus.OK))
+ .thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
// 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();
+ .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.OK_200.getStatusCode());
verify(inputsBusinessLogic, times(1)).deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME);
}
-
@Test
- public void test_deleteInput_failure_deleteInput() throws Exception {
+ void test_deleteInput_failure_deleteInput() throws Exception {
ComponentException componentException = new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
when(inputsBusinessLogic.deleteInput(RESOURCE_ID, USER_ID, LISTINPUT_NAME))
- .thenThrow(componentException);
+ .thenThrow(componentException);
// 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();
+ .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);
}
-
private Invocation.Builder buildCreateListInputCall() {
return target("/v1/catalog/services/{id}/create/listInput")
- .resolveTemplate("id", RESOURCE_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .resolveTemplate("id", RESOURCE_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
private Invocation.Builder buildGetDataTypeCall() {
return target("/v1/catalog/services/{id}/dataType/{dataTypeName}")
- .resolveTemplate("id", RESOURCE_ID)
- .resolveTemplate("dataTypeName", LISTINPUT_SCHEMA_TYPE)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .resolveTemplate("id", RESOURCE_ID)
+ .resolveTemplate("dataTypeName", LISTINPUT_SCHEMA_TYPE)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
private Invocation.Builder buildGetDataTypesCall() {
return target("/v1/catalog/services/{id}/dataTypes")
- .resolveTemplate("id", RESOURCE_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .resolveTemplate("id", RESOURCE_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
}
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 38eef3c..e755de1 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,7 +20,13 @@
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;
@@ -33,7 +39,7 @@
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.BeforeAll;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper;
import org.openecomp.sdc.be.servlets.exception.DefaultExceptionMapper;
@@ -42,13 +48,6 @@
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());
@@ -57,10 +56,12 @@
protected static WebappContext context;
protected static WebAppContextWrapper contextWrapper;
protected static WebApplicationContext applicationContext;
- private final static JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- private final static Feature loggingFeature = new LoggingFeature(log, Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, null);
+ private final static JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ private final static Feature loggingFeature = new LoggingFeature(log, Level.INFO,
+ LoggingFeature.Verbosity.PAYLOAD_ANY, null);
- @BeforeClass
+ @BeforeAll
public static void initBaseClass() {
request = mock(HttpServletRequest.class);
session = mock(HttpSessionImpl.class);
@@ -72,8 +73,8 @@
@Override
protected void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class)
- .register(loggingFeature)
- .register(jacksonJsonProvider);
+ .register(loggingFeature)
+ .register(jacksonJsonProvider);
}
protected ResourceConfig configure() {
@@ -85,21 +86,21 @@
ApplicationContext context = new AnnotationConfigApplicationContext(springConfig);
forceSet(TestProperties.CONTAINER_PORT, "0");
return new ResourceConfig()
- .register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- })
- .register(RolesAllowedDynamicFeature.class)
- .register(DefaultExceptionMapper.class)
- .register(ComponentExceptionMapper.class)
- .register(StorageExceptionMapper.class)
- .register(MultiPartFeature.class)
- .register(jacksonJsonProvider)
- .register(loggingFeature)
- .property("jersey.config.server.provider.classnames", "org.openecomp.sdc.be.view.MixinModelWriter")
- .property("contextConfig", context);
+ .register(new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .register(RolesAllowedDynamicFeature.class)
+ .register(DefaultExceptionMapper.class)
+ .register(ComponentExceptionMapper.class)
+ .register(StorageExceptionMapper.class)
+ .register(MultiPartFeature.class)
+ .register(jacksonJsonProvider)
+ .register(loggingFeature)
+ .property("jersey.config.server.provider.classnames", "org.openecomp.sdc.be.view.MixinModelWriter")
+ .property("contextConfig", context);
}
}
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 4d1b611..469a73d 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,8 +20,28 @@
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.anyString;
+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;
@@ -29,15 +49,14 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
import org.json.simple.JSONObject;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mockito;
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;
@@ -77,31 +96,7 @@
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{
+class PolicyServletTest extends JerseySpringBaseTest {
private final static String USER_ID = "jh0003";
private static final String COMPONENT_ID = "componentId";
@@ -131,201 +126,224 @@
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");
+ ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- @BeforeClass
+ @BeforeAll
public static void initClass() {
ResponseFormatManager.getInstance();
createMocks();
when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
}
- @Before
- public void beforeMethod() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
Mockito.reset(businessLogic);
- final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ 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);
}
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
@Test
- public void testGetPolicySuccess(){
+ void testGetPolicySuccess() {
String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
PolicyDefinition successResponse = new PolicyDefinition();
- when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID))).thenReturn(successResponse);
+ when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID)))
+ .thenReturn(successResponse);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get(Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
}
@Test
- public void testGetPolicyFailure(){
+ void testGetPolicyFailure() {
String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get(Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
}
-
+
@Test
- public void testPostPolicySuccess(){
+ void testPostPolicySuccess() {
String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName;
PolicyDefinition policy = new PolicyDefinition();
PolicyDefinition successResponse = policy;
- when(businessLogic.createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ 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);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
assertEquals(response.getStatus(), HttpStatus.CREATED_201.getStatusCode());
}
-
+
@Test
- public void testPostPolicyFailure(){
+ void testPostPolicyFailure() {
String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName;
PolicyDefinition policy = new PolicyDefinition();
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
}
-
+
@Test
- public void testPutPolicySuccess(){
+ void testPutPolicySuccess() {
String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
PolicyDefinition policy = new PolicyDefinition();
policy.setUniqueId(POLICY_ID);
PolicyDefinition successResponse = policy;
- when(businessLogic.updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ when(businessLogic
+ .updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID),
+ eq(true))).thenReturn(successResponse);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
}
-
+
@Test
- public void testPutPolicyFailure(){
+ void testPutPolicyFailure() {
String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
PolicyDefinition policy = new PolicyDefinition();
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
}
-
+
@Test
- public void testDeletePolicySuccess(){
+ void testDeletePolicySuccess() {
String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
PolicyDefinition successResponse = new PolicyDefinition();
- when(businessLogic.deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ when(businessLogic
+ .deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true)))
+ .thenReturn(successResponse);
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .delete(Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .delete(Response.class);
assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
}
@Test
- public void testDeletePolicyFailure(){
+ void testDeletePolicyFailure() {
String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .delete(Response.class);
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .delete(Response.class);
assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
}
@Test
- public void getPolicyProperties_operationForbidden() {
- // doThrow(new ComponentException(ActionStatus.GENERAL_ERROR)).when(businessLogic).getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID);
+ void getPolicyProperties_operationForbidden() {
+ // 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));
+ .thenThrow(new ByActionStatusComponentException(ActionStatus.AUTH_FAILED, USER_ID));
Response response = buildGetPropertiesRequest().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode());
}
@Test//(expected = ComponentException.class)
- public void getPolicyProperties_unHandledError_returnGeneralError() {
- when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenThrow(new RuntimeException());
+ void getPolicyProperties_unHandledError_returnGeneralError() {
+ when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID))
+ .thenThrow(new RuntimeException());
Response response = buildGetPropertiesRequest().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
@Test
- public void getPolicyProperties_wrongComponentType() {
+ void getPolicyProperties_wrongComponentType() {
Response response = buildGetPropertiesRequest("unknownType").get();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
//verifyZeroInteractions(businessLogic);
}
@Test
- public void getPolicyProperties() {
+ void getPolicyProperties() {
List<PropertyDataDefinition> properties = getPropertiesList();
- when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(properties);
- List<PropertyDataDefinition> policyProps = buildGetPropertiesRequest().get(new GenericType<List<PropertyDataDefinition>>() {});
+ 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")
- .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
- }
-
- @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(properties);
- List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(new GenericType<List<PropertyDataDefinition>>() {});
- assertThat(policyProps)
- .usingElementComparatorOnFields("uniqueId")
- .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
+ .usingElementComparatorOnFields("uniqueId")
+ .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
}
@Test
- public void updatePolicyTargetsSuccess() {
+ 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(properties);
+ List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME,
+ properties).invoke(new GenericType<List<PropertyDataDefinition>>() {
+ });
+ assertThat(policyProps)
+ .usingElementComparatorOnFields("uniqueId")
+ .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
+ }
+
+ @Test
+ void updatePolicyTargetsSuccess() {
List<PolicyTargetDTO> targets = getTargetDTOList();
- when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(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);
}
@Test
- public void updatePolicyPropertiesFailure() {
+ 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))).thenThrow(new ByResponseFormatComponentException(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());
}
@Test
- public void testDeclarePropertyToPolicySuccess() {
+ void testDeclarePropertyToPolicySuccess() {
Service service = new Service();
service.setUniqueId(SERVICE_ID);
service.addProperty(new PropertyDataDefinitionBuilder().setUniqueId(PROP_1).build());
@@ -335,14 +353,15 @@
setMocksForPropertyDeclaration(policyDefinition);
- when(componentsUtils.getResponseFormat(eq(ActionStatus.OK))).thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.OK)))
+ .thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
Response declareResponse = buildDeclarePropertiesRequest(PROP_1).invoke();
assertEquals(HttpStatus.OK_200.getStatusCode(), declareResponse.getStatus());
}
@Test
- public void testUndeclarePolicySuccess() {
+ void testUndeclarePolicySuccess() {
Service service = new Service();
service.setUniqueId(SERVICE_ID);
PropertyDefinition origProperty = new PropertyDataDefinitionBuilder().setUniqueId(PROP_1).build();
@@ -355,7 +374,9 @@
addGetPolicyValueToProperty(origProperty, policyDefinition);
- when(businessLogic.deletePolicy(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(policyDefinition.getUniqueId()), eq(USER_ID), eq(true))).thenReturn(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());
@@ -364,7 +385,8 @@
private void addGetPolicyValueToProperty(PropertyDefinition propertyDefinition,
PolicyDefinition policyDefinition) {
JSONObject jobject = new JSONObject();
- String origValue = Objects.isNull(propertyDefinition.getValue()) ? propertyDefinition.getDefaultValue() : propertyDefinition.getValue();
+ String origValue = Objects.isNull(propertyDefinition.getValue()) ? propertyDefinition.getDefaultValue()
+ : propertyDefinition.getValue();
jobject.put(GET_POLICY, null);
propertyDefinition.setValue(jobject.toJSONString());
@@ -384,21 +406,21 @@
when(contextWrapper.getWebAppContext(any())).thenReturn(applicationContext);
when(applicationContext.getBean(eq(PolicyBusinessLogic.class))).thenReturn(businessLogic);
when(businessLogic.declareProperties(eq(USER_ID), eq(SERVICE_ID), any(), any())).thenReturn(
- Either.left(Collections.singletonList(policyDefinition)));
+ Either.left(Collections.singletonList(policyDefinition)));
when(componentsUtils
- .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstInputsMap.class), eq(
- AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE)))
- .thenReturn(Either.left(getDeclarationBodyForProperty(PROP_1)));
+ .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstInputsMap.class), eq(
+ AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE)))
+ .thenReturn(Either.left(getDeclarationBodyForProperty(PROP_1)));
}
private List<PropertyDataDefinition> getPropertiesList() {
PropertyDefinition prop1 = new PropertyDataDefinitionBuilder()
- .setUniqueId("prop1")
- .build();
+ .setUniqueId("prop1")
+ .build();
PropertyDefinition prop2 = new PropertyDataDefinitionBuilder()
- .setUniqueId("prop2")
- .build();
+ .setUniqueId("prop2")
+ .build();
return Arrays.asList(prop1, prop2);
}
@@ -416,60 +438,60 @@
private Invocation.Builder buildGetPropertiesRequest(String componentType) {
return target(PROPS_URL)
- .resolveTemplate("componentType", componentType)
- .resolveTemplate("serviceId", SERVICE_ID)
- .resolveTemplate("policyId", POLICY_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
-
+
private Invocation buildUpdatePropertiesRequest(String componentType, List<PropertyDataDefinition> properties) {
return target(PROPS_URL)
- .resolveTemplate("componentType", componentType)
- .resolveTemplate("serviceId", SERVICE_ID)
- .resolveTemplate("policyId", POLICY_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID)
- .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON));
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON));
}
private Invocation buildUpdateTargetsRequest(String componentType, List<PolicyTargetDTO> targets) {
return target(UPDATE_TARGETS_URL)
- .resolveTemplate("componentType", componentType)
- .resolveTemplate("componentId", COMPONENT_ID)
- .resolveTemplate("policyId", POLICY_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID)
- .buildPost(Entity.entity(targets, MediaType.APPLICATION_JSON));
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("componentId", COMPONENT_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildPost(Entity.entity(targets, MediaType.APPLICATION_JSON));
}
private Invocation.Builder buildGetPropertiesRequest() {
return target(PROPS_URL)
- .resolveTemplate("componentType", "services")
- .resolveTemplate("serviceId", SERVICE_ID)
- .resolveTemplate("policyId", POLICY_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .resolveTemplate("componentType", "services")
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
private Invocation buildDeletePolicyRequest(PolicyDefinition policyDefinition) {
return target(DELETE_URL)
- .resolveTemplate("containerComponentType", "services")
- .resolveTemplate("componentId", SERVICE_ID)
- .resolveTemplate("policyId", policyDefinition.getUniqueId())
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID)
- .buildDelete();
+ .resolveTemplate("containerComponentType", "services")
+ .resolveTemplate("componentId", SERVICE_ID)
+ .resolveTemplate("policyId", policyDefinition.getUniqueId())
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildDelete();
}
private Invocation buildDeclarePropertiesRequest(String propertyId) {
return target(DECLARE_URL)
- .resolveTemplate("componentType", "services")
- .resolveTemplate("serviceId", SERVICE_ID)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID)
- .buildPost(Entity.entity(getDeclarationBodyForProperty(propertyId), MediaType.APPLICATION_JSON));
+ .resolveTemplate("componentType", "services")
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildPost(Entity.entity(getDeclarationBodyForProperty(propertyId), MediaType.APPLICATION_JSON));
}
private ComponentInstInputsMap getDeclarationBodyForProperty(String propertyId) {
@@ -483,7 +505,8 @@
propInput.setPropertiesName(propertyId);
componentInstInputsMap.setComponentInstancePropertiesToPolicies(new HashMap<>());
- componentInstInputsMap.getComponentInstancePropertiesToPolicies().put("componentInstancePropertiesToPolicies", Collections.singletonList(propInput));
+ componentInstInputsMap.getComponentInstancePropertiesToPolicies()
+ .put("componentInstancePropertiesToPolicies", Collections.singletonList(propInput));
return componentInstInputsMap;
}
@@ -492,8 +515,8 @@
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
return super.configure()
- .register(new PolicyServlet(null, null, componentsUtils,
- servletUtils, null, businessLogic));
+ .register(new PolicyServlet(null, null, componentsUtils,
+ servletUtils, null, businessLogic));
}
private static void createMocks() {
@@ -519,15 +542,15 @@
private static class BaseBusinessLogicTest extends BaseBusinessLogic {
BaseBusinessLogicTest(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
+ IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactsOperations artifactToscaOperation) {
super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
interfaceLifecycleTypeOperation, artifactToscaOperation);
}
}
-
+
}
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 d84ac90..34377b0 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,10 +20,21 @@
package org.openecomp.sdc.be.servlets;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
import org.apache.http.HttpStatus;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -33,23 +44,23 @@
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.core.GenericType;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class PolicyTypesEndpointTest extends JerseySpringBaseTest {
+class PolicyTypesEndpointTest extends JerseySpringBaseTest {
public static final String USER_ID = "userId";
public static final String COMPONENT_TYPE = "VF";
private PolicyTypeBusinessLogic policyTypeBusinessLogic;
private ComponentsUtils componentUtils;
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
@@ -58,77 +69,82 @@
UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class);
ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
return super.configure()
- .register(new PolicyTypesEndpoint(userBusinessLogic, componentsUtils, policyTypeBusinessLogic));
+ .register(new PolicyTypesEndpoint(userBusinessLogic, componentsUtils, policyTypeBusinessLogic));
}
@Test
- public void getPolicyTypes() {
+ void getPolicyTypes() {
List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList();
when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(policyTypes);
when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK));
- List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCall().get(new GenericType<List<PolicyTypeDefinition>>(){});
+ List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCall()
+ .get(new GenericType<List<PolicyTypeDefinition>>() {
+ });
verifyPolicyTypesList(policyTypes, fetchedPolicyTypes);
}
@Test
- public void getPolicyTypes_whenNoInternalComponent_passNullAsComponentType() {
+ void getPolicyTypes_whenNoInternalComponent_passNullAsComponentType() {
List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList();
when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, null)).thenReturn(policyTypes);
when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK));
- List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCallNoInternalComponent().get(new GenericType<List<PolicyTypeDefinition>>(){});
+ List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCallNoInternalComponent()
+ .get(new GenericType<List<PolicyTypeDefinition>>() {
+ });
verifyPolicyTypesList(policyTypes, fetchedPolicyTypes);
}
- private void verifyPolicyTypesList(List<PolicyTypeDefinition> policyTypes, List<PolicyTypeDefinition> fetchedPolicyTypes) {
+ private void verifyPolicyTypesList(List<PolicyTypeDefinition> policyTypes,
+ List<PolicyTypeDefinition> fetchedPolicyTypes) {
assertThat(fetchedPolicyTypes)
- .usingElementComparatorOnFields("version", "type", "uniqueId", "name", "icon")
- .isEqualTo(policyTypes);
- assertThat(fetchedPolicyTypes).extracting("derivedFrom")//derivedFrom is not on the PolicyTypeMixin and should not return in response
- .containsOnly((String)null);
+ .usingElementComparatorOnFields("version", "type", "uniqueId", "name", "icon")
+ .isEqualTo(policyTypes);
+ assertThat(fetchedPolicyTypes)
+ .extracting("derivedFrom")//derivedFrom is not on the PolicyTypeMixin and should not return in response
+ .containsOnly((String) null);
}
private Invocation.Builder buildGetPolicyTypesCall() {
return target("/v1/catalog/policyTypes")
- .queryParam("internalComponentType", COMPONENT_TYPE)
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .queryParam("internalComponentType", COMPONENT_TYPE)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
private Invocation.Builder buildGetPolicyTypesCallNoInternalComponent() {
return target("/v1/catalog/policyTypes")
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, USER_ID);
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
}
private List<PolicyTypeDefinition> buildPolicyTypesList() {
PolicyTypeDefinition type1 = new PolicyTypeBuilder()
- .setDerivedFrom("root")
- .setType("type1")
- .setUniqueId("id1")
- .setVersion("1.0")
- .setName("type1name")
- .setIcon("type1Icon")
- .build();
+ .setDerivedFrom("root")
+ .setType("type1")
+ .setUniqueId("id1")
+ .setVersion("1.0")
+ .setName("type1name")
+ .setIcon("type1Icon")
+ .build();
PolicyTypeDefinition type2 = new PolicyTypeBuilder()
- .setDerivedFrom("type1")
- .setType("type2")
- .setUniqueId("id2")
- .setVersion("1.0")
- .setName("type2name")
- .setIcon("type2con")
- .build();
+ .setDerivedFrom("type1")
+ .setType("type2")
+ .setUniqueId("id2")
+ .setVersion("1.0")
+ .setName("type2name")
+ .setIcon("type2con")
+ .build();
PolicyTypeDefinition type3 = new PolicyTypeBuilder()
- .setDerivedFrom("root")
- .setType("type3")
- .setUniqueId("id3")
- .setVersion("1.0")
- .setName("type3name")
- .setIcon("type3con")
- .build();
+ .setDerivedFrom("root")
+ .setType("type3")
+ .setUniqueId("id3")
+ .setVersion("1.0")
+ .setName("type3name")
+ .setIcon("type3con")
+ .build();
return asList(type1, type2, type3);
}
-
}
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 6c1c447..36612eb 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
@@ -7,9 +7,9 @@
* 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.
@@ -22,9 +22,29 @@
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.eq;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.when;
+
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fj.data.Either;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+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 org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.text.StrSubstitutor;
@@ -35,9 +55,10 @@
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.json.JSONException;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
@@ -68,41 +89,21 @@
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.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+class ResourceServletTest extends JerseyTest {
-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.BDDMockito.given;
-import static org.mockito.Mockito.when;
-
-public class ResourceServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
- private static final HttpSession session = Mockito.mock(HttpSession.class);
- private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- private static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
- private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- private static final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
- private static final GroupBusinessLogic groupBL = Mockito.mock(GroupBusinessLogic.class);
- private static final ComponentInstanceBusinessLogic componentInstanceBL = Mockito.mock(ComponentInstanceBusinessLogic.class);
- private static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
+ private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
+ private final HttpSession session = Mockito.mock(HttpSession.class);
+ private final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ private final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ private final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
+ private final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
+ private final GroupBusinessLogic groupBL = Mockito.mock(GroupBusinessLogic.class);
+ private final ComponentInstanceBusinessLogic componentInstanceBL = Mockito.mock(ComponentInstanceBusinessLogic.class);
+ private final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static final ResponseFormat okResponseFormat = new ResponseFormat(HttpStatus.SC_OK);
private static final ResponseFormat conflictResponseFormat = new ResponseFormat(HttpStatus.SC_CONFLICT);
@@ -111,8 +112,8 @@
private static final ResponseFormat noContentResponseFormat = new ResponseFormat(HttpStatus.SC_NO_CONTENT);
private static final ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
private static final ResponseFormat badRequestResponseFormat = new ResponseFormat(HttpStatus.SC_BAD_REQUEST);
- private static final ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration
- .getChangeListener(), "src/test/resources/config/catalog-be");
+ private static final ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ "src/test/resources/config/catalog-be");
private static final ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
private static final String RESOURCE_NAME = "resourceName";
private static final String VERSION = "version";
@@ -122,17 +123,30 @@
private static final String CSAR_UUID = "csaruuid";
private static final String EMPTY_JSON = "{}";
private static final String NON_UI_IMPORT_JSON = "{\n" +
- " \"node1\": \"value1\",\n" +
- " \"node2\": {\n" +
- " \"level21\": \"value21\",\n" +
- " \"level22\": \"value22\"\n" +
- " }\n" +
- "}";
+ " \"node1\": \"value1\",\n" +
+ " \"node2\": {\n" +
+ " \"level21\": \"value21\",\n" +
+ " \"level22\": \"value22\"\n" +
+ " }\n" +
+ "}";
private static User user;
- @BeforeClass
+ @BeforeAll
public static void setup() {
ExternalConfiguration.setAppName("catalog-be");
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
+ @BeforeEach
+ public void beforeTest() throws Exception {
+ super.setUp();
+ Mockito.reset(componentUtils);
+ Mockito.reset(resourceBusinessLogic);
+
when(request.getSession()).thenReturn(session);
when(session.getServletContext()).thenReturn(servletContext);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
@@ -147,28 +161,22 @@
user.setRole(Role.ADMIN.name());
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);
- when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(pair);
+ when(resourceImportManager
+ .importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean()))
+ .thenReturn(pair);
when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic);
- }
-
- @Before
- public void beforeTest() {
- Mockito.reset(componentUtils);
- Mockito.reset(resourceBusinessLogic);
-
- when(componentUtils.getResponseFormat(ActionStatus.OK)) .thenReturn(okResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat);
when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(createdResponseFormat);
when(componentUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(noContentResponseFormat);
when(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(badRequestResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)) .thenReturn(generalErrorResponseFormat);
- when(componentUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND)) .thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(generalErrorResponseFormat);
+ when(componentUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND)).thenReturn(notFoundResponseFormat);
}
@Test
- public void testHappyScenarioTest() {
+ void testHappyScenarioTest() {
when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(createdResponseFormat);
UploadResourceInfo validJson = buildValidJson();
@@ -182,20 +190,21 @@
}
@Test
- public void testNonValidMd5Fail() {
+ void testNonValidMd5Fail() {
UploadResourceInfo validJson = buildValidJson();
setMD5OnRequest(false, validJson);
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON)
+ .post(Entity.json(gson.toJson(validJson)), Response.class);
Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
- assertEquals(response.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus());
}
@Test
- public void testNonValidPayloadNameFail() {
+ void testNonValidPayloadNameFail() {
UploadResourceInfo mdJson = buildValidJson();
mdJson.setPayloadName("myCompute.xml");
@@ -204,7 +213,7 @@
}
@Test
- public void testNullPayloadFail() {
+ void testNullPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
mdJson.setPayloadData(null);
runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD);
@@ -212,7 +221,7 @@
}
@Test
- public void testNonYmlPayloadFail() {
+ void testNonYmlPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
String payload = "{ json : { isNot : yaml } ";
encodeAndSetPayload(mdJson, payload);
@@ -221,20 +230,23 @@
}
@Test
- public void testNonToscaPayloadFail() {
+ void testNonToscaPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
- String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
+ String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n"
+ + " description: update update";
encodeAndSetPayload(mdJson, payload);
runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE);
}
@Test
- public void testServiceToscaPayloadFail() {
+ void testServiceToscaPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
- String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n"
+ String payload =
+ "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n"
+ + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n"
+ " description: update update";
encodeAndSetPayload(mdJson, payload);
@@ -243,10 +255,12 @@
}
@Test
- public void testMultipleResourcesInPayloadFail() {
+ void testMultipleResourcesInPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
- String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n"
+ String payload =
+ "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n"
+ + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n"
+ " derived_from: tosca.nodes.Root\r\n" + " description: update update";
encodeAndSetPayload(mdJson, payload);
@@ -255,7 +269,7 @@
}
@Test
- public void testNonValidNameSpaceInPayloadFail() {
+ void testNonValidNameSpaceInPayloadFail() {
UploadResourceInfo mdJson = buildValidJson();
String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n"
@@ -267,716 +281,732 @@
}
@Test
- public void deleteResourceTryDeleteNonExistingResourceTest() {
+ void deleteResourceTryDeleteNonExistingResourceTest() {
String resourceId = "resourceId";
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put("resourceId", resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResource(any(), any(User.class)))
- .thenReturn(notFoundResponseFormat);
+ .thenReturn(notFoundResponseFormat);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
}
@Test
- public void deleteResourceExceptionDuringDeletingTest() {
+ void deleteResourceExceptionDuringDeletingTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResource(any(), any(User.class)))
- .thenThrow(new JSONException("Test exception: deleteResource"));
+ .thenThrow(new JSONException("Test exception: deleteResource"));
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void deleteResourceCategoryTest() {
+ void deleteResourceCategoryTest() {
String resourceId = "resourceId";
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put("resourceId", resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResource(eq(resourceId.toLowerCase()), any(User.class)))
- .thenReturn(noContentResponseFormat);
+ .thenReturn(noContentResponseFormat);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(org.apache.http.HttpStatus.SC_NO_CONTENT);
}
@Test
- public void deleteResourceByNameAndVersionTryDeleteNonExistingResourceTest() {
+ void deleteResourceByNameAndVersionTryDeleteNonExistingResourceTest() {
String resourceName = RESOURCE_NAME;
String version = VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(VERSION, version);
String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
- .thenReturn(notFoundResponseFormat);
+ .thenReturn(notFoundResponseFormat);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
}
@Test
- public void deleteResourceByNameAndVersionExceptionDuringDeletingTest() {
+ void deleteResourceByNameAndVersionExceptionDuringDeletingTest() {
String resourceName = RESOURCE_NAME;
String version = VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(VERSION, version);
String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
- .thenThrow(new JSONException("Test exception: deleteResourceByNameAndVersion"));
+ .thenThrow(new JSONException("Test exception: deleteResourceByNameAndVersion"));
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void deleteResourceByNameAndVersionCategoryTest() {
+ void deleteResourceByNameAndVersionCategoryTest() {
String resourceName = RESOURCE_NAME;
String version = VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(VERSION, version);
String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
- .thenReturn(noContentResponseFormat);
+ .thenReturn(noContentResponseFormat);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .delete();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .delete();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
}
@Test
- public void getResourceByIdTryGetNonExistingResourceTest() {
+ void getResourceByIdTryGetNonExistingResourceTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> getResourceByIdEither = Either.right(notFoundResponseFormat);
when(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
- .thenReturn(getResourceByIdEither);
+ .thenReturn(getResourceByIdEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
}
@Test
- public void getResourceByIdExceptionDuringSearchingTest() {
+ void getResourceByIdExceptionDuringSearchingTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
given(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
- .willAnswer( invocation -> { throw new IOException("Test exception: getResourceById"); });
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: getResourceById");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void getResourceByIdTest() {
+ void getResourceByIdTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> getResourceByIdEither = Either.left(new Resource());
when(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
- .thenReturn(getResourceByIdEither);
+ .thenReturn(getResourceByIdEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void getResourceByNameAndVersionTryGetNonExistingResourceTest() {
+ void getResourceByNameAndVersionTryGetNonExistingResourceTest() {
String resourceName = RESOURCE_NAME;
String resourceVersion = RESOURCE_VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(RESOURCE_VERSION, resourceVersion);
String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> getResourceByNameAndVersionEither = Either.right(notFoundResponseFormat);
when(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
- .thenReturn(getResourceByNameAndVersionEither);
+ .thenReturn(getResourceByNameAndVersionEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
}
@Test
- public void getResourceByNameAndVersionExceptionDuringSearchingTest() {
+ void getResourceByNameAndVersionExceptionDuringSearchingTest() {
String resourceName = RESOURCE_NAME;
String resourceVersion = RESOURCE_VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(RESOURCE_VERSION, resourceVersion);
String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
given(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
- .willAnswer( invocation -> { throw new IOException("Test exception: getResourceByNameAndVersion"); });
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: getResourceByNameAndVersion");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void getResourceByNameAndVersionTest() {
+ void getResourceByNameAndVersionTest() {
String resourceName = RESOURCE_NAME;
String resourceVersion = RESOURCE_VERSION;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
parametersMap.put(RESOURCE_VERSION, resourceVersion);
String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> getResourceByNameAndVersionEither = Either.left(new Resource());
when(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
- .thenReturn(getResourceByNameAndVersionEither);
+ .thenReturn(getResourceByNameAndVersionEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void validateResourceNameTryValidateNonExistingResourceTest() {
+ void validateResourceNameTryValidateNonExistingResourceTest() {
String resourceName = RESOURCE_NAME;
String resourceType = "VFC";
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Map<String, Boolean>, ResponseFormat> validateResourceNameEither =
- Either.right(notFoundResponseFormat);
+ Either.right(notFoundResponseFormat);
ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.valueOf(resourceType);
when(resourceBusinessLogic.validateResourceNameExists(eq(resourceName), eq(resourceTypeEnum), eq(user.getUserId())))
- .thenReturn(validateResourceNameEither);
+ .thenReturn(validateResourceNameEither);
Response response = target()
- .path(path)
- .queryParam(SUBTYPE, resourceType)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .queryParam(SUBTYPE, resourceType)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
}
@Test
- public void validateResourceNameInvalidContentTest() {
+ void validateResourceNameInvalidContentTest() {
String resourceName = RESOURCE_NAME;
String resourceType = "ThisIsInvalid";
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Response response = target()
- .path(path)
- .queryParam(SUBTYPE, resourceType)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .queryParam(SUBTYPE, resourceType)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void validateResourceNameTest() {
+ void validateResourceNameTest() {
String resourceName = RESOURCE_NAME;
String resourceType = "VFC";
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_NAME, resourceName);
String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Map<String, Boolean>, ResponseFormat> validateResourceNameEither =
- Either.left(new HashMap<>());
+ Either.left(new HashMap<>());
ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.valueOf(resourceType);
when(resourceBusinessLogic.validateResourceNameExists(eq(resourceName), eq(resourceTypeEnum), eq(user.getUserId())))
- .thenReturn(validateResourceNameEither);
+ .thenReturn(validateResourceNameEither);
Response response = target()
- .path(path)
- .queryParam(SUBTYPE, resourceType)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .queryParam(SUBTYPE, resourceType)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void getCertifiedAbstractResourcesExceptionDuringSearchingTest() {
+ void getCertifiedAbstractResourcesExceptionDuringSearchingTest() {
String path = "/v1/catalog/resources/certified/abstract";
given(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.HIGHEST_ONLY),
- eq(user.getUserId())))
- .willAnswer( invocation -> { throw new IOException("Test exception: getCertifiedAbstractResources"); });
+ eq(user.getUserId())))
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: getCertifiedAbstractResources");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void getCertifiedAbstractResourcesTest() {
+ void getCertifiedAbstractResourcesTest() {
String path = "/v1/catalog/resources/certified/abstract";
List<Resource> resources = Arrays.asList(new Resource(), new Resource());
when(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.HIGHEST_ONLY),
- eq(user.getUserId())))
- .thenReturn(resources);
+ eq(user.getUserId())))
+ .thenReturn(resources);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void getCertifiedNotAbstractResourcesExceptionDuringSearchingTest() {
+ void getCertifiedNotAbstractResourcesExceptionDuringSearchingTest() {
String path = "/v1/catalog/resources/certified/notabstract";
given(resourceBusinessLogic.getAllCertifiedResources(eq(false), eq(HighestFilterEnum.ALL),
- eq(user.getUserId())))
- .willAnswer( invocation -> { throw new IOException("Test exception: getCertifiedNotAbstractResources"); });
+ eq(user.getUserId())))
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: getCertifiedNotAbstractResources");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void getCertifiedNotAbstractResourcesTest() {
+ void getCertifiedNotAbstractResourcesTest() {
String path = "/v1/catalog/resources/certified/notabstract";
List<Resource> resources = Arrays.asList(new Resource(), new Resource());
when(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.ALL),
- eq(user.getUserId())))
- .thenReturn(resources);
+ eq(user.getUserId())))
+ .thenReturn(resources);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void updateResourceMetadataTryUpdateNonExistingResourceTest() {
+ void updateResourceMetadataTryUpdateNonExistingResourceTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> updateResourceMetadataEither = Either.right(badRequestResponseFormat);
when(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
- eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(updateResourceMetadataEither);
+ eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(updateResourceMetadataEither);
when(resourceBusinessLogic.updateResourceMetadata(eq(resourceId.toLowerCase()), any(), any(), any(User.class),
- eq(false)))
- .thenReturn(new Resource());
+ eq(false)))
+ .thenReturn(new Resource());
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(EMPTY_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(EMPTY_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void updateResourceMetadataExceptionDuringUpdateTest() {
+ void updateResourceMetadataExceptionDuringUpdateTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
given(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
- eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .willAnswer( invocation -> { throw new IOException("Test exception: updateResourceMetadata"); });
+ eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: updateResourceMetadata");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(EMPTY_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(EMPTY_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void updateResourceMetadataCategoryTest() {
+ void updateResourceMetadataCategoryTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Resource initialResource = new Resource();
Either<Resource, ResponseFormat> updateResourceMetadataEither = Either.left(initialResource);
when(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
- eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(updateResourceMetadataEither);
+ eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(updateResourceMetadataEither);
when(resourceBusinessLogic.updateResourceMetadata(eq(resourceId.toLowerCase()), eq(initialResource), any(),
- any(User.class), eq(false)))
- .thenReturn(new Resource());
+ any(User.class), eq(false)))
+ .thenReturn(new Resource());
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(EMPTY_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(EMPTY_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void updateResourceParsingUncussessfulTest() {
+ void updateResourceParsingUncussessfulTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> updateResourceEither = Either.right(badRequestResponseFormat);
when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
- eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(updateResourceEither);
+ eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(updateResourceEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void updateResourceExceptionDuringUpdateTest() {
+ void updateResourceExceptionDuringUpdateTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
given(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
- eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .willAnswer( invocation -> { throw new IOException("Test exception: updateResource"); });
+ eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: updateResource");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void updateResourceNonUiImportTest() {
+ void updateResourceNonUiImportTest() {
String resourceId = RESOURCE_ID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(RESOURCE_ID, resourceId);
String formatEndpoint = "/v1/catalog/resources/{resourceId}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> updateResourceEither = Either.left(new Resource());
when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class), eq(Resource.class),
- eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(updateResourceEither);
+ eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(updateResourceEither);
when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(), any(), any(), any(), eq(resourceId)))
- .thenReturn(new Resource());
+ .thenReturn(new Resource());
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .put(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .put(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void getResourceFromCsarTryGetNonExistingResourceTest() {
+ void getResourceFromCsarTryGetNonExistingResourceTest() {
String csarUuid = CSAR_UUID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(CSAR_UUID, csarUuid);
String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
-
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
+
Either<Resource, ResponseFormat> getResourceFromCsarEither = Either.right(notFoundResponseFormat);
when(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
- .thenReturn(getResourceFromCsarEither);
+ .thenReturn(getResourceFromCsarEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void getResourceFromCsarExceptionDuringGettingTest() {
+ void getResourceFromCsarExceptionDuringGettingTest() {
String csarUuid = CSAR_UUID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(CSAR_UUID, csarUuid);
String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
given(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
- .willAnswer( invocation -> { throw new IOException("Test exception: getResourceFromCsar"); });
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: getResourceFromCsar");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void getResourceFromCsarTest() {
+ void getResourceFromCsarTest() {
String csarUuid = CSAR_UUID;
- Map<String,String> parametersMap = new HashMap<>();
+ Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(CSAR_UUID, csarUuid);
String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
- String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
+ String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{", "}");
Either<Resource, ResponseFormat> getResourceFromCsarEither = Either.left(new Resource());
when(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
- .thenReturn(getResourceFromCsarEither);
+ .thenReturn(getResourceFromCsarEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .get();
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
}
@Test
- public void createResourceExceptionDuringCreateTest() {
+ void createResourceExceptionDuringCreateTest() {
String path = "/v1/catalog/resources";
given(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
- eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
- .willAnswer( invocation -> { throw new IOException("Test exception: createResource"); });
+ eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
+ .willAnswer(invocation -> {
+ throw new IOException("Test exception: createResource");
+ });
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .post(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .post(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
@Test
- public void createResourceNonUiImportProcessingFailedTest() {
+ void createResourceNonUiImportProcessingFailedTest() {
String path = "/v1/catalog/resources";
Either<Resource, ResponseFormat> createResourceEither = Either.right(badRequestResponseFormat);
when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
- eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(createResourceEither);
+ eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(createResourceEither);
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .post(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .post(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void createResourceNonUiImportTest() {
+ void createResourceNonUiImportTest() {
String path = "/v1/catalog/resources";
Either<Resource, ResponseFormat> createResourceEither = Either.left(new Resource());
when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
- eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
- .thenReturn(createResourceEither);
+ eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
+ .thenReturn(createResourceEither);
when(resourceBusinessLogic.createResource(eq(createResourceEither.left().value()), eq(AuditingActionEnum.CREATE_RESOURCE),
- any(User.class), any(), any()))
- .thenReturn(new Resource());
+ any(User.class), any(), any()))
+ .thenReturn(new Resource());
Response response = target()
- .path(path)
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, user.getUserId())
- .post(Entity.json(NON_UI_IMPORT_JSON));
+ .path(path)
+ .request()
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, user.getUserId())
+ .post(Entity.json(NON_UI_IMPORT_JSON));
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
}
@@ -988,10 +1018,11 @@
private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) {
setMD5OnRequest(true, mdJson);
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class);
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON)
+ .post(Entity.json(gson.toJson(mdJson)), Response.class);
Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload);
- assertEquals(response.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus());
}
private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) {
@@ -1012,7 +1043,7 @@
ret.setIcon("router");
ret.setTags(Collections.singletonList("ciMyCompute"));
ret.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
+ "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
return ret;
}
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 c649f71..c948910 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,8 +20,26 @@
package org.openecomp.sdc.be.servlets;
+import static java.util.Collections.emptyMap;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+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.doNothing;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
import fj.data.Either;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.jersey.client.ClientConfig;
@@ -34,8 +52,10 @@
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.CommonImportManager;
import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -55,26 +75,7 @@
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.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-import static java.util.Collections.emptyMap;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
-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.doNothing;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class TypesUploadEndpointTest extends JerseySpringBaseTest {
+class TypesUploadEndpointTest extends JerseySpringBaseTest {
static final String userId = "jh0003";
@@ -92,7 +93,8 @@
TypesUploadEndpoint typesUploadEndpoint() {
UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class);
ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
- return new TypesUploadEndpoint(userBusinessLogic, componentsUtils, commonImportManager(), annotationTypeOperations(), accessValidations);
+ return new TypesUploadEndpoint(userBusinessLogic, componentsUtils, commonImportManager(),
+ annotationTypeOperations(), accessValidations);
}
@Bean
@@ -111,7 +113,7 @@
}
}
- @BeforeClass
+ @BeforeAll
public static void initClass() {
janusGraphGenericDao = mock(HealingJanusGraphGenericDao.class);
accessValidations = mock(AccessValidations.class);
@@ -120,10 +122,20 @@
operationUtils = Mockito.mock(OperationUtils.class);
}
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Override
protected void configureClient(ClientConfig config) {
final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
- .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
config.register(MultiPartFeature.class);
}
@@ -132,31 +144,37 @@
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
return super.configure(TypesUploadEndpointTest.TypesUploadTestConfig.class)
- .register(TypesUploadEndpoint.class)
- .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
+ .register(TypesUploadEndpoint.class)
+ .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
}
@Test
- public void creatingAnnotationTypeSuccessTest() {
+ void creatingAnnotationTypeSuccessTest() {
doNothing().when(accessValidations).validateUserExists(eq(userId), anyString());
- when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
- when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
- when(janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right(
- JanusGraphOperationStatus.NOT_FOUND));
- when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList())).thenReturn(Either.left(emptyMap()));
+ when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class)))
+ .thenReturn(Either.left(new AnnotationTypeData()));
+ when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"),
+ eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
+ when(
+ janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class)))
+ .thenReturn(Either.right(
+ JanusGraphOperationStatus.NOT_FOUND));
+ when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList()))
+ .thenReturn(Either.left(emptyMap()));
when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn(
JanusGraphOperationStatus.OK);
when(propertyOperation.getJanusGraphGenericDao()).thenReturn(janusGraphGenericDao);
when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
- FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip", new File("src/test/resources/types/annotationTypes.zip"));
+ FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip",
+ new File("src/test/resources/types/annotationTypes.zip"));
MultiPart multipartEntity = new FormDataMultiPart();
multipartEntity.bodyPart(filePart);
Response response = target().path("/v1/catalog/uploadType/annotationtypes")
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId)
- .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId)
+ .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED_201);
assertThat(Boolean.valueOf(getTypeActionResult(response))).isTrue();
}
@@ -168,40 +186,46 @@
if (indexColon > 0) {
int indexCurly = body.indexOf('}', indexColon);
if (indexCurly > 0) {
- typeResult = body.substring(indexColon+1, indexCurly);
+ typeResult = body.substring(indexColon + 1, indexCurly);
}
}
return typeResult;
}
@Test
- public void creatingAnnotationTypeFailureTest() {
+ void creatingAnnotationTypeFailureTest() {
doNothing().when(accessValidations).validateUserExists(eq(userId), anyString());
- when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
- when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
- when(janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right(
- JanusGraphOperationStatus.NOT_FOUND));
- when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList())).thenThrow(new StorageException(
- JanusGraphOperationStatus.MATCH_NOT_FOUND));
+ when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class)))
+ .thenReturn(Either.left(new AnnotationTypeData()));
+ when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"),
+ eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData()));
+ when(
+ janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class)))
+ .thenReturn(Either.right(
+ JanusGraphOperationStatus.NOT_FOUND));
+ when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList()))
+ .thenThrow(new StorageException(
+ JanusGraphOperationStatus.MATCH_NOT_FOUND));
when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn(
JanusGraphOperationStatus.OK);
when(propertyOperation.getJanusGraphGenericDao()).thenReturn(janusGraphGenericDao);
when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
- FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip", new File("src/test/resources/types/annotationTypes.zip"));
+ FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip",
+ new File("src/test/resources/types/annotationTypes.zip"));
MultiPart multipartEntity = new FormDataMultiPart();
multipartEntity.bodyPart(filePart);
Response response = target().path("/v1/catalog/uploadType/annotationtypes")
- .request(MediaType.APPLICATION_JSON)
- .header(Constants.USER_ID_HEADER, userId)
- .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId)
+ .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400);
assertThat(Boolean.valueOf(getTypeActionResult(response))).isFalse();
}
@Test
- public void singleTypeSucceeded_statusIsCreated() {
+ void singleTypeSucceeded_statusIsCreated() {
List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typeActionResults = new ArrayList<>();
AnnotationTypeDefinition dummyDefition = new AnnotationTypeDefinition();
typeActionResults.add(new ImmutablePair(dummyDefition, true));
@@ -209,7 +233,7 @@
}
@Test
- public void singleTypeExists_statusIsConflict() {
+ void singleTypeExists_statusIsConflict() {
List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typeActionResults = new ArrayList<>();
AnnotationTypeDefinition dummyDefition = new AnnotationTypeDefinition();
typeActionResults.add(new ImmutablePair(dummyDefition, null));
@@ -217,7 +241,7 @@
}
@Test
- public void mixedSuccessAndExists_statusIsCreated() {
+ void mixedSuccessAndExists_statusIsCreated() {
List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typeActionResults = new ArrayList<>();
AnnotationTypeDefinition dummyDefition = new AnnotationTypeDefinition();
typeActionResults.add(new ImmutablePair(dummyDefition, true));
@@ -226,7 +250,7 @@
}
@Test
- public void mixedSuccessAndFailure_statusIsBadRequest() {
+ void mixedSuccessAndFailure_statusIsBadRequest() {
List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typeActionResults = new ArrayList<>();
AnnotationTypeDefinition dummyDefition = new AnnotationTypeDefinition();
typeActionResults.add(new ImmutablePair(dummyDefition, true));
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 5c6b7c9..993e68b 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
@@ -7,9 +7,9 @@
* 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.
@@ -20,7 +20,19 @@
package org.openecomp.sdc.be.servlets;
+import static java.util.Collections.emptyList;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
+import java.io.File;
+import java.util.List;
+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 org.apache.commons.lang3.tuple.ImmutablePair;
import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
@@ -32,8 +44,10 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -55,20 +69,7 @@
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.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.util.List;
-
-import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.when;
-
-public class TypesUploadServletTest extends JerseyTest {
+class TypesUploadServletTest extends JerseyTest {
public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
private static final HttpSession session = Mockito.mock(HttpSession.class);
@@ -81,10 +82,11 @@
private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
- @BeforeClass
+ @BeforeAll
public static void setup() {
ExternalConfiguration.setAppName("catalog-be");
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager);
when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
@@ -101,17 +103,30 @@
}
+ @BeforeEach
+ public void before() throws Exception {
+ super.setUp();
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
+ }
+
@Test
- public void creatingCapabilityTypeSuccessTest() {
- Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> either = Either.left(emptyList());
+ void creatingCapabilityTypeSuccessTest() {
+ Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> either = Either
+ .left(emptyList());
when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either);
- FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", new File("src/test/resources/types/capabilityTypes.zip"));
+ FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip",
+ new File("src/test/resources/types/capabilityTypes.zip"));
MultiPart multipartEntity = new FormDataMultiPart();
multipartEntity.bodyPart(filePart);
- Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
+ Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON)
+ .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
- assertEquals(response.getStatus(), HttpStatus.CREATED_201);
+ assertEquals(HttpStatus.CREATED_201, response.getStatus());
}
@@ -123,37 +138,37 @@
@Override
protected ResourceConfig configure() {
-
- forceSet(TestProperties.CONTAINER_PORT, "0");
TypesUploadServlet typesUploadServlet = new TypesUploadServlet(null, null, componentUtils,
servletUtils, null, importManager, null,
null, null,
null, null, null);
ResourceConfig resourceConfig = new ResourceConfig()
- .register(typesUploadServlet);
+ .register(typesUploadServlet);
resourceConfig.register(MultiPartFeature.class);
resourceConfig.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()) {
+ @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(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader);
- }
+ }
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- }
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
+ .thenReturn(configurationManager);
+ }
});
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
resourceConfig.property("contextConfig", context);
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
index 3e83199..ad97e02 100644
--- 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
@@ -20,8 +20,22 @@
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.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;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
import fj.data.Either;
+import java.util.ArrayList;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
@@ -31,9 +45,10 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
import org.janusgraph.graphdb.types.system.EmptyVertex;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.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;
@@ -54,26 +69,11 @@
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;
+class UserEndpointTest extends JerseySpringBaseTest {
-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 final String USER_ID = "jh0003";
+ private static final String NEW_USER_ID = "ab0001";
+ private static final String MODIFIER_ID = "admin1";
private static ComponentsUtils componentUtils;
private static JanusGraphGenericDao janusGraphGenericDao;
@@ -81,7 +81,6 @@
private static LifecycleBusinessLogic lifecycleBusinessLogic;
private static UserOperation facadeUserOperation;
-
private UserData userData = new UserData();
private UserData modifierData = new UserData();
@@ -102,7 +101,8 @@
@Bean
UserBusinessLogicExt userBusinessLogicExt() {
- return new UserBusinessLogicExt(userBusinessLogic(), userAdminOperation(), lifecycleBusinessLogic, componentUtils);
+ return new UserBusinessLogicExt(userBusinessLogic(), userAdminOperation(), lifecycleBusinessLogic,
+ componentUtils);
}
@Bean
@@ -111,7 +111,7 @@
}
}
- @BeforeClass
+ @BeforeAll
public static void initClass() {
janusGraphGenericDao = mock(JanusGraphGenericDao.class);
componentUtils = mock(ComponentsUtils.class);
@@ -120,18 +120,26 @@
facadeUserOperation = mock(UserOperation.class);
}
- @Before
- public void setup() {
+ @BeforeEach
+ public void before() throws Exception {
+ super.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));
+ .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));
+ }
+
+ @AfterEach
+ void after() throws Exception {
+ super.tearDown();
}
private void setUserProperties(UserData user, String userId, Role role, UserStatusEnum statusEnum) {
@@ -143,7 +151,7 @@
@Override
protected void configureClient(ClientConfig config) {
final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
- .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config.register(jacksonJsonProvider);
config.register(MultiPartFeature.class);
}
@@ -152,50 +160,50 @@
protected ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "0");
return super.configure(UserEndpointTest.UserTestConfig.class)
- .register(UserAdminServlet.class)
- .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
+ .register(UserAdminServlet.class)
+ .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
}
@Test
- public void getUser_success() {
+ 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);
+ .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() {
+ 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);
+ .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() {
+ 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));
+ .thenReturn(Either.left(emptyVertex));
when(janusGraphGenericDao.getOutgoingEdgesByCriteria(eq(emptyVertex), eq(GraphEdgeLabels.STATE), any()))
- .thenReturn(Either.left(new ArrayList<>()));
+ .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);
+ .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() {
+ void createUser_success() {
User newUser = new User();
newUser.setUserId(NEW_USER_ID);
UserData updatedUser = new UserData();
@@ -203,9 +211,9 @@
//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);
+ .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);
@@ -213,33 +221,33 @@
}
@Test
- public void authorizeUser_success() {
+ 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);
+ .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() {
+ 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));
+ .thenReturn(Either.left(emptyVertex));
when(janusGraphGenericDao.getOutgoingEdgesByCriteria(eq(emptyVertex), eq(GraphEdgeLabels.STATE), any()))
- .thenReturn(Either.left(new ArrayList<>()));
+ .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);
+ .request(MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, MODIFIER_ID)
+ .delete(User.class);
assertThat(user.getUserId()).isEqualTo(USER_ID);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java
index 3e22152..3663076 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java
@@ -7,9 +7,9 @@
* 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.
@@ -20,8 +20,25 @@
package org.openecomp.sdc.be.user;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
import com.google.common.collect.Lists;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge;
@@ -46,31 +63,12 @@
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.UserAdminOperation;
-import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.api.UserRoleEnum;
import org.openecomp.sdc.common.datastructure.UserContext;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
@RunWith(MockitoJUnitRunner.class)
public class UserBusinessLogicTest {
@@ -95,7 +93,8 @@
@Before
public void setUp() {
new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
- doThrow(new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR)).when(componentsUtils).auditAdminUserActionAndThrowException(any(), any(), any(), any(), any(), any());
+ doThrow(new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR)).when(componentsUtils)
+ .auditAdminUserActionAndThrowException(any(), any(), any(), any(), any(), any());
}
@Test(expected = ComponentException.class)
@@ -110,6 +109,7 @@
@Test(expected = ComponentException.class)
public void testGetUserContextNull() {
+ ThreadLocalsHolder.setUserContext(null);
testSubject.getUser("userId");
}
@@ -127,7 +127,7 @@
String userId = "userId";
Set<String> userRoles = new HashSet<>();
userRoles.add(Role.DESIGNER.name());
- UserContext userContext = new UserContext(userId, userRoles, "test" ,"User");
+ UserContext userContext = new UserContext(userId, userRoles, "test", "User");
User user = new User();
user.setUserId(userId);
@@ -144,8 +144,7 @@
ThreadLocalsHolder.setUserContext(userContext);
User convertedUser = testSubject.getUser(userId);
assertThat(convertedUser).isEqualTo(user);
- }
- finally {
+ } finally {
ThreadLocalsHolder.setUserContext(originalUserContext);
}
}
@@ -156,7 +155,7 @@
String userId = "userId";
//Set<String> userRoles = new HashSet<>();
//userRoles.add(Role.DESIGNER.name());
- UserContext userContext = new UserContext(userId, null, "test" ,"User");
+ UserContext userContext = new UserContext(userId, null, "test", "User");
User user = new User();
user.setUserId(userId);
@@ -280,7 +279,7 @@
verify(facadeUserOperation).updateUserCache(UserOperationEnum.CREATE, newUser.getUserId(), newUser.getRole());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateUserRoleNotFound() {
User modifier = new User(MOCK_MODIFIER);
String userIdToUpdate = "";
@@ -292,7 +291,7 @@
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateUserRoleModifierWrongRole() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.DESIGNER.getName());
@@ -305,7 +304,7 @@
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateUserRoleSameId() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -317,7 +316,7 @@
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateUserRoleUpdatedNotFound() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -332,7 +331,7 @@
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateUserRoleUpdatedToInvalidRole() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -347,7 +346,7 @@
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = StorageException.class)
+ @Test(expected = StorageException.class)
public void testUpdateUserRolePendingTaskFetchFailed() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -360,7 +359,8 @@
when(userAdminOperation.getUserData(modifier.getUserId(), false)).thenReturn(Either.left(modifier));
when(userAdminOperation.getUserData(userIdToUpdate, false)).thenReturn(Either.left(updatedUser));
- when(userAdminOperation.getUserPendingTasksList(Mockito.any(), Mockito.any())).thenThrow(new StorageException(StorageOperationStatus.INCONSISTENCY));
+ when(userAdminOperation.getUserPendingTasksList(Mockito.any(), Mockito.any()))
+ .thenThrow(new StorageException(StorageOperationStatus.INCONSISTENCY));
// default test
testSubject.updateUserRole(MOCK_MODIFIER, userIdToUpdate, userRole);
@@ -394,7 +394,7 @@
verify(facadeUserOperation).updateUserCache(UserOperationEnum.CHANGE_ROLE, userIdToUpdate, UserRoleEnum.TESTER.name());
}
- @Test(expected = ComponentException.class)
+ @Test(expected = ComponentException.class)
public void testUpdateDesignerRoleListOfTasksNotEmpty_shouldFail() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -412,13 +412,13 @@
when(userAdminOperation.getUserData(userIdToUpdate, false)).thenReturn(Either.left(updatedUser));
List<Edge> list = new LinkedList<>();
list.add(new DetachedEdge("sdas", "fdfs", new HashMap<>(), Pair.with("sadas", "sadasd"), "",
- Pair.with("sadas", "sadasd"), ""));
+ Pair.with("sadas", "sadasd"), ""));
testSubject.updateUserRole(MOCK_MODIFIER, userIdToUpdate, userRole);
verify(facadeUserOperation, never()).updateUserCache(any(UserOperationEnum.class), anyString(), anyString());
}
- @Test(expected = StorageException.class)
+ @Test(expected = StorageException.class)
public void testUpdateUserRoleStorageError_shouldFail() {
User modifier = new User(MOCK_MODIFIER);
modifier.setRole(UserRoleEnum.ADMIN.getName());
@@ -478,7 +478,7 @@
public void testGetAllAdminUsers() {
Either<List<User>, ActionStatus> response = Either.left(new LinkedList<>());
when(userAdminOperation.getAllUsersWithRole(anyString(), Mockito.nullable(String.class)))
- .thenReturn(response);
+ .thenReturn(response);
assertEquals(0, testSubject.getAllAdminUsers().size());
}
@@ -486,7 +486,7 @@
public void testGetAllAdminUsersFail() {
Either<List<User>, ActionStatus> response = Either.right(ActionStatus.NOT_ALLOWED);
when(userAdminOperation.getAllUsersWithRole(anyString(), Mockito.nullable(String.class)))
- .thenReturn(response);
+ .thenReturn(response);
testSubject.getAllAdminUsers();
}
@@ -528,7 +528,7 @@
when(userAdminOperation.getUserData(modifierAttId, false)).thenReturn(value3);
Either<List<User>, ActionStatus> value = Either.left(new LinkedList<>());
when(userAdminOperation.getAllUsersWithRole(Mockito.nullable(String.class), anyString()))
- .thenReturn(value);
+ .thenReturn(value);
assertEquals(0, testSubject.getUsersList(modifierAttId, roles, rolesStr).size());
}
@@ -564,7 +564,7 @@
when(userAdminOperation.getUserData(modifierAttId, false)).thenReturn(value3);
Either<List<User>, ActionStatus> value = Either.left(new LinkedList<>());
when(userAdminOperation.getAllUsersWithRole(Mockito.nullable(String.class), anyString()))
- .thenReturn(value);
+ .thenReturn(value);
assertEquals(0, testSubject.getUsersList(modifierAttId, roles, rolesStr).size());
}
@@ -659,13 +659,13 @@
when(userAdminOperation.updateUserData(Mockito.any(User.class))).thenReturn(updatedUserCred);
assertEquals(updatedUserCred.getUserId(),
- testSubject.updateUserCredentials(updatedUserCred).left().value().getUserId());
+ testSubject.updateUserCredentials(updatedUserCred).left().value().getUserId());
}
@Test
public void getUsersPerRoleWhenListIsEmpty() {
when(userAdminOperation.getAllUsersWithRole(any(), any()))
- .thenReturn(Either.left(Lists.newArrayList()));
+ .thenReturn(Either.left(Lists.newArrayList()));
assertEquals(0, testSubject.getUsersPerRole("all", user, "").left().value().size());
}
@@ -675,7 +675,7 @@
when(user.getUserId()).thenReturn("123");
when(userNull.getUserId()).thenReturn(null);
when(userAdminOperation.getAllUsersWithRole(any(), any()))
- .thenReturn(Either.left(users));
+ .thenReturn(Either.left(users));
List<User> result = testSubject.getUsersPerRole("all", user, "").left().value();
assertEquals(1, result.size());
@@ -687,7 +687,7 @@
List<User> users = Lists.newArrayList(user, user);
when(user.getUserId()).thenReturn("123");
when(userAdminOperation.getAllUsersWithRole(any(), any()))
- .thenReturn(Either.left(users));
+ .thenReturn(Either.left(users));
List<User> result = testSubject.getUsersPerRole("all", user, "").left().value();
assertEquals(2, result.size());
@@ -699,7 +699,7 @@
List<User> users = Lists.newArrayList(userNull);
when(userNull.getUserId()).thenReturn(null);
when(userAdminOperation.getAllUsersWithRole(any(), any()))
- .thenReturn(Either.left(users));
+ .thenReturn(Either.left(users));
List<User> result = testSubject.getUsersPerRole("all", user, "").left().value();
assertEquals(0, result.size());
@@ -713,7 +713,7 @@
String userId = "mock";
Set<String> userRoles = new HashSet<>();
userRoles.add(Role.DESIGNER.name());
- UserContext userContext = new UserContext(userId, userRoles, "test" ,"User");
+ UserContext userContext = new UserContext(userId, userRoles, "test", "User");
ThreadLocalsHolder.setUserContext(userContext);
assertThat(testSubject.hasActiveUser(userId)).isTrue();
@@ -729,7 +729,7 @@
originalUserContext = ThreadLocalsHolder.getUserContext();
String userId = "mock";
Set<String> userRoles = new HashSet<>();
- UserContext userContext = new UserContext(userId, userRoles, "test" ,"User");
+ UserContext userContext = new UserContext(userId, userRoles, "test", "User");
ThreadLocalsHolder.setUserContext(userContext);
assertThat(testSubject.hasActiveUser(userId)).isFalse();
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java
index 84f83d9..dd44e17 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java
@@ -25,7 +25,6 @@
import org.junit.runner.RunWith;
import org.openecomp.sdc.be.components.BeConfDependentTest;
-// TODO - investigate NPE
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:cucumber/tenantIsolation.feature", glue = "org.openecomp.sdc.be.components.distribution.engine")
public class RunTenantIsolationTest extends BeConfDependentTest {
diff --git a/catalog-be/src/test/resources/application-context-test.xml b/catalog-be/src/test/resources/application-context-test.xml
index c45680c..10b12ff 100644
--- a/catalog-be/src/test/resources/application-context-test.xml
+++ b/catalog-be/src/test/resources/application-context-test.xml
@@ -29,4 +29,46 @@
<bean id="userAdmin" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.openecomp.sdc.be.user.UserBusinessLogic" />
</bean>
+ <bean id="componentInstanceBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic" />
+ </bean>
+ <bean id="servletUtils" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.impl.ServletUtils" />
+ </bean>
+ <bean id="resourceImportManager" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.ResourceImportManager" />
+ </bean>
+ <bean id="elementBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.ElementBusinessLogic" />
+ </bean>
+ <bean id="assetMetadataConverter" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter" />
+ </bean>
+ <bean id="lifecycleBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic" />
+ </bean>
+ <bean id="resourceBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.ResourceBusinessLogic" />
+ </bean>
+ <bean id="serviceBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.ServiceBusinessLogic" />
+ </bean>
+ <bean id="compositionBusinessLogic" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.openecomp.sdc.be.components.impl.CompositionBusinessLogic" />
+ </bean>
+
+ <bean class="org.openecomp.sdc.be.externalapi.servlet.CrudExternalServlet">
+ <constructor-arg ref="userAdmin" />
+ <constructor-arg ref="componentInstanceBusinessLogic" />
+ <constructor-arg ref="componentUtils"/>
+ <constructor-arg ref="servletUtils" />
+ <constructor-arg ref="resourceImportManager" />
+ <constructor-arg ref="elementBusinessLogic" />
+ <constructor-arg ref="assetMetadataConverter" />
+ <constructor-arg ref="lifecycleBusinessLogic" />
+ <constructor-arg ref="resourceBusinessLogic" />
+ <constructor-arg ref="serviceBusinessLogic" />
+ </bean>
+
+
</beans>