diff options
Diffstat (limited to 'vid-app-common')
36 files changed, 2027 insertions, 401 deletions
diff --git a/vid-app-common/jest.config.js b/vid-app-common/jest.config.js index e9ca59b11..3f72db3be 100644 --- a/vid-app-common/jest.config.js +++ b/vid-app-common/jest.config.js @@ -7,10 +7,10 @@ module.exports = { "<rootDir>/src/main/webapp/app/vid/external" ], setupFilesAfterEnv: ["<rootDir>/test-config.js"], - collectCoverage: true, + collectCoverage: false, collectCoverageFrom: [ "src/**/*.js", "!**/node_modules/**", "!**/vendor/**" ] -};
\ No newline at end of file +}; diff --git a/vid-app-common/pom.xml b/vid-app-common/pom.xml index 205d6422a..0cc2195e9 100755 --- a/vid-app-common/pom.xml +++ b/vid-app-common/pom.xml @@ -818,5 +818,10 @@ <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger2</artifactId> + <version>2.9.2</version> + </dependency> </dependencies> </project> diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java index a472268a3..8d5fbbdbb 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java @@ -30,10 +30,10 @@ import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.MsoProperties; -import org.onap.vid.mso.rest.MockedWorkflowsRestClient; import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.services.CloudOwnerService; import org.onap.vid.services.CloudOwnerServiceImpl; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.togglz.core.manager.FeatureManager; @@ -48,16 +48,12 @@ public class MsoConfig { } @Bean - public MsoRestClientNew msoClient(ObjectMapper unirestObjectMapper, HttpsAuthClient httpsAuthClient){ + public MsoRestClientNew msoClient(ObjectMapper unirestObjectMapper, HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemPropertiesWrapper){ // Satisfy both interfaces -- MsoInterface and RestMsoImplementation return new MsoRestClientNew(new SyncRestClient(unirestObjectMapper), SystemProperties.getProperty( - MsoProperties.MSO_SERVER_URL),httpsAuthClient); + MsoProperties.MSO_SERVER_URL),httpsAuthClient, systemPropertiesWrapper); } - @Bean - public MockedWorkflowsRestClient mockedWorkflowsClient(ObjectMapper unirestObjectMapper){ - return new MockedWorkflowsRestClient(new SyncRestClient(unirestObjectMapper), "http://vid-simulator:1080/"); - } @Bean public MsoBusinessLogic getMsoBusinessLogic(MsoInterface msoClient, FeatureManager featureManager){ diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java index 543aa9432..e00c2d7a5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java @@ -42,11 +42,18 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.togglz.core.manager.FeatureManager; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; +@EnableSwagger2 @Configuration public class WebConfig { @@ -193,4 +200,12 @@ public class WebConfig { } + @Bean + public Docket api(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("org.onap.vid.controller.open")) + .paths(PathSelectors.any()) + .build(); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/WorkflowsController.java b/vid-app-common/src/main/java/org/onap/vid/controller/WorkflowsController.java index a6ad92321..1d0ff95bc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/WorkflowsController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/WorkflowsController.java @@ -62,10 +62,6 @@ public class WorkflowsController extends VidRestrictedBaseController { return externalWorkflowsService.getWorkflows(vnfModelId); } - @RequestMapping(value = "remote-workflow-parameters/{id}", method = RequestMethod.GET) - SOWorkflowParameterDefinitions getParameters(@PathVariable Long id) { - return externalWorkflowsService.getWorkflowParameterDefinitions(id); - } @RequestMapping(value = "local-workflow-parameters/{name}", method = RequestMethod.GET) LocalWorkflowParameterDefinitions getParameters(@PathVariable String name) { diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controller/open/HealthCheckController.java index 04d5babcc..92e1a1802 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/open/HealthCheckController.java @@ -18,11 +18,12 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; import org.onap.portalsdk.core.controller.UnRestrictedBaseController; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.controller.HealthStatus; import org.onap.vid.dao.FnAppDoaImpl; import org.onap.vid.model.GitRepositoryState; import org.springframework.beans.factory.annotation.Autowired; diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java b/vid-app-common/src/main/java/org/onap/vid/controller/open/MaintenanceController.java index dfba4e31a..d1004401a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/open/MaintenanceController.java @@ -1,4 +1,4 @@ -package org.onap.vid.controller; +package org.onap.vid.controller.open; /*- * ============LICENSE_START======================================================= diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java b/vid-app-common/src/main/java/org/onap/vid/controller/open/RoleGeneratorController.java index 107142d7f..7b57df2c7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/open/RoleGeneratorController.java @@ -19,7 +19,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; import static org.springframework.http.HttpStatus.OK; diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java b/vid-app-common/src/main/java/org/onap/vid/controller/open/VersionController.java index aa15f0fa3..0a4d6f5ac 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/open/VersionController.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; import com.fasterxml.jackson.core.type.TypeReference; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/SOWorkflows.kt b/vid-app-common/src/main/java/org/onap/vid/model/SOWorkflows.kt index b88c3f6f6..00cc7b943 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/SOWorkflows.kt +++ b/vid-app-common/src/main/java/org/onap/vid/model/SOWorkflows.kt @@ -20,9 +20,18 @@ package org.onap.vid.model +import com.google.common.collect.Lists + +enum class WorkflowSource(val source: String) { + SDC("sdc"), NATIVE("native") +} + data class SOWorkflow constructor( - val id: Long, - val name: String) { + val id: String, + val name: String, + val source: WorkflowSource, + val workflowInputParameters: List<WorkflowInputParameter> +) { fun clone(): SOWorkflow { return copy() } @@ -79,3 +88,50 @@ data class LocalWorkflowParameterDefinitions constructor( } } + +data class ArtifactInfo constructor( + val artifactType: String, + val artifactUuid: String, + val artifactName: String, + val artifactVersion: String, + val artifactDescription: String? = null, + val workflowName: String, + val operationName: String? = null, + val workflowSource: String, + val workflowResourceTarget: String +) + +data class ActivitySequenceItem constructor( + val name: String, + val description: String +) + +data class WorkflowInputParameter constructor( + val label: String, + val inputType: String, + val required: Boolean, + val validation: List<InputParameterValidation>? = Lists.newArrayList(), + val soFieldName: String, + val soPayloadLocation: String?, + val description: String? + +) + +data class InputParameterValidation constructor( + val maxLength: String?, + val allowableChars: String? +) + +data class WorkflowSpecification constructor( + val artifactInfo: ArtifactInfo, + val activitySequence: List<ActivitySequenceItem>? = Lists.newArrayList(), + val workflowInputParameters: List<WorkflowInputParameter> +) + +data class WorkflowSpecificationWrapper constructor( + val workflowSpecification: WorkflowSpecification +) + +data class SOWorkflowList constructor( + val workflowSpecificationList: List<WorkflowSpecificationWrapper>? = Lists.newArrayList() +) diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java index 1ff30f03c..3b2cdb1bf 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright 2019 Nokia * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.vid.mso; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.controller.OperationalEnvironmentController; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.model.SoftDeleteRequest; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; @@ -138,4 +140,5 @@ public interface MsoBusinessLogic { MsoResponseWrapper2 activateFabricConfiguration(String serviceInstanceId, RequestDetails requestDetails); + SOWorkflowList getWorkflowListByModelId(String modelVersionId); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java index ad07eacae..64c405a39 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java @@ -8,9 +8,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. @@ -26,26 +26,44 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import io.joshworks.restclient.http.HttpResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.changeManagement.UIWorkflowsRequest; import org.onap.vid.changeManagement.WorkflowRequestDetail; -import org.onap.vid.controller.ControllersUtils; import org.onap.vid.controller.OperationalEnvironmentController; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.model.SoftDeleteRequest; -import org.onap.vid.mso.model.*; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; +import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; +import org.onap.vid.mso.model.RequestInfo; +import org.onap.vid.mso.model.RequestParameters; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; -import org.onap.vid.mso.rest.*; +import org.onap.vid.mso.rest.RelatedInstance; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestList; +import org.onap.vid.mso.rest.RequestWrapper; +import org.onap.vid.mso.rest.Task; +import org.onap.vid.mso.rest.TaskList; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.togglz.core.manager.FeatureManager; import javax.ws.rs.BadRequestException; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -54,8 +72,16 @@ import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.StringUtils.upperCase; import static org.onap.vid.changeManagement.ChangeManagementRequest.MsoChangeManagementRequest; -import static org.onap.vid.controller.MsoController.*; -import static org.onap.vid.mso.MsoProperties.*; +import static org.onap.vid.controller.MsoController.CONFIGURATION_ID; +import static org.onap.vid.controller.MsoController.REQUEST_TYPE; +import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.WORKFLOW_ID; +import static org.onap.vid.mso.MsoProperties.MSO_REST_API_CLOUD_RESOURCES_REQUEST_STATUS; +import static org.onap.vid.mso.MsoProperties.MSO_REST_API_OPERATIONAL_ENVIRONMENT_ACTIVATE; +import static org.onap.vid.mso.MsoProperties.MSO_REST_API_OPERATIONAL_ENVIRONMENT_CREATE; +import static org.onap.vid.mso.MsoProperties.MSO_REST_API_OPERATIONAL_ENVIRONMENT_DEACTIVATE; +import static org.onap.vid.mso.MsoProperties.MSO_REST_API_WORKFLOW_SPECIFICATIONS; import static org.onap.vid.properties.Features.FLAG_UNASSIGN_SERVICE; import static org.onap.vid.utils.Logging.debugRequestDetails; @@ -97,7 +123,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { this.featureManager = featureManager; } - public static String validateEndpointPath(String endpointEnvVariable) { + public static String validateEndpointPath(String endpointEnvVariable) { String endpoint = SystemProperties.getProperty(endpointEnvVariable); if (endpoint == null || endpoint.isEmpty()) { throw new GenericUncheckedException(endpointEnvVariable + " env variable is not defined"); @@ -404,7 +430,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } } - private List<Task> deserializeManualTasksJson(String manualTasksJson) { + private List<Task> deserializeManualTasksJson(String manualTasksJson) { logInvocationInDebug("deserializeManualTasksJson"); ObjectMapper mapper = new ObjectMapper(); @@ -558,6 +584,20 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return new MsoResponseWrapper2<>(msoClientInterface.post(path, new RequestDetailsWrapper<>(requestDetails), RequestReferencesContainer.class)); } + @Override + public SOWorkflowList getWorkflowListByModelId(String modelVersionId) { + logInvocationInDebug("getWorkflowListByModelId"); + String pathTemplate = validateEndpointPath(MSO_REST_API_WORKFLOW_SPECIFICATIONS); + String path = pathTemplate.replaceFirst("<model_version_id>", modelVersionId); + + HttpResponse<SOWorkflowList> workflowListByModelId = msoClientInterface.getWorkflowListByModelId(path); + if (!isSuccessful(workflowListByModelId)) { + logger.error(EELFLoggerDelegate.errorLogger, workflowListByModelId.getStatusText()); + throw new WorkflowListException(String.format("Get worklflow list for id: %s failed due to %s", modelVersionId, workflowListByModelId.getStatusText())); + } + return workflowListByModelId.getBody(); + } + @Override public MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { @@ -842,6 +882,18 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString()); } + private boolean isSuccessful(HttpResponse<SOWorkflowList> workflowListByModelId) { + int status = workflowListByModelId.getStatus(); + return HttpStatus.OK.value() == status || HttpStatus.ACCEPTED.value() == status; + } + + static class WorkflowListException extends RuntimeException{ + + WorkflowListException(String message) { + super(message); + } + } + enum RequestType { CREATE_INSTANCE("createInstance"), diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java index 904ba13e4..9befc0f90 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java @@ -22,6 +22,7 @@ package org.onap.vid.mso; import io.joshworks.restclient.http.HttpResponse; import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.mso.rest.RequestDetails; @@ -114,6 +115,8 @@ public interface MsoInterface { MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath); + HttpResponse<SOWorkflowList> getWorkflowListByModelId(String endpoint); + MsoResponseWrapper invokeWorkflow(WorkflowRequestDetail requestDetails,String invokeWorkflowsPath, Map<String, String> extraHeaders); <T> HttpResponse<T> get(String path, Class<T> responseClass); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java index 47cb95f2f..4e6258c16 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java @@ -125,4 +125,6 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_REST_API_SERVICE_INSTANCE_ASSIGN */ public static final String MSO_REST_API_SERVICE_INSTANCE_ASSIGN = "mso.restapi.serviceInstanceAssign"; + + public static final String MSO_REST_API_WORKFLOW_SPECIFICATIONS= "mso.restapi.changeManagement.workflowSpecifications"; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java index e14ac0e11..17af75200 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java @@ -26,7 +26,6 @@ import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpException; import org.eclipse.jetty.util.security.Password; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.util.HttpClientMode; import org.onap.vid.aai.util.HttpsAuthClient; @@ -34,6 +33,7 @@ import org.onap.vid.client.HttpBasicClient; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.rest.RestInterface; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; @@ -64,6 +64,7 @@ public class RestMsoImplementation implements RestInterface { protected HttpsAuthClient httpsAuthClient; + protected SystemPropertiesWrapper systemProperties; private static final String START_LOG = " start"; private static final String APPLICATION_JSON = "application/json"; @@ -80,8 +81,9 @@ public class RestMsoImplementation implements RestInterface { */ @Autowired - protected RestMsoImplementation(HttpsAuthClient httpsAuthClient){ + protected RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties){ this.httpsAuthClient=httpsAuthClient; + this.systemProperties = systemProperties; } @SuppressWarnings("Duplicates") @@ -89,9 +91,9 @@ public class RestMsoImplementation implements RestInterface { { final String methodname = "initRestClient()"; - final String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME); - final String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD); - final String mso_url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL); + final String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME); + final String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD); + final String mso_url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL); final String decrypted_password = Password.deobfuscate(password); String authString = username + ":" + decrypted_password; @@ -140,7 +142,7 @@ public class RestMsoImplementation implements RestInterface { try { restObject.set(t); - url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); @@ -179,7 +181,7 @@ public class RestMsoImplementation implements RestInterface { final String methodName = getMethodName(); logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz); - String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url); MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); @@ -216,7 +218,7 @@ public class RestMsoImplementation implements RestInterface { try { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url, r); cres = client.target(url) .request() @@ -281,7 +283,7 @@ public class RestMsoImplementation implements RestInterface { public Invocation.Builder prepareClient(String path, String methodName) { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url); // Change the content length return client.target(url) @@ -307,7 +309,7 @@ public class RestMsoImplementation implements RestInterface { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id))); - url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; Logging.logRequest(outgoingRequestsLogger, httpMethod, url, payload); // Change the content length final Invocation.Builder restBuilder = client.target(url) @@ -369,7 +371,7 @@ public class RestMsoImplementation implements RestInterface { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, r); // Change the content length final Response cres = client.target(url) diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MockedWorkflowsRestClient.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MockedWorkflowsRestClient.java deleted file mode 100644 index 54ee6464f..000000000 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MockedWorkflowsRestClient.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.mso.rest; - -import java.util.Collections; -import org.jetbrains.annotations.NotNull; -import org.onap.vid.client.SyncRestClient; -import org.onap.vid.model.SOWorkflowParameterDefinitions; -import org.onap.vid.model.SOWorkflows; -import org.onap.vid.mso.MsoResponseWrapper2; - -public class MockedWorkflowsRestClient { - - private SyncRestClient syncRestClient; - private String baseUrl; - - public MockedWorkflowsRestClient(SyncRestClient syncRestClient, String baseUrl) { - this.syncRestClient = syncRestClient; - this.baseUrl = baseUrl; - } - - public MsoResponseWrapper2<SOWorkflows> getWorkflows(String vnfName) { - // Temporary skip vnfName and call mocked service - return new MsoResponseWrapper2<>(syncRestClient - .get(getWorkflowsUrl(), - Collections.emptyMap(), - Collections.emptyMap(), - SOWorkflows.class)); - } - - public MsoResponseWrapper2<SOWorkflowParameterDefinitions> getWorkflowParameterDefinitions(Long workflowId) { - return new MsoResponseWrapper2<>(syncRestClient - .get((workflowId <= 3 && workflowId > 0) ? getParametersUrl(workflowId) : getParametersUrl(), - Collections.emptyMap(), - Collections.emptyMap(), - SOWorkflowParameterDefinitions.class)); - } - - @NotNull - private String getWorkflowsUrl() { - return baseUrl + "so/workflows"; - } - - - @NotNull - private String getParametersUrl() { - return baseUrl + "so/workflow-parameters"; - } - - @NotNull - private String getParametersUrl(Long workflowId) { - return baseUrl + "so/workflow-parameters/" + workflowId; - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java index ff7acffcf..6a498fc01 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java @@ -21,6 +21,7 @@ package org.onap.vid.mso.rest; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; import io.joshworks.restclient.http.HttpResponse; import io.joshworks.restclient.http.JsonNode; import java.text.DateFormat; @@ -40,6 +41,7 @@ import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; @@ -48,6 +50,7 @@ import org.onap.vid.mso.MsoUtil; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.SystemPropertiesWrapper; /** @@ -69,8 +72,8 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestClientNew.class); - public MsoRestClientNew(SyncRestClient client, String baseUrl, HttpsAuthClient authClient) { - super(authClient); + public MsoRestClientNew(SyncRestClient client, String baseUrl, HttpsAuthClient authClient, SystemPropertiesWrapper systemPropertiesWrapper) { + super(authClient,systemPropertiesWrapper); this.client = client; this.baseUrl = baseUrl; this.commonHeaders = initCommonHeaders(); @@ -473,6 +476,12 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } + public HttpResponse<SOWorkflowList> getWorkflowListByModelId(String endpoint){ + String path = baseUrl + endpoint; + + return client.get(path, commonHeaders, Maps.newHashMap(), SOWorkflowList.class); + } + private MsoResponseWrapper createInstance(Object request, String path) { String methodName = "createInstance"; logger.debug(methodName + START); @@ -517,8 +526,8 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } private Map<String, String> initCommonHeaders() { - String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME); - String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD); + String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME); + String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD); String decrypted_password = Password.deobfuscate(password); String authString = username + ":" + decrypted_password; @@ -530,7 +539,7 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf map.put(HttpHeaders.AUTHORIZATION, "Basic " + authStringEnc); map.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); map.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - map.put(X_FROM_APP_ID, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)); + map.put(X_FROM_APP_ID, systemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)); map.put(SystemProperties.ECOMP_REQUEST_ID, Logging.extractOrGenerateRequestId()); return ImmutableMap.copyOf(map); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsService.java b/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsService.java index 2eae52f4f..4620eed34 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * VID * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,8 @@ package org.onap.vid.services; import java.util.List; import org.onap.vid.model.SOWorkflow; -import org.onap.vid.model.SOWorkflowParameterDefinitions; + public interface ExternalWorkflowsService { List<SOWorkflow> getWorkflows(String vnfModelId); - - SOWorkflowParameterDefinitions getWorkflowParameterDefinitions(Long workflowId); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsServiceImpl.java index e03b5463a..0648b6ac9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ExternalWorkflowsServiceImpl.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * VID * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,60 +20,48 @@ package org.onap.vid.services; -import java.util.List; +import org.onap.vid.model.ArtifactInfo; import org.onap.vid.model.SOWorkflow; -import org.onap.vid.model.SOWorkflowParameterDefinitions; -import org.onap.vid.model.SOWorkflows; -import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.mso.rest.MockedWorkflowsRestClient; +import org.onap.vid.model.SOWorkflowList; +import org.onap.vid.model.WorkflowSource; +import org.onap.vid.model.WorkflowSpecification; +import org.onap.vid.mso.MsoBusinessLogic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + @Service public class ExternalWorkflowsServiceImpl implements ExternalWorkflowsService { - private MockedWorkflowsRestClient mockedWorkflowsRestClient; + private MsoBusinessLogic msoService; @Autowired - public ExternalWorkflowsServiceImpl(MockedWorkflowsRestClient mockedWorkflowsRestClient) { - this.mockedWorkflowsRestClient = mockedWorkflowsRestClient; + public ExternalWorkflowsServiceImpl(MsoBusinessLogic msoService) { + this.msoService = msoService; } @Override public List<SOWorkflow> getWorkflows(String vnfModelId) { - MsoResponseWrapper2<SOWorkflows> msoResponse = mockedWorkflowsRestClient.getWorkflows(vnfModelId); - validateSOResponse(msoResponse, SOWorkflows.class); - return convertMsoResponseToWorkflowList(msoResponse); - } + SOWorkflowList workflowListByModelId = msoService.getWorkflowListByModelId(vnfModelId); + List<SOWorkflow> soWorkflows = new ArrayList<>(); + Objects.requireNonNull(workflowListByModelId + .getWorkflowSpecificationList()) + .forEach( + workflow -> soWorkflows.add(convertWorkflow(workflow.getWorkflowSpecification())) + ); - @Override - public SOWorkflowParameterDefinitions getWorkflowParameterDefinitions(Long workflowId) { - MsoResponseWrapper2<SOWorkflowParameterDefinitions> msoResponse = mockedWorkflowsRestClient.getWorkflowParameterDefinitions(workflowId); - validateSOResponse(msoResponse, SOWorkflowParameterDefinitions.class); - return (SOWorkflowParameterDefinitions) msoResponse.getEntity(); + return soWorkflows; } - private List<SOWorkflow> convertMsoResponseToWorkflowList(MsoResponseWrapper2<SOWorkflows> msoResponse) { - SOWorkflows soWorkflows = (SOWorkflows) msoResponse.getEntity(); - return soWorkflows.getWorkflows(); - } + private SOWorkflow convertWorkflow(WorkflowSpecification workflow) { + ArtifactInfo artifactInfo = workflow.getArtifactInfo(); - private void validateSOResponse(MsoResponseWrapper2 response, Class<?> expectedResponseClass){ - if (response.getStatus() >= 400 || !expectedResponseClass.isInstance(response.getEntity())) { - throw new BadResponseFromMso(response); - } + return new SOWorkflow(artifactInfo.getArtifactUuid(), + artifactInfo.getWorkflowName(), + WorkflowSource.valueOf(artifactInfo.getWorkflowSource().toUpperCase()), + workflow.getWorkflowInputParameters()); } - - public static class BadResponseFromMso extends RuntimeException { - private final MsoResponseWrapper2<?> msoResponse; - - BadResponseFromMso(MsoResponseWrapper2<?> msoResponse) { - this.msoResponse = msoResponse; - } - - public MsoResponseWrapper2<?> getMsoResponse() { - return msoResponse; - } - } - } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js index 05a6cde31..16ec01dfd 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js @@ -55,13 +55,11 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", $scope.init();
$scope.fetchSubs(FIELD.PROMPT.FETCHING_SUBS);
$scope.fetchServices();
-
};
$scope.cancelCreateSI = function () {
window.location.href = COMPONENT.WELCOME_PATH;
-
};
$scope.getServiceTypes = function (globalCustomerId) {
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.test.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.test.js index 3e6bd2f3e..af3c2186a 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.test.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.test.js @@ -19,35 +19,1487 @@ */ require('./aaiSubscriberController'); +require('../services/dataService'); + const jestMock = require('jest-mock'); describe('TreeCtrl testing', () => { - let $scope; - beforeEach( - angular.mock.module('app') - ); - - beforeEach(inject(function (_$controller_) { - $scope = {}; - _$controller_('TreeCtrl', { - $scope: $scope - }); - })); - - test('Verify expandAll calls broadcast with expand-all parameter', () => { - // given - const broadcast = jestMock.fn(); - $scope.$broadcast = broadcast; - FIELD = { - ID: { - ANGULAR_UI_TREE_EXPANDALL: "angular-ui-tree:expand-all" - } - }; - // when - $scope.expandAll(); - // then - expect(broadcast).toHaveBeenCalledWith("angular-ui-tree:expand-all"); - }); + var window; + + let $scope; + beforeEach( + angular.mock.module('app') + ); + + beforeEach(inject(function (_$controller_) { + $scope = {}; + _$controller_('TreeCtrl', { + $scope: $scope + }); + })); + + test('Verify expandAll calls broadcast with expand-all parameter', () => { + // given + const broadcast = jestMock.fn(); + $scope.$broadcast = broadcast; + FIELD = { + ID: { + ANGULAR_UI_TREE_EXPANDALL: "angular-ui-tree:expand-all" + } + }; + // when + $scope.expandAll(); + // then + expect(broadcast).toHaveBeenCalledWith("angular-ui-tree:expand-all"); + }); + + test('Verify collapseAll calls broadcast with collapse-all parameter', () => { + // given + const broadcast = jestMock.fn(); + $scope.$broadcast = broadcast; + FIELD = { + ID: { + ANGULAR_UI_TREE_COLLAPSEALL: "angular-ui-tree:collapse-all" + } + }; + // when + $scope.collapseAll(); + // then + expect(broadcast).toHaveBeenCalledWith("angular-ui-tree:collapse-all"); + }); + test('Verify toggle calls toggle in given scope', () => { + // given + const testScope = {}; + testScope.toggle = jestMock.fn(); + // when + $scope.toggle(testScope); + // then + expect(testScope.toggle).toHaveBeenCalled(); + }); + + test('Verify remove calls remove in given scope', () => { + // given + const testScope = {}; + testScope.remove = jestMock.fn(); + // when + $scope.remove(testScope); + // then + expect(testScope.remove).toHaveBeenCalled(); + }); + + test('Verify moveLastToTheBeginning pops last element from data and puts it on the beginning', () => { + // given + $scope.data = [ 'a', 'b', 'c' ]; + const expectedResult = [ 'c', 'a', 'b' ]; + + // when + $scope.moveLastToTheBeginning(); + // then + expect($scope.data).toMatchObject(expectedResult); + }); + + test('Verify newSubItem pushes new item into given scope', () => { + // given + const testScope = {}; + const testModel = {}; + + testModel.id = 2; + testModel.nodes = []; + testModel.title = 'testObject'; + + const expectedResult = { + id: 20, + title: 'testObject.1', + nodes: [] + }; + + testScope.$modelValue = testModel; + + // when + $scope.newSubItem(testScope); + // then + expect(testModel.nodes.length).toBe(1); + expect(testModel.nodes[0]).toMatchObject(expectedResult); + }); }); +describe('aaiSubscriberController testing', () => { + + beforeEach( + angular.mock.module('app') + ); + + let $scope; + let $any; + + let mockFIELD = { + PROMPT: { + SELECT_SERVICE: 'testService' + }, + NAME: { + SERVICE_INSTANCE_ID: 'testID', + SERVICE_INSTANCE_NAME: 'testName' + }, + ID: { + INVENTORY_RESPONSE_ITEMS: 0, + INVENTORY_RESPONSE_ITEM: 0 + }, + STYLE: { + MSO_CTRL_BTN: 'testButtonStyle', + }, + STATUS: { + DONE: 'done', + }, + ERROR: { + AAI: 'testAAIError', + FETCHING_SERVICE_TYPES: 'testServiceType', + SELECT: 'testAlertError', + }, + + }; + + let mockCOMPONENT = { + SHOW_COMPONENT_DETAILS: 'testComponentDetails', + VNF: 'testComponentVNF', + WELCOME_PATH: 'http://test/welcome/', + CREATE_INSTANCE_PATH: 'testInstancePath', + FEATURE_FLAGS:{}, + }; + + let mockAaiService = { + getSubscriptionServiceTypeList(customerId,successFunction,failFunction){}, + getServiceModelsByServiceType(queryId,customerId,serviceType,successFunction,failFunction){}, + searchServiceInstances(query){}, + }; + + let mockAsdcService = { + isMacro(item){}, + shouldTakeTheAsyncInstantiationFlow(serviceModel){}, + }; + + let mockPropertyService = { + retrieveMsoMaxPollingIntervalMsec(){return 1000}, + setMsoMaxPollingIntervalMsec(msecs){}, + retrieveMsoMaxPolls(){return 1000}, + setMsoMaxPolls(polls){}, + }; + + let mockUtilityService = { + }; + + let mockVidService = { + setModel(model){}, + }; + + let dataService; + + let mockLocation = { + path(path){}, + }; + + let mockHttp = { + get(){}, + }; + + let mockOwningEntityService = { + getOwningEntityProperties(callBack){} + }; + + let mockQ = { + + }; + + $ = (selector) => {return mockSelector}; + let mockSelector = { + addClass(){return this}, + removeClass(){return this}, + attr(){}, + }; + + let mock_ = { + reduce(service,iterateeFunction,accumulatorFunction){}, + forEach(services,iteratedFunction){}, + includes(array, status){ + return array.includes(status); + }, + }; + + let mockedLog = {}; + + let mockFeatureFlags = {}; + + let mockVIDCONFIGURATION = {}; + + let mockRoute = {}; + + let mockUibModal = {}; + + let timeout; + + beforeEach(inject(function (_$controller_,DataService,$timeout) { + $scope = { + $on(request,toDoFunction){} + }; + $any = {}; + dataService = DataService; + timeout = $timeout; + _$controller_('aaiSubscriberController', { + $scope: $scope, + COMPONENT: mockCOMPONENT, + FIELD: mockFIELD, + PARAMETER: $any, + DataService: DataService, + PropertyService: mockPropertyService, + $http: mockHttp, + $timeout: timeout, + $location: mockLocation, + $log: mockedLog, + $route: mockRoute, + $uibModal: mockUibModal, + VIDCONFIGURATION: mockVIDCONFIGURATION, + UtilityService: mockUtilityService, + vidService: mockVidService, + AaiService: mockAaiService, + MsoService: $any, + OwningEntityService: mockOwningEntityService, + AsdcService: mockAsdcService, + featureFlags: mockFeatureFlags, + $q: mockQ, + _: mock_ + }); + })); + + test('Verify showVnfDetails calls proper broadcast methots with proper parameters', () => { + // given + const broadcast = jestMock.fn(); + $scope.$broadcast = broadcast; + + aaiResult = [[['test']]]; + + // when + $scope.showVnfDetails('testVNF'); + + // then + expect(broadcast).toHaveBeenCalledWith(mockCOMPONENT.SHOW_COMPONENT_DETAILS, { componentId: mockCOMPONENT.VNF,callbackFunction: expect.any(Function) } ); + }); + + test('Verify getSubs will call fetchSubs and fetchServices and gets gets customer list from AaiService on success', () => { + // given + mockAaiService.getSubList = (successFunction,failFunction) => { + successFunction(['testCustomer1', 'testCustomer2']); + }; + mockAaiService.getServices2 = (successFunction,failFunction) => { + successFunction('testListId'); + }; + + // when + $scope.getSubs(); + + // then + expect( $scope.customerList ).toContain('testCustomer1','testCustomer2'); + expect( dataService.getServiceIdList() ).toEqual('testListId'); + }); + + test('Verify getSubs will call fetchSubs and fetchServices and return error message from AaiService on fail', () => { + // given + mockAaiService.getSubList = (successFunction,failFunction) => { + failFunction({status: 404, data: 'getSubListTestErrorMessage'} ); + }; + mockAaiService.getServices2 = (successFunction,failFunction) => { + failFunction({status: 404, data: 'getServices02TestErrorMessage'} ); + }; + + // when + $scope.getSubs(); + + // then + expect( $scope.errorDetails ).toEqual('getServices02TestErrorMessage'); + }); + + test('Verify refreshServiceTypes will call getServiceTypesList and gets service type list from AaiService, with proper customerID ', () => { + // given + dataService.setGlobalCustomerId('testCustomerID'); + dataService.setServiceIdList(['testServiceId1','testServiceId2']); + + mockAaiService.getSubscriptionServiceTypeList = (customerId, successFunction,failFunction) => { + if (customerId === 'testCustomerID'){ + successFunction(['testServiceType1', 'testServiceType2']); + } + }; + + // when + $scope.refreshServiceTypes('testCustomerID'); + + // then + expect( $scope.serviceTypeList ).toContain('testServiceType1','testServiceType2'); + }); + + test('Verify refreshServiceTypes will call getServiceTypesList and return error message with wrong customerID ', () => { + // given + mockAaiService.getSubscriptionServiceTypeList = (customerId, successFunction,failFunction) => { + if (customerId === 'testWrongCustomerID'){ + failFunction( {status: 404, data: 'testErrorMessage'} ); + } + }; + + // when + $scope.refreshServiceTypes('testWrongCustomerID'); + + // then + expect( $scope.errorDetails ).toEqual('testErrorMessage'); + }); + + test('Verify refreshServiceTypes will call getServiceTypesList and calls alert with no customerID ', () => { + // given + alert = jestMock.fn(); + + // when + $scope.refreshServiceTypes(''); + + // then + expect( alert ).toHaveBeenCalledWith(mockFIELD.ERROR.SELECT); + }); + + test('Verify getAaiServiceModels will set correct location ', () => { + // given + mockLocation.path = jestMock.fn(); + + // when + $scope.getAaiServiceModels('testServiceType','testSubName'); + + // then + expect(mockLocation.path).toHaveBeenCalledWith(mockCOMPONENT.CREATE_INSTANCE_PATH); + }); + + test('Verify getAaiServiceModels wont set correct location if service type is empty', () => { + // given + mockLocation.path = jestMock.fn(); + + // when + $scope.getAaiServiceModels('','testSubName'); + + // then + expect(mockLocation.path).not.toHaveBeenCalled(); + }); + + test('Verify getAaiServiceModelsList will call AaiService getServiceModelsByServiceType and will set wholeData ', () => { + // given + + mockAaiService.getServiceModelsByServiceType = (queryId,customerId,serviceType,successFunction,failFunction) => { + let response = {}; + response.data = {}; + response.data['inventory-response-item'] = [[],[]]; + response.data['inventory-response-item'][0]['inventory-response-items'] = []; + response.data['inventory-response-item'][0]['service-subscription'] = []; + + let testItem = []; + testItem['extra-properties'] = []; + testItem['extra-properties']['extra-property'] = [[],[],[],[],[],[],[]]; + testItem['extra-properties']['extra-property'][6]["property-value"] = 1.546; + + testItem['extra-properties']['extra-property'][4]['property-value'] = 0; + + response.data['inventory-response-item'][0]['service-subscription']['service-type'] = 'testServiceType'; + response.data['inventory-response-item'][0]['inventory-response-items']['inventory-response-item'] = testItem; + + + successFunction(response); + }; + + mock_.reduce = (service,iterateeFunction,accumulatorFunction) => { + return iterateeFunction([],service); + }; + mock_.forEach = (service,iterateeFunction) => { + iterateeFunction(service); + }; + mock_.maxBy = (item,maxFunction) => { + return maxFunction( item[0][0] ) + }; + + dataService.setServiceIdList(['testService1','testService2','testService3','testService4']); + dataService.setSubscribers([{subscriberName:'testSubscriber1'},{subscriberName:'testSubscriber2'},{subscriberName:'testSubscriber3'},{subscriberName:'testSubscriber4'}]); + dataService.setGlobalCustomerId(2); + dataService.setSubscriberName('testSubscriber1'); + + // when + $scope.getAaiServiceModelsList(); + + // then + expect($scope.services[0]).toEqual(1.546); + expect($scope.serviceType).toEqual('testServiceType'); + }); + + test('Verify getAaiServiceModelsList will call AaiService getServiceModelsByServiceType and will return error data on fail ', () => { + // given + dataService.setServiceIdList([['testServiceId1','testServiceId2']]); + dataService.setSubscribers(['testSubscriber1,testSubscriber2']); + + mockAaiService.getServiceModelsByServiceType = (queryId,customerId,serviceType,successFunction,failFunction) => { + failFunction( {status: 404, data: 'testErrorMessage'}) + }; + + // when + $scope.getAaiServiceModelsList(); + + // then + expect($scope.errorDetails).toEqual('testErrorMessage'); + }); + + test('Verify getAaiServiceModelsList will call AaiService getServiceModelsByServiceType and will return error data if respose data is empty ', () => { + // given + dataService.setServiceIdList([['testServiceId1','testServiceId2']]); + dataService.setSubscribers(['testSubscriber1,testSubscriber2']); + + mockAaiService.getServiceModelsByServiceType = (queryId,customerId,serviceType,successFunction,failFunction) => { + let response = {}; + response.data = {}; + response.data['inventory-response-item'] = []; + successFunction(response); + }; + + // when + $scope.getAaiServiceModelsList(); + + // then + expect($scope.status).toEqual('Failed to get service models from SDC.'); + }); + + test('Verify deployService will call http get method to rest model service', () => { + // given + mockedLog.error = jestMock.fn(); + mockAsdcService.isMacro = (item) => { return true }; + mockAsdcService.shouldTakeTheAsyncInstantiationFlow = (serviceModel) => {return 'testModel'}; + mockUtilityService.convertModel = (serviceModel)=>{return serviceModel}; + $scope.$broadcast = (broadcastType, broadcastObject) => {broadcastObject.callbackFunction( + { + isSuccessful:true, + control: + [ + {id:"subscriberName",value:"testSubscriber"}, + {id:"serviceType",value:"testService"} + ], + instanceId:"testInstance" + })}; + + let service = { + "service-instance":{ + "model-version-id": 101 + } + }; + + $scope.refreshSubs = jestMock.fn(); + + let mockedGetPromise = Promise.resolve({data: {service: {name: 'testServiceName' }}}); + mockHttp.get = () => mockedGetPromise; + + // when + $scope.deployService(service,true); + }); + + test('Verify deployService will log error if get fails ', () => { + // given + + let mockedGetPromise = Promise.reject({code: 404}); + mockHttp.get = () => mockedGetPromise; + + let service = { + "service-instance":{ + "model-version-id": 101 + } + }; + + // when + $scope.deployService(service,false); + }); + + test('Verify refreshSubs fetches Subs and Services', () => { + // given + $scope.fetchSubs = jestMock.fn(); + $scope.fetchServices = jestMock.fn(); + $scope.init = jestMock.fn(); + + mockFIELD.PROMPT.REFRESH_SUB_LIST = 'testRefreshMock'; + + // when + $scope.refreshSubs(); + + // then + expect($scope.init).toHaveBeenCalled(); + expect($scope.fetchSubs).toHaveBeenCalledWith(mockFIELD.PROMPT.REFRESH_SUB_LIST); + expect($scope.fetchServices).toHaveBeenCalled(); + + }); + + test('Verify loadOwningEntity gets owning entity properties', () => { + // given + mockOwningEntityService.getOwningEntityProperties = (callBack) => { + callBack({owningEntity:'testOwner',project:'testProject'}); + }; + + // when + $scope.loadOwningEntity(); + + // then + expect($scope.owningEntities).toEqual('testOwner'); + expect($scope.projects).toEqual('testProject'); + }); + + test('Verify getPermitted returns items permission', () => { + // given + mockFIELD.ID.IS_PERMITTED = 'testPermission'; + + // when + expect( + $scope.getPermitted({}) + ).toEqual(undefined); + + expect( + $scope.getPermitted({isPermitted:true}) + ).toEqual(true); + + expect( + $scope.getPermitted({isPermitted:false}) + ).toEqual(undefined); + + expect( + $scope.getPermitted({isPermitted:false,testPermission:true}) + ).toEqual(true); + + expect( + $scope.getPermitted({testPermission:false,testPermission:false}) + ).toEqual(false); + + expect( + $scope.getPermitted({isPermitted:true,testPermission:false}) + ).toEqual(true); + }); + + test('Verify getSubDetails calls to aaiService for service instance', () => { + // given + let aaiPromise = Promise.resolve( + { + displayData:[ + {globalCustomerId:"testCustomerId01",subscriberName:"testCustomer1"}, + {globalCustomerId:"testCustomerId02",subscriberName:"testCustomer2"}, + ] + }); + + mockLocation.url = () => {return ""}; + + mockAaiService.searchServiceInstances = (query)=>aaiPromise; + + // when + $scope.getSubDetails(); + }); + + test('Verify getSubDetails catches bad response', () => { + // given + let aaiPromise = Promise.reject( + {data:'testError',status:404}); + + mockLocation.url = () => {return ""}; + + mockAaiService.searchServiceInstances = (query)=>aaiPromise; + + // when + $scope.getSubDetails(); + }); + + test('Verify getComponentList returns list of components if query is correct', () => { + // given + mockLocation.search = () => { + return { + subscriberId: 'testSubscriberID', + serviceType: 'testService', + serviceInstanceId: "testServiceInstanceID", + subscriberName: "testSubscriber", + aaiModelVersionId: "testModelVersion" + } + }; + + mockVidService.getModel = () => { + return { + service:{ + uuid: "testModelVersion", + }, + } + }; + + mockUtilityService.hasContents = (content) => { + if (content==="testModelVersion") { + return true; + } + return false; + }; + + mockQ.resolve = (item) => {return Promise.resolve("testModelVersion")}; + + $scope.prepareScopeWithModel = () => {return Promise.resolve()}; + + mockAaiService.getVlansByNetworksMapping = (globalCustomerId, serviceType, serviceInstanceId, modelServiceUuid) => { + return Promise.resolve({serviceNetworks:true}); + }; + + $scope.service ={ + model:{ + service:{ + uuid: 'testModelServiceUuid' + } + } + }; + + mockedLog.debug = () => {}; + mockUtilityService.isObjectEmpty = () => { + return false; + }; + + mockFIELD.ID.INVENTORY_RESPONSE_ITEM = "testResponseItems"; + mockFIELD.ID.SERVICE_SUBSCRIPTION = 0; + mockFIELD.ID.SERVICE_INSTANCES = 0; + mockFIELD.ID.SERVICE_INSTANCE = 0; + mockFIELD.ID.SERVICE_INSTANCE_ID = 'testServiceInstanceID'; + mockFIELD.STATUS.ASSIGNED = 'teststatus'; + + mockAaiService.runNamedQuery = (namedQueryId,globalCustomerId,serviceType,serviceInstanceId,successFunction,failureFunction) => { + successFunction({ + data:{ + testResponseItems:[ + "testItem1", + "testItem2", + "testItem3", + ] + }, + }); + return Promise.resolve("testComponentList"); + }; + + mockAaiService.getPortMirroringData = (portMirroringConfigurationIds) => { + return Promise.resolve({data:[8080,9090]}); + }; + + mockAaiService.getPortMirroringSourcePorts = (portMirroringConfigurationIds) => { + return Promise.resolve({data:[8888,9999]}) + }; + + mockAaiService.getSubscriberName = (customerId, successFunction) => { + successFunction({subscriberName:"testSubscriber1",serviceSubscriptions:[[ + [[[{'testServiceInstanceID':'testServiceInstanceID','orchestration-status':'testStatus'},{'testServiceInstanceID':'','orchestration-status':''}]]], + [[[{'testServiceInstanceID':'','orchestration-status':''}]]] + ]], + }); + }; + + mock_.map = (serviceNetworkVlans, networkId) => { + return ["aaiNetworkId1","aaiNetworkId2"]; + }; + + // when + return $scope.getComponentList('',''). + then(components =>{ + expect(components).toEqual("testComponentList") + }); + + }); + + test('Verify handleServerError sets proper $scope.error and $scope.status', () => { + // given + mockUtilityService.getHttpErrorMessage = (response) => {return response.statusText}; + mockFIELD.ERROR.SYSTEM_ERROR = "testSystemError"; + mockFIELD.STATUS.ERROR = "testStatusError"; + + // when + $scope.handleServerError({statusText:'testStatusError'},''); + + // then + expect($scope.error).toEqual("testSystemError (testStatusError)"); + expect($scope.status).toEqual("testStatusError"); + }); + + test('Verify showContentError sets proper $scope.error and $scope.status if UtilityService has that content', () => { + // given + mockFIELD.STATUS.ERROR = "testStatusError"; + + mockUtilityService.hasContents = (content) => { + return content === 'testContentError'; + + }; + + // when + $scope.showContentError('testContentError'); + + // then + expect($scope.error).toEqual("System failure (testContentError)"); + expect($scope.status).toEqual("testStatusError"); + }); + + test('Verify showContentError sets proper $scope.error and $scope.status if UtilityService has not that content', () => { + // given + mockFIELD.ERROR.SYSTEM_ERROR = "testSystemError"; + mockFIELD.STATUS.ERROR = "testStatusError"; + + mockUtilityService.hasContents = (content) => { + return false; + }; + + // when + $scope.showContentError('testContentError'); + + // then + expect($scope.error).toEqual("testSystemError"); + expect($scope.status).toEqual("testStatusError"); + }); + + test('Verify handleInitialResponse shows error for response codes other then 200,201,202', () => { + // given + let response = { + data:{ + status:404, + } + }; + + mockFIELD.ERROR.MSO = "testSystemError"; + mockFIELD.ERROR.AAI_FETCHING_CUST_DATA = "testStatusError:"; + + $scope.showError = jestMock.fn(); + + // when + $scope.handleInitialResponse(response); + + // then + expect($scope.showError).toHaveBeenCalledWith("testSystemError"); + expect($scope.status).toEqual("testStatusError:404"); + }); + + test('Verify handleInitialResponse updates customer list with response code 202', () => { + // given + let customer ={ + 'globalCustomerId':'testCustomerID', + "subscriberName":'testSubscriber', + "isPermitted":false + }; + let response = { + data:{ + status:202, + customer:[customer], + } + }; + + mockFIELD.ID.GLOBAL_CUSTOMER_ID = 'globalCustomerId'; + mockFIELD.ID.SUBNAME = 'subscriberName'; + mockFIELD.ID.IS_PERMITTED = 'isPermitted'; + + // when + $scope.handleInitialResponse(response); + + // then + expect($scope.customerList).toContainEqual(customer); + }); + + test('Verify handleInitialResponse calls showContentError with wrong response ', () => { + // given + $scope.showContentError = jestMock.fn(); + + // when + $scope.handleInitialResponse(null); + + // then + expect($scope.showContentError).toHaveBeenCalledWith(expect.objectContaining({message:"Cannot read property 'data' of null"})); + }); + + test('Verify isConfigurationDataAvailiable will return proper response', () => { + // given + mockedLog.debug = jestMock.fn(); + // when + expect( $scope.isConfigurationDataAvailiable({configData:{}}) ).toEqual(true); + expect( $scope.isConfigurationDataAvailiable({configData:{errorDescription:"testerror"}}) ).toEqual(false); + expect( $scope.isConfigurationDataAvailiable({}) ).toEqual(undefined); + + }); + + test('Verify isActivateDeactivateEnabled will return proper response', () => { + // given + mockedLog.debug = jestMock.fn(); + + $scope.serviceOrchestrationStatus = "active"; + mockCOMPONENT.ACTIVATE_SERVICE_STATUSES = ["active","up"]; + + // when + expect( $scope.isActivateDeactivateEnabled("deactivate")).toEqual(true); + expect( $scope.isActivateDeactivateEnabled("activate")).toEqual(true); + + $scope.serviceOrchestrationStatus = "down"; + mockCOMPONENT.ACTIVATE_SERVICE_STATUSES = ["active","up"]; + + expect( $scope.isActivateDeactivateEnabled("deactivate")).toEqual(false); + expect( $scope.isActivateDeactivateEnabled("activate")).toEqual(false); + + $scope.serviceOrchestrationStatus = null; + + expect( $scope.isActivateDeactivateEnabled(null)).toEqual(false); + + }); + + test('Verify isShowVerifyService will return proper response base on feature flag', () => { + // given + mockCOMPONENT.FEATURE_FLAGS.FLAG_SHOW_VERIFY_SERVICE = 'showVerifyService'; + mockFeatureFlags.isOn = (flag) => { + if (flag === 'showVerifyService'){return true}; + }; + + // when + expect( $scope.isShowVerifyService()).toEqual(true); + }); + + test('Verify isEnableVerifyService will return false if is not ALaCarte', () => { + // given + dataService.setALaCarte(false); + + // when + expect( $scope.isEnableVerifyService()).toEqual(false); + }); + + test('Verify isEnableVerifyService will return verifyButtonEnabled if is ALaCarte', () => { + // given + dataService.setALaCarte(true); + + // when + $scope.verifyButtonEnabled = true; + expect( $scope.isEnableVerifyService()).toEqual(true); + + $scope.verifyButtonEnabled = false; + expect( $scope.isEnableVerifyService()).toEqual(false); + }); + + test('Verify activateVerifyService will post POMBA verification', () => { + // given + mockCOMPONENT.VERIFY_SERVICE_URL = "/testURL"; + + mockAaiService.postPOMBAverificationRequest = jestMock.fn(); + + $scope.serviceInstanceId = "testInstanceID"; + $scope.service = {model:{service:{}},instance:{}}; + $scope.service.model.service.uuid = "testUuid"; + $scope.service.model.service.invariantUuid = "testInvariantUuid"; + $scope.globalCustomerId = "testCustomerId"; + $scope.service.instance.serviceType = "testServiceType"; + + // when + $scope.activateVerifyService(); + + // then + expect(mockAaiService.postPOMBAverificationRequest).toHaveBeenCalledWith( + "/testURL", + expect.objectContaining({'serviceInstanceList':[expect.any(Object)]}), + expect.objectContaining({'headers':expect.any(Object)})); + }); + + test('Verify isShowAssignmentsEnabled will return proper response determine by feature flag', () => { + // given + mockCOMPONENT.FEATURE_FLAGS.FLAG_SHOW_ASSIGNMENTS = "showAssignment"; + + mockFeatureFlags.isOn = (flag) => { + if (flag === 'showAssignment'){return true}; + }; + + // when + $scope.serviceOrchestrationStatus = "assigned"; + expect( $scope.isShowAssignmentsEnabled() ).toEqual(true); + + $scope.serviceOrchestrationStatus = "notAssigned"; + expect( $scope.isShowAssignmentsEnabled() ).toEqual(false); + + $scope.serviceOrchestrationStatus = null; + expect( $scope.isShowAssignmentsEnabled() ).toEqual(false); + }); + + test('Verify isActivateFabricConfiguration will return proper response determine by feature flag', () => { + // given + mockCOMPONENT.FEATURE_FLAGS.FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS = "fabricConfigurationAssignment"; + $scope.hasFabricConfigurations = true; + + mockFeatureFlags.isOn = (flag) => { + if (flag === 'fabricConfigurationAssignment'){return true}; + }; + + // when + $scope.serviceOrchestrationStatus = "assigned"; + expect( $scope.isActivateFabricConfiguration() ).toEqual(true); + + $scope.serviceOrchestrationStatus = "notAssigned"; + expect( $scope.isActivateFabricConfiguration() ).toEqual(false); + + $scope.serviceOrchestrationStatus = null; + expect( $scope.isActivateFabricConfiguration() ).toEqual(false); + }); + + test('Verify isResumeShown will return proper response determine by feature flag with disabled ActivateDeactivate', () => { + // given + $scope.serviceOrchestrationStatus = "assigned"; + $scope.isActivateDeactivateEnabled = () => {return false}; + + // when + expect( $scope.isResumeShown("assigned") ).toEqual(true); + expect( $scope.isResumeShown("unAssigned") ).toEqual(false); + + }); + + test('Verify isResumeShown will return proper response determine by feature flag with enable ActivateDeactivate', () => { + // given + $scope.serviceOrchestrationStatus = "assigned"; + $scope.isActivateDeactivateEnabled = () => {return true}; + + // when + expect( $scope.isResumeShown("assigned") ).toEqual(false); + expect( $scope.isResumeShown("unAssigned") ).toEqual(false); + + }); + + test('Verify close will call time out cancel and hides pop up window if timer is defined', () => { + // given + $scope.timer = 1000; + $scope.isPopupVisible = true; + + timeout.cancel = jestMock.fn(); + + // when + $scope.close(); + + // then + expect(timeout.cancel).toHaveBeenCalledWith(1000); + expect($scope.isPopupVisible).toEqual(false); + }); + + test('Verify close will hide pop up window if timer is undefined', () => { + // given + $scope.timer = undefined; + $scope.isPopupVisible = true; + + // when + $scope.close(); + + // then + expect($scope.isPopupVisible).toEqual(false); + }); + + test('Verify reloadRoute will call reload on rout', () => { + // given + mockRoute.reload = jestMock.fn(); + + // when + $scope.reloadRoute(); + + // then + expect(mockRoute.reload).toHaveBeenCalled(); + }); + + test('Verify prevPage will decrease currentPage', () => { + // given + $scope.currentPage = 5; + + // when + $scope.prevPage(); + + // then + expect($scope.currentPage).toEqual(4); + }); + + test('Verify showAssignmentsSDNC will return proper response base on VIDCONFIGURATION', () => { + // given + $scope.service = {}; + $scope.service.instance = {}; + $scope.service.instance.id = "testServiceInstanceId"; + + mockVIDCONFIGURATION.SDNC_SHOW_ASSIGNMENTS_URL = "test/ulr/to/<SERVICE_INSTANCE_ID>"; + + // when + expect( $scope.showAssignmentsSDNC() ).toEqual("test/ulr/to/testServiceInstanceId"); + }); + + test('Verify showAssignmentsSDNC will return null if service instance dos not exist or is null', () => { + // given + $scope.service = {}; + + // when + expect( $scope.showAssignmentsSDNC() ).toEqual(null); + + $scope.service.instance = null; + expect( $scope.showAssignmentsSDNC() ).toEqual(null); + }); + + test('Verify activateFabricConfigurationMSO with logged in user, will call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + mockCOMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ = "testMsoActivateType"; + + $scope.service = {}; + $scope.service.model = {}; + $scope.service = {}; + $scope.serviceInstanceId= "testServiceInstanceId"; + + dataService.setLoggedInUserId("testUserId"); + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.activateFabricConfigurationMSO(); + + // then + expect( resopnse.msoType() ).toEqual("testMsoActivateType"); + expect( resopnse.requestParams().serviceInstanceId ).toEqual("testServiceInstanceId"); + expect( resopnse.requestParams().userId ).toEqual("testUserId"); + expect( resopnse.configuration() ).toEqual(undefined); + }); + + test('Verify activateFabricConfigurationMSO without logged in user will first get user id from AaiService , will call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + mockCOMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ = "testMsoActivateType"; + + $scope.service = {}; + $scope.service.model = {}; + $scope.service = {}; + $scope.serviceInstanceId= "testServiceInstanceId"; + + + mockAaiService.getLoggedInUserID = (onSuccess) => { + onSuccess({data:"testAaiUserId"}); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.activateFabricConfigurationMSO(); + + // then + expect( resopnse.msoType() ).toEqual("testMsoActivateType"); + expect( resopnse.requestParams().serviceInstanceId ).toEqual("testServiceInstanceId"); + expect( resopnse.requestParams().userId ).toEqual("testAaiUserId"); + expect( resopnse.configuration() ).toEqual(undefined); + }); + + test('Verify activateMSOInstance with logged in user, will get aicZone from AaiService and call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + mockCOMPONENT.MSO_ACTIVATE_SERVICE_REQ = "testMsoActivateType"; + + $scope.service = {}; + $scope.service.model = {}; + $scope.service.instance = {}; + + dataService.setLoggedInUserId("testUserId"); + + mockAaiService.getAicZoneForPNF = (globalCustomerId,serviceType,serviceInstanceId,getZoneFunction) => { + getZoneFunction("testAicZone"); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.activateMSOInstance(); + + // then + expect( resopnse.msoType() ).toEqual("testMsoActivateType"); + expect( resopnse.requestParams().aicZone ).toEqual("testAicZone"); + expect( resopnse.requestParams().userId ).toEqual("testUserId"); + expect( resopnse.configuration() ).toEqual(undefined); + }); + + test('Verify activateMSOInstance without logged in user will first get user id from AaiService , will call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + mockCOMPONENT.MSO_ACTIVATE_SERVICE_REQ = "testMsoActivateType"; + + $scope.service = {}; + $scope.service.model = {}; + $scope.service.instance = {}; + + + mockAaiService.getAicZoneForPNF = (globalCustomerId,serviceType,serviceInstanceId,getZoneFunction) => { + getZoneFunction("testAicZone"); + }; + + mockAaiService.getLoggedInUserID = (onSuccess) => { + onSuccess({data:"testAaiUserId"}); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.activateMSOInstance(); + + // then + expect( resopnse.msoType() ).toEqual("testMsoActivateType"); + expect( resopnse.requestParams().aicZone ).toEqual("testAicZone"); + expect( resopnse.requestParams().userId ).toEqual("testAaiUserId"); + expect( resopnse.configuration() ).toEqual(undefined); + }); + + test('Verify deactivateMSOInstance will get call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + mockCOMPONENT.MSO_DEACTIVATE_SERVICE_REQ = "testMsoDeactivateType"; + + $scope.service = {}; + $scope.service.model = {}; + $scope.service.instance = {}; + + + mockAaiService.getAicZoneForPNF = (globalCustomerId,serviceType,serviceInstanceId,getZoneFunction) => { + getZoneFunction("testAicZone"); + }; + + mockAaiService.getLoggedInUserID = (onSuccess) => { + onSuccess({data:"testAaiUserId"}); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.deactivateMSOInstance(); + + // then + expect( resopnse.msoType() ).toEqual("testMsoDeactivateType"); + expect( resopnse.requestParams().aicZone ).toEqual("testAicZone"); + expect( resopnse.requestParams().userId ).toEqual("testAaiUserId"); + expect( resopnse.configuration() ).toEqual(undefined); + }); + + test('Verify deleteConfiguration will get call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + serviceObject = { + model:{ + service:{ + invariantUuid:"testInvariantUuid", + uuid:"testUuid", + name:"testService", + version:"testVersion", + }}, + instance:{ + serviceInstanceId:"testServiceInstanceId", + } + }; + + configuration = { + modelInvariantId:"testModelInvariantId", + modelVersionId:"testModelVersionId", + modelCustomizationId:"testModelCustomizationId", + nodeId:"testNodeId", + DELETE:"testDELETE", + }; + + mockCOMPONENT.MSO_DELETE_CONFIGURATION_REQ = "testMsoDeleteType"; + + mockAaiService.getLoggedInUserID = (successFunction) => { + successFunction( {data:"testLoggedInUserId"} ); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + // when + $scope.deleteConfiguration(serviceObject, configuration); + + // then + expect( resopnse.msoType() ).toEqual("testMsoDeleteType"); + expect( resopnse.requestParams().serviceModel.modelInvariantId ).toEqual("testInvariantUuid"); + expect( resopnse.requestParams().serviceModel.modelVersionId ).toEqual("testUuid"); + expect( resopnse.requestParams().serviceModel.modelName ).toEqual("testService"); + expect( resopnse.requestParams().serviceModel.modelVersion ).toEqual("testVersion"); + expect( resopnse.requestParams().serviceInstanceId ).toEqual("testServiceInstanceId"); + expect( resopnse.requestParams().configurationModel.modelInvariantId ).toEqual("testModelInvariantId"); + expect( resopnse.requestParams().configurationModel.modelVersionId ).toEqual("testModelVersionId"); + expect( resopnse.requestParams().configurationModel.modelCustomizationId ).toEqual("testModelCustomizationId"); + expect( resopnse.requestParams().configurationId ).toEqual("testNodeId"); + expect( resopnse.requestParams().configStatus ).toEqual("testDELETE"); + expect( resopnse.requestParams().userId ).toEqual("testLoggedInUserId"); + }); + + test('Verify toggleConfigurationStatus will get call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + serviceObject = { + model:{ + service:{ + invariantUuid:"testInvariantUuid", + uuid:"testUuid", + name:"testService", + version:"testVersion", + }}, + instance:{ + serviceInstanceId:"testServiceInstanceId", + } + }; + + configuration = { + modelInvariantId:"testModelInvariantId", + modelVersionId:"testModelVersionId", + modelCustomizationId:"testModelCustomizationId", + nodeId:"testNodeId", + nodeStatus:"testNodeStatus", + }; + + mockAaiService.getLoggedInUserID = (successFunction) => { + successFunction( {data:"testLoggedInUserId"} ); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + mockCOMPONENT.MSO_CHANGE_CONFIG_STATUS_REQ = "testMsoChangeConfig"; + + // when + $scope.toggleConfigurationStatus(serviceObject, configuration); + + // then + expect( resopnse.msoType() ).toEqual("testMsoChangeConfig"); + expect( resopnse.requestParams().serviceModel.modelInvariantId ).toEqual("testInvariantUuid"); + expect( resopnse.requestParams().serviceModel.modelVersionId ).toEqual("testUuid"); + expect( resopnse.requestParams().serviceModel.modelName ).toEqual("testService"); + expect( resopnse.requestParams().serviceModel.modelVersion ).toEqual("testVersion"); + expect( resopnse.requestParams().serviceInstanceId ).toEqual("testServiceInstanceId"); + expect( resopnse.requestParams().configurationModel.modelInvariantId ).toEqual("testModelInvariantId"); + expect( resopnse.requestParams().configurationModel.modelVersionId ).toEqual("testModelVersionId"); + expect( resopnse.requestParams().configurationModel.modelCustomizationId ).toEqual("testModelCustomizationId"); + expect( resopnse.requestParams().configurationId ).toEqual("testNodeId"); + expect( resopnse.requestParams().configStatus ).toEqual("testNodeStatus"); + expect( resopnse.requestParams().userId ).toEqual("testLoggedInUserId"); + }); + + test('Verify togglePortStatus will get call uibModal open that will return response ', () => { + // given + let resopnse = {}; + + let serviceObject = { + model:{ + service:{ + invariantUuid:"testInvariantUuid", + uuid:"testUuid", + name:"testService", + version:"testVersion", + }}, + instance:{ + serviceInstanceId:"testServiceInstanceId", + } + }; + + let configuration = { + modelInvariantId:"testModelInvariantId", + modelVersionId:"testModelVersionId", + modelCustomizationId:"testModelCustomizationId", + nodeId:"testNodeId", + }; + + let port = { + portId:"testPort", + portStatus:"open", + }; + + mockAaiService.getLoggedInUserID = (successFunction) => { + successFunction( {data:"testLoggedInUserId"} ); + }; + + mockUibModal.open = (testResponse) => { + resopnse = testResponse.resolve; + }; + + mockCOMPONENT.MSO_CHANGE_PORT_STATUS_REQ = "testMsoPortStatus"; + + // when + $scope.togglePortStatus(serviceObject, configuration,port); + + // then + expect( resopnse.msoType() ).toEqual("testMsoPortStatus"); + expect( resopnse.requestParams().serviceModel.modelInvariantId ).toEqual("testInvariantUuid"); + expect( resopnse.requestParams().serviceModel.modelVersionId ).toEqual("testUuid"); + expect( resopnse.requestParams().serviceModel.modelName ).toEqual("testService"); + expect( resopnse.requestParams().serviceModel.modelVersion ).toEqual("testVersion"); + expect( resopnse.requestParams().serviceInstanceId ).toEqual("testServiceInstanceId"); + expect( resopnse.requestParams().configurationModel.modelInvariantId ).toEqual("testModelInvariantId"); + expect( resopnse.requestParams().configurationModel.modelVersionId ).toEqual("testModelVersionId"); + expect( resopnse.requestParams().configurationModel.modelCustomizationId ).toEqual("testModelCustomizationId"); + expect( resopnse.requestParams().configurationId ).toEqual("testNodeId"); + expect( resopnse.requestParams().userId ).toEqual("testLoggedInUserId"); + expect( resopnse.requestParams().portId ).toEqual("testPort"); + expect( resopnse.requestParams().portStatus ).toEqual("open"); + }); + + + test('Verify getServiceInstancesSearchResults will get global customer Id from AaiService with proper service instance', () => { + // given + let selectedCustomer = 'testCustomer'; + let selectedInstanceIdentifierType = 'testInstanceIdentifierType'; + let selectedServiceInstance = 'testServiceInstance '; + let selectedProject = "testProject"; + let selectedOwningEntity = "testOwningEntity"; + + let globalCustomerId = 'testCustomerIdResponse'; + + mockAaiService.getGlobalCustomerIdByInstanceIdentifier = jestMock.fn((serviceInstance, instanceIdentifierType) => { + if(serviceInstance===selectedServiceInstance && instanceIdentifierType == selectedInstanceIdentifierType){ + return Promise.resolve(globalCustomerId); + } + return Promise.reject(); + }); + + mockAaiService.getMultipleValueParamQueryString = ( element, subPath) => { + return subPath + '/ ' + element; + }; + + mockAaiService.getJoinedQueryString = jestMock.fn(); + + mock_.map = (element,id) => { + return element; + }; + + mockCOMPONENT.PROJECT_SUB_PATH = "test/project/sub"; + mockCOMPONENT.OWNING_ENTITY_SUB_PATH = "test/entity/sub"; + mockCOMPONENT.SELECTED_SUBSCRIBER_SUB_PATH = "test/subscriber/sub"; + mockCOMPONENT.SELECTED_SERVICE_INSTANCE_SUB_PATH = "test/service/instance/sub"; + mockCOMPONENT.SELECTED_SERVICE_SUB_PATH = "text/service/sub"; + + mockUtilityService.hasContents = (element) => { + if ( element === selectedCustomer || + element === selectedServiceInstance || + element === globalCustomerId ) + return true; + }; + + window.location = {}; + + // when + $scope.getServiceInstancesSearchResults(selectedCustomer, selectedInstanceIdentifierType, selectedServiceInstance, selectedProject, selectedOwningEntity); + + // then + expect(mockAaiService.getGlobalCustomerIdByInstanceIdentifier).toHaveBeenCalledWith(selectedServiceInstance,selectedInstanceIdentifierType); + }); + + test('Verify getServiceInstancesSearchResults will alert error if non of parameters is located in UtilityService', () => { + // given + let selectedCustomer = 'testCustomer'; + let selectedInstanceIdentifierType = 'testInstanceIdentifierType'; + let selectedServiceInstance = 'testServiceInstance '; + let selectedProject = "testProject"; + let selectedOwningEntity = "testOwningEntity"; + + let globalCustomerId = 'testCustomerIdResponse'; + + mockAaiService.getGlobalCustomerIdByInstanceIdentifier = (serviceInstance, instanceIdentifierType) => { + if(serviceInstance===selectedServiceInstance && instanceIdentifierType == selectedInstanceIdentifierType){ + return Promise.resolve(globalCustomerId); + } + return Promise.reject(); + }; + + mockAaiService.getMultipleValueParamQueryString = ( element, subPath) => { + return subPath + '/ ' + element; + }; + + mockAaiService.getJoinedQueryString = (queryArray) => { + let joinedQuery = ""; + queryArray.forEach((element)=>{ + joinedQuery += element + "//" + }); + + return joinedQuery; + }; + + mock_.map = (element,id) => { + return element; + }; + + mockCOMPONENT.PROJECT_SUB_PATH = "test/project/sub"; + mockCOMPONENT.OWNING_ENTITY_SUB_PATH = "test/entity/sub"; + mockCOMPONENT.SELECTED_SUBSCRIBER_SUB_PATH = "test/subscriber/sub"; + mockCOMPONENT.SELECTED_SERVICE_INSTANCE_SUB_PATH = "test/service/instance/sub"; + mockCOMPONENT.SELECTED_SERVICE_SUB_PATH = "text/service/sub"; + + mockUtilityService.hasContents = (element) => { + return false; + }; + + alert = jestMock.fn(); + mockFIELD.ERROR.SELECT = "testError"; + + window.location = {}; + + // when + $scope.getServiceInstancesSearchResults(selectedCustomer, selectedInstanceIdentifierType, selectedServiceInstance, selectedProject, selectedOwningEntity); + + // then + expect(alert).toHaveBeenCalledWith("testError"); + }); + + test('Verify getServiceInstancesSearchResults will navigate to proper page if selected service instance is not present in UtilityService', () => { + // given + let selectedCustomer = 'testCustomer'; + let selectedInstanceIdentifierType = 'testInstanceIdentifierType'; + let selectedServiceInstance = 'testServiceInstance '; + let selectedProject = "testProject"; + let selectedOwningEntity = "testOwningEntity"; + + let globalCustomerId = 'testCustomerIdResponse'; + + mockAaiService.getGlobalCustomerIdByInstanceIdentifier = (serviceInstance, instanceIdentifierType) => { + if(serviceInstance===selectedServiceInstance && instanceIdentifierType == selectedInstanceIdentifierType){ + return Promise.resolve(globalCustomerId); + } + return Promise.reject(); + }; + + mockAaiService.getMultipleValueParamQueryString = ( element, subPath) => { + return subPath + element; + }; + + mockAaiService.getJoinedQueryString = jestMock.fn(); + + mock_.map = (element,id) => { + return element; + }; + + mockCOMPONENT.PROJECT_SUB_PATH = "test/project/sub/"; + mockCOMPONENT.OWNING_ENTITY_SUB_PATH = "test/entity/sub/"; + mockCOMPONENT.SELECTED_SUBSCRIBER_SUB_PATH = "test/subscriber/sub/"; + mockCOMPONENT.SELECTED_SERVICE_INSTANCE_SUB_PATH = "test/service/instance/sub/"; + mockCOMPONENT.SELECTED_SERVICE_SUB_PATH = "text/service/sub/"; + + + mockUtilityService.hasContents = (element) => { + return element === selectedCustomer; + }; + + window.location = {}; + + // when + $scope.getServiceInstancesSearchResults(selectedCustomer, selectedInstanceIdentifierType, selectedServiceInstance, selectedProject, selectedOwningEntity); + + // then + expect(mockAaiService.getJoinedQueryString).toHaveBeenCalledWith(expect.arrayContaining([ + mockCOMPONENT.PROJECT_SUB_PATH+selectedProject, + mockCOMPONENT.OWNING_ENTITY_SUB_PATH+selectedOwningEntity, + mockCOMPONENT.SELECTED_SUBSCRIBER_SUB_PATH+selectedCustomer + ])); + }); + + +});
\ No newline at end of file diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js index f8202fbf2..246834cdd 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js @@ -390,11 +390,9 @@ workflowParameters.requestDetails.cloudConfiguration = vm.changeManagement.vnfNames[0].cloudConfiguration; let parameters = vm.getRemoteWorkFlowParameters(vm.changeManagement.workflow); - let i = 1; parameters.forEach((parameter)=>{ - let inputField = document.getElementById('so-workflow-parameter-'+i); - i++; - workflowParameters.requestDetails.requestParameters.userParams[0][parameter.name]=inputField.value; + let inputField = document.getElementById('so-workflow-parameter-'+parameter.soFieldName); + workflowParameters.requestDetails.requestParameters.userParams[0][parameter.soFieldName]=inputField.value; }); return workflowParameters; @@ -402,40 +400,60 @@ vm.openModal = function () { if(vm.hasScheduler) { //scheduling supported - $scope.widgetParameter = ""; // needed by the scheduler? - - // properties needed by the scheduler so it knows whether to show - // policy or sniro related features on the scheduler UI or not. - vm.changeManagement.policyYN = "Y"; - vm.changeManagement.sniroYN = "Y"; - - if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_ADD_MSO_TESTAPI_FIELD)) { - vm.changeManagement.testApi = DataService.getMsoRequestParametersTestApi(); - } - var data = { - widgetName: 'Portal-Common-Scheduler', - widgetData: vm.changeManagement, - widgetParameter: $scope.widgetParameter - }; - - window.parent.postMessage(data, VIDCONFIGURATION.SCHEDULER_PORTAL_URL); + vm.scheduleWorkflow(); } else { - //no scheduling support - var dataToSo = extractChangeManagementCallbackDataStr(vm.changeManagement); - if(dataToSo) { - var vnfName = vm.changeManagement.vnfNames[0].name; - changeManagementService.postChangeManagementNow(dataToSo, vnfName); - } + //no scheduling support + vm.executeWorkflow(); + } + }; + + vm.scheduleWorkflow = function () { + $scope.widgetParameter = ""; // needed by the scheduler? + + // properties needed by the scheduler so it knows whether to show + // policy or sniro related features on the scheduler UI or not. + vm.changeManagement.policyYN = "Y"; + vm.changeManagement.sniroYN = "Y"; + + if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_ADD_MSO_TESTAPI_FIELD)) { + vm.changeManagement.testApi = DataService.getMsoRequestParametersTestApi(); + } + var data = { + widgetName: 'Portal-Common-Scheduler', + widgetData: vm.changeManagement, + widgetParameter: $scope.widgetParameter + }; + + window.parent.postMessage(data, VIDCONFIGURATION.SCHEDULER_PORTAL_URL); + }; + vm.executeWorkflow = function () { + if (vm.localWorkflows && vm.localWorkflows.length > 0) { + vm.triggerLocalWorkflow(); + } else { + vm.triggerRemoteWorkflow(); + } + }; + + vm.triggerLocalWorkflow = function () { + var dataToSo = extractChangeManagementCallbackDataStr(vm.changeManagement); + if (dataToSo) { + var vnfName = vm.changeManagement.vnfNames[0].name; + changeManagementService.postChangeManagementNow(dataToSo, vnfName); + } + }; + + vm.triggerRemoteWorkflow = function () { + let cachedWorkflowDetails = vm.getCachedWorkflowDetails(vm.changeManagement.workflow); + if (cachedWorkflowDetails.length > 0) { let workflowParameters = getWorkflowParametersFromForm(); - if(workflowParameters){ + if (workflowParameters) { let servieInstanceId = vm.changeManagement.vnfNames[0]['service-instance-node'][0].properties['service-instance-id']; let vnfInstanceId = vm.changeManagement.vnfNames[0].id; - let workflow_UUID = vm.changeManagement.fromVNFVersion; - - changeManagementService.postWorkflowsParametersNow(servieInstanceId,vnfInstanceId,workflow_UUID,workflowParameters); + let workflow_UUID = cachedWorkflowDetails[0].id; + changeManagementService.postWorkflowsParametersNow(servieInstanceId, vnfInstanceId, workflow_UUID, workflowParameters); } - } + } }; vm.loadSubscribers = function () { @@ -728,13 +746,37 @@ }; vm.loadRemoteWorkFlowParameters = function (workflow) { - changeManagementService.getSOWorkflowParameter(workflow.id) - .then(function (response) { - vm.remoteWorkflowsParameters.set(workflow.name, response.data.parameterDefinitions); - }) - .catch(function (error) { - $log.error(error); - }); + let parameters = []; + workflow.workflowInputParameters + .filter( function (param) { + return param.soPayloadLocation === "userParams" + }) + .forEach(function (param) { + let workflowParams = vm.repackAttributes(param); + if (param.validation.length > 0) { + let validation = param.validation[0]; + if ('maxLength' in validation) { + workflowParams.maxLength = validation.maxLength; + } + if ('allowableChars' in validation) { + workflowParams.pattern = validation.allowableChars; + } + } + parameters.push(workflowParams); + } + ); + vm.remoteWorkflowsParameters.set(workflow.name, parameters); + }; + + vm.repackAttributes = function (workflowParam){ + return { + name: workflowParam.label, + required: workflowParam.required, + id: workflowParam.soFieldName, + soFieldName: workflowParam.soFieldName, + maxLength: '500', + pattern: '.*' + } }; vm.getRemoteWorkFlowParameters = function (workflow) { @@ -757,6 +799,13 @@ } }; + vm.getCachedWorkflowDetails = function (workflow) { + return vm.remoteWorkflows.filter( function (remoteWorkflow) { + return remoteWorkflow.name === workflow; + }); + + }; + //Must be $scope because we bind to the onchange of the html (cannot attached to vm variable). $scope.selectFileForVNFName = function (fileInput) { if (fileInput && fileInput.id) { diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.test.js b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.test.js index 9810c0013..5989ffdd6 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.test.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.test.js @@ -100,32 +100,59 @@ describe('Testing workFlows from SO', () => { } ], }}); - let getSOWorkflowsPromiseStub = Promise.resolve({"data": [{"id": "1", "name": "workflow 1"}, {"id": "2", "name": "workflow 2"}]}); - let getSOWorkflowsParametersPromiseStub = Promise.resolve({"data":{"parameterDefinitions": []}}); + let getSOWorkflowsPromiseStub = Promise.resolve({"data":[{ - $controller.changeManagement.vnfNames = [{name: 'test1'}, {name: "test2"}]; + "id": "ab6478e4-ea33-3346-ac12-ab121484a333", + "workflowName": "inPlaceSoftwareUpdate", + "name": "inPlaceSoftwareUpdate", + "source": "sdc", + "workflowInputParameters": [ + { + "label": "New Software Version", + "inputType": "text", + "required": true, + "soFieldName": "new_software_version", + "soPayloadLocation": "userParams", + "validation":[] + } + ] + }] + }); + + $controller.changeManagement.vnfNames = [{modelVersionId: 'test1', name:'test'}]; $changeManagementService.getWorkflows = () => getWorkflowsStub; $changeManagementService.getLocalWorkflowParameter = () => getLocalWorkflowsParametersStub; $changeManagementService.getSOWorkflows = () => getSOWorkflowsPromiseStub; - $changeManagementService.getSOWorkflowParameter = () => getSOWorkflowsParametersPromiseStub; // when return $controller.loadWorkFlows().then(() => { - expect($controller.workflows).toContain('workflow 1'); - expect($controller.workflows).toContain('workflow 2'); + expect($controller.workflows).toContain('inPlaceSoftwareUpdate'); + expect($controller.localWorkflowsParameters).toBeUndefined(); }); }); - test('Verify load workflows will call load workflows parameters from SO', () => { + test('Verify load workflows will set workflows and parameters', () => { // given let getWorkflowsStub = Promise.resolve({"data": {"workflows": ["workflow 0"]}}); let getLocalWorkflowsParametersStub = Promise.resolve({"data": {}}); - let getSOWorkflowsPromiseStub = Promise.resolve({"data": [{"id": "1", "name": "workflow 0"}]}); - let getSOWorkflowsParametersPromiseStub = Promise.resolve({"data":{"parameterDefinitions": [ - {"id": 1, "name": "parameter 1", "required": true, "type": "STRING", "pattern": "[0-9]*"}, - {"id": 2, "name": "parameter 2", "required": true, "type": "STRING", "pattern": ".*"}, - {"id": 3, "name": "parameter 3", "required": false, "type": "STRING", "pattern": "[0-9]*"}]}}); + let getSOWorkflowsPromiseStub = Promise.resolve({"data":[{ - $controller.changeManagement.vnfNames = [{name: 'test1'}, {name: "test2"}]; + "id": "ab6478e4-ea33-3346-ac12-ab121484a333", + "workflowName": "inPlaceSoftwareUpdate", + "name": "inPlaceSoftwareUpdate", + "source": "sdc", + "workflowInputParameters": [ + { + "label": "New Software Version", + "inputType": "text", + "required": true, + "soFieldName": "new_software_version", + "soPayloadLocation": "userParams", + "validation":[] + } + ] + }] + }); + $controller.changeManagement.vnfNames = [{modelVersionId: 'test1', name:'test'}]; $changeManagementService.getWorkflows = () => getWorkflowsStub; $changeManagementService.getLocalWorkflowParameter = () => getLocalWorkflowsParametersStub; $changeManagementService.getSOWorkflows = () => getSOWorkflowsPromiseStub; @@ -133,10 +160,17 @@ describe('Testing workFlows from SO', () => { // when return $controller.loadWorkFlows() .then(() => { - expect($controller.remoteWorkflowsParameters).toEqual(new Map([["workflow 0", - [{"id": 1, "name": "parameter 1", "pattern": "[0-9]*", "required": true, "type": "STRING"}, - {"id": 2, "name": "parameter 2", "pattern": ".*", "required": true, "type": "STRING"}, - {"id": 3, "name": "parameter 3", "pattern": "[0-9]*", "required": false, "type": "STRING"}]]])); + expect($controller.workflows).toEqual(["inPlaceSoftwareUpdate"]); + expect($controller.remoteWorkflowsParameters).toEqual(new Map([["inPlaceSoftwareUpdate", + [{ + "name": "New Software Version", + "required": true, + "id": "new_software_version", + "soFieldName": "new_software_version", + "maxLength": '500', + "pattern": '.*' + }]] + ])); }); }); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.html b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.html index 9fb978c42..a5a6d1610 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.html +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.html @@ -97,7 +97,7 @@ <div class="form-group" ng-if="vm.changeManagement.workflow" ng-repeat="item in vm.getRemoteWorkFlowParameters(vm.changeManagement.workflow)"> <label for="so-workflow-parameter-{{item.id}}" class="control-label">{{item.name}}</label> - <input ng-model="item.value" type="text" id="so-workflow-parameter-{{item.id}}" pattern="{{item.pattern}}" ng-required="{{item.required}}"> + <input ng-model="item.value" type="text" id="so-workflow-parameter-{{item.id}}" pattern="{{item.pattern}}" maxlength="{{item.maxLength}}" ng-required="{{item.required}}" soFieldName="{{item.soFieldName}}"> </div> </div> diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java index 0abf6cd57..a7676d152 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -21,27 +21,41 @@ package org.onap.vid.controller; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.google.common.collect.ImmutableList; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.aai.AaiResponseTranslator; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; +import org.onap.vid.aai.model.PortDetailsTranslator.PortDetails; +import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsError; +import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsOk; import org.onap.vid.aai.util.AAIRestInterface; import org.onap.vid.roles.RoleProvider; import org.onap.vid.services.AaiService; import org.onap.vid.utils.SystemPropertiesWrapper; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(MockitoJUnitRunner.class) public class AaiControllerTest { + private static final String ID_1 = "id1"; + private static final String ID_2 = "id2"; @Mock private AaiService aaiService; @Mock @@ -51,32 +65,50 @@ public class AaiControllerTest { @Mock private SystemPropertiesWrapper systemPropertiesWrapper; + private MockMvc mockMvc; private AaiController aaiController; @Before - public void setUp(){ + public void setUp() { aaiController = new AaiController(aaiService, aaiRestInterface, roleProvider, systemPropertiesWrapper); + mockMvc = MockMvcBuilders.standaloneSetup(aaiController).build(); } @Test - public void getPortMirroringConfigData_givenThreeIds_ReturnsThreeResults() { + public void getPortMirroringConfigData_givenIds_shouldReturnConfigDataMappedById() throws Exception { + PortMirroringConfigDataOk okConfigData = new PortMirroringConfigDataOk("foo"); + PortMirroringConfigDataError errorConfigData = new PortMirroringConfigDataError("bar", "{ baz: qux }"); + Map<String, PortMirroringConfigData> expectedJson = ImmutableMap.of( + ID_1, okConfigData, + ID_2, errorConfigData); + given(aaiService.getPortMirroringConfigData(ID_1)).willReturn(okConfigData); + given(aaiService.getPortMirroringConfigData(ID_2)).willReturn(errorConfigData); - final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForA = new AaiResponseTranslator.PortMirroringConfigDataOk("foobar"); - final AaiResponseTranslator.PortMirroringConfigDataError toBeReturnedForB = new AaiResponseTranslator.PortMirroringConfigDataError("foo", "{ baz: qux }"); - final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForC = new AaiResponseTranslator.PortMirroringConfigDataOk("corge"); - - Mockito - .doReturn(toBeReturnedForA) - .doReturn(toBeReturnedForB) - .doReturn(toBeReturnedForC) - .when(aaiService).getPortMirroringConfigData(Mockito.anyString()); + mockMvc + .perform(get("/aai_getPortMirroringConfigsData") + .param("configurationIds", ID_1, ID_2) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(new ObjectMapper().writeValueAsString(expectedJson))); + } - final Map<String, AaiResponseTranslator.PortMirroringConfigData> result = aaiController.getPortMirroringConfigsData(ImmutableList.of("a", "b", "c")); + @Test + public void getPortMirroringSourcePorts_givenIds_shouldReturnPortDetailsMappedById() throws Exception { + PortDetailsOk portDetailsOk = new PortDetailsOk("foo", "testInterface", true); + PortDetailsError portDetailsError = new PortDetailsError("bar", "{ baz: qux }"); + Multimap<String, PortDetails> expectedJson = ImmutableMultimap.of( + ID_1, portDetailsOk, + ID_2, portDetailsError); + given(aaiService.getPortMirroringSourcePorts(ID_1)).willReturn(Lists.newArrayList(portDetailsOk)); + given(aaiService.getPortMirroringSourcePorts(ID_2)).willReturn(Lists.newArrayList(portDetailsError)); - assertThat(result, is(ImmutableMap.of( - "a", toBeReturnedForA, - "b", toBeReturnedForB, - "c", toBeReturnedForC - ))); + mockMvc + .perform(get("/aai_getPortMirroringSourcePorts") + .param("configurationIds", ID_1, ID_2) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(new ObjectMapper().writeValueAsString(expectedJson.asMap()))); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/open/HealthCheckControllerTest.java index 49e6645bc..76ee5617b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/open/HealthCheckControllerTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; import org.apache.log4j.BasicConfigurator; import org.junit.Before; @@ -26,6 +26,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.controller.open.HealthCheckController; import org.onap.vid.dao.FnAppDoaImpl; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/open/MaintenanceControllerTest.java index b9193810a..3e78828f0 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/open/MaintenanceControllerTest.java @@ -1,4 +1,4 @@ -package org.onap.vid.controller; +package org.onap.vid.controller.open; /*- * ============LICENSE_START======================================================= @@ -35,6 +35,7 @@ import org.onap.vid.category.AddCategoryOptionResponse; import org.onap.vid.category.AddCategoryOptionsRequest; import org.onap.vid.category.CategoryParameterOptionRep; import org.onap.vid.category.CategoryParametersResponse; +import org.onap.vid.controller.open.MaintenanceController; import org.onap.vid.model.CategoryParameter; import org.onap.vid.model.CategoryParameterOption; import org.onap.vid.services.CategoryParameterService; diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/open/RoleGeneratorControllerTest.java index c5b4a55dc..c1509d956 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/open/RoleGeneratorControllerTest.java @@ -19,7 +19,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -32,6 +32,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; +import org.onap.vid.controller.open.RoleGeneratorController; import org.onap.vid.services.RoleGeneratorService; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/open/VersionControllerTest.java index f92a26ea7..835ea4a66 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/open/VersionControllerTest.java @@ -18,8 +18,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.controller; +package org.onap.vid.controller.open; +import org.onap.vid.controller.open.VersionController; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 11bf364fb..4494f4872 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -28,7 +28,7 @@ import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.NotNull; import org.mockito.hamcrest.MockitoHamcrest; import org.onap.vid.changeManagement.WorkflowRequestDetail; -import org.onap.vid.controller.ControllersUtils; +import org.onap.vid.model.SOWorkflowList; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -78,6 +78,7 @@ import static org.hamcrest.Matchers.hasEntry; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -103,6 +104,12 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { private MsoInterface msoInterface; @Mock + private SOWorkflowList workflowList; + + @Mock + private HttpResponse<SOWorkflowList> workflowListResponse; + + @Mock private RequestDetails msoRequest; @@ -1357,6 +1364,26 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { assertThat(response).isEqualToComparingFieldByField(okResponse); } + + @Test + public void shouldReturnWorkflowListForGivenModelId() { + given(msoInterface.getWorkflowListByModelId(anyString())).willReturn(workflowListResponse); + given(workflowListResponse.getBody()).willReturn(workflowList); + given(workflowListResponse.getStatus()).willReturn(HttpStatus.ACCEPTED.value()); + + SOWorkflowList workflows = msoBusinessLogic.getWorkflowListByModelId("sampleModelId"); + + assertThat(workflows).isEqualTo(workflowList); + } + + @Test(expectedExceptions = {MsoBusinessLogicImpl.WorkflowListException.class}) + public void shouldRaiseExceptionWhenRetrievingWorkflowsFailed() { + given(msoInterface.getWorkflowListByModelId(anyString())).willReturn(workflowListResponse); + given(workflowListResponse.getStatus()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value()); + + msoBusinessLogic.getWorkflowListByModelId("sampleModelId"); + } + private WorkflowRequestDetail createWorkflowRequestDetail() { WorkflowRequestDetail workflowRequestDetail = new WorkflowRequestDetail(); org.onap.vid.changeManagement.RequestParameters requestParameters = new org.onap.vid.changeManagement.RequestParameters(); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java index 4cba53785..102c89ac1 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java @@ -24,11 +24,11 @@ import io.joshworks.restclient.request.HttpRequest; import org.glassfish.jersey.client.JerseyInvocation; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.testng.annotations.BeforeClass; @@ -72,15 +72,19 @@ public class RestMsoImplementationTest { @Mock private JerseyInvocation jerseyInvocation; + @Mock + private SystemPropertiesWrapper systemProperties; + @InjectMocks - private RestMsoImplementation restMsoImplementation = new RestMsoImplementation(mockHttpsAuthClient); + private RestMsoImplementation restMsoImplementation = new RestMsoImplementation(mockHttpsAuthClient, systemProperties); - String path = "/test_path/"; - String rawData = "test-row-data"; + private String path = "/test_path/"; + private String rawData = "test-row-data"; @BeforeClass public void setUp(){ initMocks(this); + when(systemProperties.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1ghz1kfx1j1w1m7w1i271e8q1eas1hzj1m4i1iyy1kch1gdz"); } @Test @@ -127,7 +131,8 @@ public class RestMsoImplementationTest { RestObject<HttpRequest> restObject = new RestObject<>(); prepareMocks("",HttpStatus.ACCEPTED.value(),""); - when(mockClient.target(SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL))).thenThrow(new MsoTestException("test-target-exception")); + when(systemProperties.getProperty(MsoProperties.MSO_SERVER_URL)).thenReturn("SAMPLE_URL"); + when(mockClient.target("SAMPLE_URL")).thenThrow(new MsoTestException("test-target-exception")); // when restMsoImplementation.Get(httpRequest, "", restObject,false); @@ -418,4 +423,4 @@ public class RestMsoImplementationTest { } } -}
\ No newline at end of file +} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index 12fd4a519..832aa098a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -45,6 +45,7 @@ import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.RestObject; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = {SystemProperties.class}) @@ -473,10 +474,10 @@ public class MsoRestClientNewTest { private MsoRestClientNew msoRestClient() { final WebConfig webConfig = new WebConfig(); - return new MsoRestClientNew(new SyncRestClient(webConfig.unirestFasterxmlObjectMapper(new ObjectMapper())), baseUrl(),null); + return new MsoRestClientNew(new SyncRestClient(webConfig.unirestFasterxmlObjectMapper(new ObjectMapper())), baseUrl(), null, new SystemPropertiesWrapper()); } private MsoRestClientNew createTestSubject() { - return new MsoRestClientNew(null, "",null); + return new MsoRestClientNew(null, "", null, new SystemPropertiesWrapper()); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java index 839e6e6c1..050fa0dce 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java @@ -44,12 +44,14 @@ import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.client.SyncRestClient; import org.onap.vid.controller.LocalWebConfig; import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.MsoUtil; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.CloudConfiguration; import org.onap.vid.mso.model.RequestReferences; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.annotations.BeforeClass; @@ -75,6 +77,8 @@ public class MsoRestClientTest { @Mock private SyncRestClient client; + @Mock + private SystemPropertiesWrapper systemProperties; private MsoRestClientNew restClient; @@ -82,8 +86,9 @@ public class MsoRestClientTest { @BeforeClass private void setUp(){ initMocks(this); - restClient = new MsoRestClientNew(client,baseUrl,null); - + when(systemProperties.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1ghz1kfx1j1w1m7w1i271e8q1eas1hzj1m4i1iyy1kch1gdz"); + when(systemProperties.getProperty("app_display_name")).thenReturn("vid"); + restClient = new MsoRestClientNew(client,baseUrl,null,systemProperties); } @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowServiceImplTest.java deleted file mode 100644 index 160ba97a5..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowServiceImplTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.services; - - - -import com.google.common.collect.Lists; -import io.joshworks.restclient.http.HttpResponse; -import java.util.Collections; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.onap.vid.model.SOWorkflow; -import org.onap.vid.model.SOWorkflowParameterDefinition; -import org.onap.vid.model.SOWorkflowParameterDefinitions; -import org.onap.vid.model.SOWorkflowType; -import org.onap.vid.model.SOWorkflows; -import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.mso.rest.MockedWorkflowsRestClient; -import org.onap.vid.services.ExternalWorkflowsServiceImpl.BadResponseFromMso; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class ExternalWorkflowServiceImplTest { - - @Mock - private MockedWorkflowsRestClient client; - @Mock - private HttpResponse<SOWorkflows> response; - - @Mock - private HttpResponse<SOWorkflowParameterDefinitions> parameterDefinitionsHttpResponse; - - - @BeforeMethod - public void init(){ - MockitoAnnotations.initMocks(this); - } - - @Test - public void shouldReturnWorkflowsOnValidResponse(){ - // given - ExternalWorkflowsService extWorkflowsService = new ExternalWorkflowsServiceImpl(client); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.getBody()).thenReturn(new SOWorkflows(Collections.singletonList(new SOWorkflow(1L, "xyz")))); - MsoResponseWrapper2<SOWorkflows> msoResponseStub = new MsoResponseWrapper2<>(response); - Mockito.when(client.getWorkflows("test")).thenReturn(msoResponseStub); - // when - List<SOWorkflow> workflows = extWorkflowsService.getWorkflows("test"); - // then - Mockito.verify(client).getWorkflows("test"); - Assertions.assertThat(workflows.get(0).getName()).isEqualTo("xyz"); - } - - @Test(expectedExceptions = BadResponseFromMso.class) - public void shouldThrowBadResponseOnInvalidResponse(){ - // given - ExternalWorkflowsService extWorkflowsService = new ExternalWorkflowsServiceImpl(client); - Mockito.when(response.getStatus()).thenReturn(500); - Mockito.when(response.getBody()).thenReturn(new SOWorkflows(Collections.singletonList(new SOWorkflow(1L, "xyz")))); - MsoResponseWrapper2<SOWorkflows> msoResponseStub = new MsoResponseWrapper2<>(response); - Mockito.when(client.getWorkflows("test")).thenReturn(msoResponseStub); - // when - extWorkflowsService.getWorkflows("test"); - // then throw exception - } - @Test - public void shouldReturnWorkflowParametersOnValidResponse() { - SOWorkflowParameterDefinitions parameters = new SOWorkflowParameterDefinitions(Collections.singletonList(new SOWorkflowParameterDefinition(1L, "sample", "[0-9]", SOWorkflowType.STRING, true))); - ExternalWorkflowsService extWorkflowsService = new ExternalWorkflowsServiceImpl(client); - Mockito.when(parameterDefinitionsHttpResponse.getStatus()).thenReturn(200); - Mockito.when(parameterDefinitionsHttpResponse.getBody()).thenReturn(parameters); - MsoResponseWrapper2<SOWorkflowParameterDefinitions> msoResponseWrapper = new MsoResponseWrapper2<>(parameterDefinitionsHttpResponse); - Mockito.when(client.getWorkflowParameterDefinitions(1L)).thenReturn(msoResponseWrapper); - - - SOWorkflowParameterDefinitions workflowParameterDefinitions = extWorkflowsService.getWorkflowParameterDefinitions(1L); - - Assertions.assertThat(workflowParameterDefinitions).isEqualTo(parameters); - } - - @Test - public void shouldProperlyHandleEmptyParametersList(){ - ExternalWorkflowsService extWorkflowsService = new ExternalWorkflowsServiceImpl(client); - Mockito.when(parameterDefinitionsHttpResponse.getStatus()).thenReturn(200); - Mockito.when(parameterDefinitionsHttpResponse.getBody()).thenReturn(new SOWorkflowParameterDefinitions(Lists.newArrayList())); - - MsoResponseWrapper2<SOWorkflowParameterDefinitions> msoResponseWrapper = new MsoResponseWrapper2<>(parameterDefinitionsHttpResponse); - Mockito.when(client.getWorkflowParameterDefinitions(1L)).thenReturn(msoResponseWrapper); - - - SOWorkflowParameterDefinitions workflowParameterDefinitions = extWorkflowsService.getWorkflowParameterDefinitions(1L); - Assertions.assertThat(workflowParameterDefinitions.getParameterDefinitions()).isEmpty(); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowsServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowsServiceImplTest.java new file mode 100644 index 000000000..94771b29e --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/ExternalWorkflowsServiceImplTest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.services; + + +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.model.ArtifactInfo; +import org.onap.vid.model.SOWorkflow; +import org.onap.vid.model.SOWorkflowList; +import org.onap.vid.model.WorkflowInputParameter; +import org.onap.vid.model.WorkflowSource; +import org.onap.vid.model.WorkflowSpecification; +import org.onap.vid.model.WorkflowSpecificationWrapper; +import org.onap.vid.mso.MsoBusinessLogic; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +public class ExternalWorkflowsServiceImplTest { + + @Mock + private MsoBusinessLogic msoBusinessLogic; + + + private static final UUID SAMPLE_UUID = UUID.randomUUID(); + + @BeforeMethod + public void init() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldReturnWorkflowsOnValidResponse() { + // given + ExternalWorkflowsService extWorkflowsService = new ExternalWorkflowsServiceImpl(msoBusinessLogic); + WorkflowInputParameter parameter = new WorkflowInputParameter("sampleLabel", "text", + true, Collections.EMPTY_LIST, "sampleName", "userParams", "description"); + SOWorkflowList workflowList = createWorkflowList(parameter); + SOWorkflow workflow = new SOWorkflow(SAMPLE_UUID.toString(), "sampleName", WorkflowSource.SDC, Collections.singletonList(parameter)); + when(msoBusinessLogic.getWorkflowListByModelId("test")).thenReturn(workflowList); + // when + List<SOWorkflow> workflows = extWorkflowsService.getWorkflows("test"); + // then + assertThat(workflows).hasSize(1).contains(workflow); + } + + private SOWorkflowList createWorkflowList(WorkflowInputParameter parameter) { + ArtifactInfo artifactInfo = new ArtifactInfo("workflow", SAMPLE_UUID.toString(), "sampleArtifactName", + "sampleVersion", "sampleDescription", "sampleName", "sampleOperation", "sdc", "vnf"); + WorkflowSpecification specification = new WorkflowSpecification(artifactInfo, Collections.EMPTY_LIST, Collections.singletonList(parameter)); + WorkflowSpecificationWrapper wrapper = new WorkflowSpecificationWrapper(specification); + return new SOWorkflowList(Collections.singletonList(wrapper)); + } + +} diff --git a/vid-app-common/src/test/resources/WEB-INF/conf/system.properties b/vid-app-common/src/test/resources/WEB-INF/conf/system.properties index 422514baa..a0f0dbe19 100644 --- a/vid-app-common/src/test/resources/WEB-INF/conf/system.properties +++ b/vid-app-common/src/test/resources/WEB-INF/conf/system.properties @@ -172,6 +172,7 @@ mso.restapi.operationalEnvironment.create=${mso.restapi.cloudResourcesApiRoot}/o mso.restapi.serviceInstantiationApiRoot=/serviceInstantiation/v7 mso.restapi.serviceInstanceCreate=${mso.restapi.serviceInstantiationApiRoot}/serviceInstances mso.restapi.serviceInstanceAssign=${mso.restapi.serviceInstantiationApiRoot}/serviceInstances/assign +mso.restapi.changeManagement.workflowSpecifications=/workflowSpecifications/v1/workflows?vnfModelVersionId=<model_version_id> vid.truststore.filename=/opt/app/vid/etc/vid_keystore.jks mso.dme2.client.timeout=30000 |