From c678c3a22f7761928f4be8e4f82f2f3c7ea417db Mon Sep 17 00:00:00 2001 From: "ning.xi" Date: Tue, 13 Aug 2019 05:20:20 +0000 Subject: add JUnit test in client deployment and client full Issue-ID: POLICY-1962 Change-Id: Ic10b0edc9364624161f71935f51f4411fe67c882 Signed-off-by: ning.xi --- client/client-deployment/pom.xml | 11 + .../rest/ApexDeploymentRestResource.java | 26 +- .../client/deployment/rest/ParameterCheck.java | 39 +- .../webapp/resources/models/SmallModel.json | 416 +++++++++++++++++++++ .../deployment/rest/DeploymentExceptionTest.java | 37 ++ .../deployment/rest/DeploymentRestMainTest.java | 226 +++++++++++ .../rest/DeploymentRestParameterTest.java | 38 ++ .../client/deployment/rest/ParameterCheckTest.java | 188 ++++++++++ .../client/deployment/rest/RestResourceTest.java | 175 +++++++++ client/client-full/pom.xml | 7 +- .../apex/client/full/rest/ParameterCheck.java | 41 +- .../apex/client/full/rest/ParameterCheckTest.java | 188 ++++++++++ .../client/full/rest/ServicesExceptionTest.java | 37 ++ .../client/full/rest/ServicesRestMainTest.java | 221 +++++++++++ .../full/rest/ServicesRestParameterTest.java | 47 +++ 15 files changed, 1682 insertions(+), 15 deletions(-) create mode 100644 client/client-deployment/src/main/resources/webapp/resources/models/SmallModel.json create mode 100644 client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentExceptionTest.java create mode 100644 client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestMainTest.java create mode 100644 client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestParameterTest.java create mode 100644 client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/ParameterCheckTest.java create mode 100644 client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/RestResourceTest.java create mode 100644 client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ParameterCheckTest.java create mode 100644 client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesExceptionTest.java create mode 100644 client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestMainTest.java create mode 100644 client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestParameterTest.java (limited to 'client') diff --git a/client/client-deployment/pom.xml b/client/client-deployment/pom.xml index 12c2a1394..aef5450ed 100644 --- a/client/client-deployment/pom.xml +++ b/client/client-deployment/pom.xml @@ -60,6 +60,17 @@ commons-cli commons-cli + + org.mockito + mockito-all + test + + + org.assertj + assertj-core + 3.13.2 + test + org.onap.policy.apex-pdp.client diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java index d3a7d654a..55cabe900 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java @@ -21,9 +21,7 @@ package org.onap.policy.apex.client.deployment.rest; import com.google.gson.JsonObject; - import java.io.InputStream; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -32,8 +30,6 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.onap.policy.apex.core.deployment.ApexDeploymentException; import org.onap.policy.apex.core.deployment.EngineServiceFacade; @@ -69,7 +65,7 @@ public class ApexDeploymentRestResource { @GET public Response createSession(@QueryParam("hostName") final String hostName, @QueryParam("port") final int port) { final String host = hostName + ":" + port; - final EngineServiceFacade engineServiceFacade = new EngineServiceFacade(hostName, port); + final EngineServiceFacade engineServiceFacade = getEngineServiceFacade(hostName, port); try { engineServiceFacade.init(); @@ -109,10 +105,10 @@ public class ApexDeploymentRestResource { @Consumes(MediaType.MULTIPART_FORM_DATA) public Response modelUpload(@FormDataParam("hostName") final String hostName, @FormDataParam("port") final int port, @FormDataParam("file") final InputStream uploadedInputStream, - @FormDataParam("file") final FormDataContentDisposition fileDetail, + @FormDataParam("fileName") final String fileName, @FormDataParam("ignoreConflicts") final boolean ignoreConflicts, @FormDataParam("forceUpdate") final boolean forceUpdate) { - final EngineServiceFacade engineServiceFacade = new EngineServiceFacade(hostName, port); + final EngineServiceFacade engineServiceFacade = getEngineServiceFacade(hostName, port); try { engineServiceFacade.init(); @@ -124,8 +120,7 @@ public class ApexDeploymentRestResource { } try { - engineServiceFacade.deployModel(fileDetail.getFileName(), uploadedInputStream, ignoreConflicts, - forceUpdate); + engineServiceFacade.deployModel(fileName, uploadedInputStream, ignoreConflicts, forceUpdate); } catch (final Exception e) { LOGGER.warn("Error updating model on engine service " + engineServiceFacade.getKey().getId(), e); final String errorMessage = @@ -135,8 +130,19 @@ public class ApexDeploymentRestResource { .build(); } - return Response.ok("Model " + fileDetail.getFileName() + " deployed on engine service " + return Response.ok("Model " + fileName + " deployed on engine service " + engineServiceFacade.getKey().getId()).build(); } + /** + * Get an engine service facade for sending REST requests. This method is package because it is used by unit test. + * + * @param hostName the host name of the Apex engine + * @param port the port of the Apex engine + * @return the engine service facade + */ + protected EngineServiceFacade getEngineServiceFacade(final String hostName, final int port) { + return new EngineServiceFacade(hostName, port); + } + } diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java index 4e75763db..cad0911f1 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +22,6 @@ package org.onap.policy.apex.client.deployment.rest; import java.util.Map; - import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -71,12 +71,19 @@ public final class ParameterCheck { * @return the host name */ public static String getHostName(final Map parameterMap) { + if (parameterMap == null) { + return null; + } + if (!parameterMap.containsKey(HOSTNAME_PAR)) { LOGGER.warn(PARAMETER + HOSTNAME_PAR + NOT_FOUND); return null; } final String[] hostNameValue = parameterMap.get(HOSTNAME_PAR); + if (hostNameValue == null) { + return null; + } if (hostNameValue.length == 0 || hostNameValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"" + HOSTNAME_PAR + NOT_FOUND); @@ -93,6 +100,10 @@ public final class ParameterCheck { * @return the port */ public static int getPort(final Map parameterMap) { + if (parameterMap == null) { + return -1; + } + if (!parameterMap.containsKey(PORT_PAR)) { LOGGER.warn(PARAMETER + PORT_PAR + NOT_FOUND); return -1; @@ -130,6 +141,10 @@ public final class ParameterCheck { * @return the engine key */ public static AxArtifactKey getEngineKey(final Map parameterMap) { + if (parameterMap == null) { + return null; + } + String artifactKeyParameter = null; for (final String parameter : parameterMap.keySet()) { // Check for an AxArtifactKey parameter @@ -152,7 +167,12 @@ public final class ParameterCheck { return null; } - return new AxArtifactKey(axArtifactKeyArray[1]); + try { + return new AxArtifactKey(axArtifactKeyArray[1]); + } catch (Exception apEx) { + LOGGER.trace("invalid artifact key ID {}", axArtifactKeyArray[1], apEx); + return null; + } } /** @@ -164,6 +184,10 @@ public final class ParameterCheck { */ public static ParameterCheck.StartStop getStartStop(final Map parameterMap, final AxArtifactKey engineKey) { + if (parameterMap == null || engineKey == null) { + return null; + } + final String startStopPar = AXARTIFACTKEY_PAR + '#' + engineKey.getId(); if (!parameterMap.containsKey(startStopPar)) { LOGGER.warn("parameter \"{}\" not found", startStopPar); @@ -171,6 +195,9 @@ public final class ParameterCheck { } final String[] startStopValue = parameterMap.get(startStopPar); + if (startStopValue == null) { + return null; + } if (startStopValue.length == 0 || startStopValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"{}\" not found", startStopPar); @@ -198,6 +225,10 @@ public final class ParameterCheck { * @return The long value */ public static long getLong(final Map parameterMap, final String longName) { + if (parameterMap == null || longName == null) { + return -1; + } + if (!parameterMap.containsKey(longName)) { LOGGER.warn("parameter \"{}\" not found", longName); return -1; @@ -205,6 +236,10 @@ public final class ParameterCheck { final String[] longValue = parameterMap.get(longName); + if (longValue == null) { + return -1; + } + if (longValue.length == 0 || longValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"{}\" not found", longName); return -1; diff --git a/client/client-deployment/src/main/resources/webapp/resources/models/SmallModel.json b/client/client-deployment/src/main/resources/webapp/resources/models/SmallModel.json new file mode 100644 index 000000000..5c0628809 --- /dev/null +++ b/client/client-deployment/src/main/resources/webapp/resources/models/SmallModel.json @@ -0,0 +1,416 @@ +{ + "apexPolicyModel" : { + "key" : { + "name" : "SmallModel", + "version" : "0.0.1" + }, + "keyInformation" : { + "key" : { + "name" : "SmallModel_KeyInfo", + "version" : "0.0.1" + }, + "keyInfoMap" : { + "entry" : [ { + "key" : { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + }, + "UUID" : "fec1b353-b35f-4384-b7d9-69622059c248", + "description" : "Generated description for a concept called \"BasicContextAlbum\" with version \"0.0.1\" and UUID \"fec1b353-b35f-4384-b7d9-69622059c248\"" + } + }, { + "key" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "UUID" : "cc8d3c1a-e975-459a-bcd2-69f423eaa1f3", + "description" : "Generated description for a concept called \"BasicEvent\" with version \"0.0.1\" and UUID \"cc8d3c1a-e975-459a-bcd2-69f423eaa1f3\"" + } + }, { + "key" : { + "name" : "BasicPolicy", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicPolicy", + "version" : "0.0.1" + }, + "UUID" : "d0c5d8ee-5fe7-4978-89ce-4a3e69cad043", + "description" : "Generated description for a concept called \"BasicPolicy\" with version \"0.0.1\" and UUID \"d0c5d8ee-5fe7-4978-89ce-4a3e69cad043\"" + } + }, { + "key" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "UUID" : "c5651414-fc1c-493b-878d-75f0ce685c36", + "description" : "Generated description for a concept called \"BasicTask\" with version \"0.0.1\" and UUID \"c5651414-fc1c-493b-878d-75f0ce685c36\"" + } + }, { + "key" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "UUID" : "790ff718-8dc0-44e0-89d8-1b3bbe238310", + "description" : "Generated description for a concept called \"IntType\" with version \"0.0.1\" and UUID \"790ff718-8dc0-44e0-89d8-1b3bbe238310\"" + } + }, { + "key" : { + "name" : "SmallModel", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel", + "version" : "0.0.1" + }, + "UUID" : "a1bd1f4e-713b-456b-b1a8-bb48beee28e8", + "description" : "Generated description for a concept called \"SmallModel\" with version \"0.0.1\" and UUID \"a1bd1f4e-713b-456b-b1a8-bb48beee28e8\"" + } + }, { + "key" : { + "name" : "SmallModel_Albums", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_Albums", + "version" : "0.0.1" + }, + "UUID" : "72bed9af-ab7d-3379-b9f7-b5eca5c9ef22", + "description" : "Generated description for concept referred to by key \"SmallModel_Albums:0.0.1\"" + } + }, { + "key" : { + "name" : "SmallModel_Events", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_Events", + "version" : "0.0.1" + }, + "UUID" : "796dc6b0-627d-34ae-a5e2-1bc4b4b486b8", + "description" : "Generated description for concept referred to by key \"SmallModel_Events:0.0.1\"" + } + }, { + "key" : { + "name" : "SmallModel_KeyInfo", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_KeyInfo", + "version" : "0.0.1" + }, + "UUID" : "b4876774-6907-3d27-a2b8-f05737c5ee4a", + "description" : "Generated description for concept referred to by key \"SmallModel_KeyInfo:0.0.1\"" + } + }, { + "key" : { + "name" : "SmallModel_Policies", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_Policies", + "version" : "0.0.1" + }, + "UUID" : "5bcf946b-67be-3190-a906-f954896f999f", + "description" : "Generated description for concept referred to by key \"SmallModel_Policies:0.0.1\"" + } + }, { + "key" : { + "name" : "SmallModel_Schemas", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_Schemas", + "version" : "0.0.1" + }, + "UUID" : "c25bf5c3-7f1e-3667-b8a9-971ba21517bc", + "description" : "Generated description for concept referred to by key \"SmallModel_Schemas:0.0.1\"" + } + }, { + "key" : { + "name" : "SmallModel_Tasks", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "SmallModel_Tasks", + "version" : "0.0.1" + }, + "UUID" : "43b015ca-2ed1-3a35-b103-e8a5aa68f1ef", + "description" : "Generated description for concept referred to by key \"SmallModel_Tasks:0.0.1\"" + } + } ] + } + }, + "policies" : { + "key" : { + "name" : "SmallModel_Policies", + "version" : "0.0.1" + }, + "policyMap" : { + "entry" : [ { + "key" : { + "name" : "BasicPolicy", + "version" : "0.0.1" + }, + "value" : { + "policyKey" : { + "name" : "BasicPolicy", + "version" : "0.0.1" + }, + "template" : "FREEFORM", + "state" : { + "entry" : [ { + "key" : "OnlyState", + "value" : { + "stateKey" : { + "parentKeyName" : "BasicPolicy", + "parentKeyVersion" : "0.0.1", + "parentLocalName" : "NULL", + "localName" : "OnlyState" + }, + "trigger" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "stateOutputs" : { + "entry" : [ { + "key" : "OnlyOutput", + "value" : { + "key" : { + "parentKeyName" : "BasicPolicy", + "parentKeyVersion" : "0.0.1", + "parentLocalName" : "OnlyState", + "localName" : "OnlyOutput" + }, + "outgoingEvent" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "nextState" : { + "parentKeyName" : "NULL", + "parentKeyVersion" : "0.0.0", + "parentLocalName" : "NULL", + "localName" : "NULL" + } + } + } ] + }, + "contextAlbumReference" : [ { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + } ], + "taskSelectionLogic" : { + "key" : "NULL", + "logicFlavour" : "UNDEFINED", + "logic" : "" + }, + "stateFinalizerLogicMap" : { + "entry" : [ ] + }, + "defaultTask" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "taskReferences" : { + "entry" : [ { + "key" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "parentKeyName" : "BasicPolicy", + "parentKeyVersion" : "0.0.1", + "parentLocalName" : "OnlyState", + "localName" : "BasicTask" + }, + "outputType" : "DIRECT", + "output" : { + "parentKeyName" : "BasicPolicy", + "parentKeyVersion" : "0.0.1", + "parentLocalName" : "OnlyState", + "localName" : "OnlyOutput" + } + } + } ] + } + } + } ] + }, + "firstState" : "OnlyState" + } + } ] + } + }, + "tasks" : { + "key" : { + "name" : "SmallModel_Tasks", + "version" : "0.0.1" + }, + "taskMap" : { + "entry" : [ { + "key" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicTask", + "version" : "0.0.1" + }, + "inputFields" : { + "entry" : [ { + "key" : "intPar", + "value" : { + "key" : "intPar", + "fieldSchemaKey" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "optional" : false + } + } ] + }, + "outputFields" : { + "entry" : [ { + "key" : "intPar", + "value" : { + "key" : "intPar", + "fieldSchemaKey" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "optional" : false + } + } ] + }, + "taskParameters" : { + "entry" : [ ] + }, + "contextAlbumReference" : [ { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + } ], + "taskLogic" : { + "key" : "TaskLogic", + "logicFlavour" : "JAVASCRIPT", + "logic" : "executor.logger.debug(executor.subject.id);\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.name);\nexecutor.logger.debug(executor.inFields);\n\nexecutor.logger.debug(executor.eo);\n\nvar returnValue = executor.isTrue;" + } + } + } ] + } + }, + "events" : { + "key" : { + "name" : "SmallModel_Events", + "version" : "0.0.1" + }, + "eventMap" : { + "entry" : [ { + "key" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicEvent", + "version" : "0.0.1" + }, + "nameSpace" : "org.onap.policy.apex.events", + "source" : "source", + "target" : "target", + "parameter" : { + "entry" : [ { + "key" : "intPar", + "value" : { + "key" : "intPar", + "fieldSchemaKey" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "optional" : false + } + } ] + } + } + } ] + } + }, + "albums" : { + "key" : { + "name" : "SmallModel_Albums", + "version" : "0.0.1" + }, + "albums" : { + "entry" : [ { + "key" : { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "BasicContextAlbum", + "version" : "0.0.1" + }, + "scope" : "GLOBAL", + "isWritable" : true, + "itemSchema" : { + "name" : "IntType", + "version" : "0.0.1" + } + } + } ] + } + }, + "schemas" : { + "key" : { + "name" : "SmallModel_Schemas", + "version" : "0.0.1" + }, + "schemas" : { + "entry" : [ { + "key" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "value" : { + "key" : { + "name" : "IntType", + "version" : "0.0.1" + }, + "schemaFlavour" : "Java", + "schemaDefinition" : "java.lang.Integer" + } + } ] + } + } + } +} diff --git a/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentExceptionTest.java b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentExceptionTest.java new file mode 100644 index 000000000..fc941acf0 --- /dev/null +++ b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentExceptionTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.deployment.rest; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +/** + * Test the REST Deployment exception. + * + */ +public class DeploymentExceptionTest { + + @Test + public void test() { + ApexDeploymentRestParameterException ame = new ApexDeploymentRestParameterException("a message"); + assertEquals("a message", ame.getMessage()); + } +} diff --git a/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestMainTest.java b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestMainTest.java new file mode 100644 index 000000000..2ca12ab9a --- /dev/null +++ b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestMainTest.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.deployment.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.catchThrowable; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * Test the periodic event manager utility. + */ +public class DeploymentRestMainTest { + private static InputStream systemInStream = System.in; + + @Test + public void testDeploymentClientOk() { + final String[] eventArgs = {"-t", "1", "-p", "1256"}; + assertThatCode(() -> ApexDeploymentRestMain.main(eventArgs)).doesNotThrowAnyException(); + } + + @Test + public void testDeploymentClientNoOptions() { + final String[] eventArgs = new String[] + {}; + assertThat(testApexDeploymentRestMainConstructor(eventArgs)).isEqualTo("*** StdOut ***\n\n*** StdErr ***\n"); + } + + @Test + public void testDeploymentClientBadOptions() { + final String[] eventArgs = + { "-zabbu" }; + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[null], State=STOPPED) " + + "parameter error, invalid command line arguments specified " + + ": Unrecognized option: -zabbu"); + } + + @Test + public void testDeploymentClientHelp() { + final String[] eventArgs = + { "-h" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "usage: org.onap.policy.apex.client.deployment.rest.ApexDeploymentRestMain [options...]"); + + } + + @Test + public void testDeploymentClientPortBad() { + final String[] eventArgs = + { "-p", "hello" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[null], State=STOPPED) " + + "parameter error, error parsing argument \"port\" :For input string: \"hello\""); + + } + + @Test + public void testDeploymentClientPortNegative() { + final String[] eventArgs = + { "-p", "-1" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[ApexDeploymentRestParameters: " + + "URI=http://localhost:-1/apexservices/, TTL=-1sec], State=STOPPED) parameters invalid, " + + "port must be greater than 1023 and less than 65536"); + + } + + @Test + public void testDeploymentClientTtlTooSmall() { + final String[] eventArgs = + { "-t", "-2" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[ApexDeploymentRestParameters: " + + "URI=http://localhost:18989/apexservices/, TTL=-2sec], State=STOPPED) parameters invalid, " + + "time to live must be greater than -1 (set to -1 to wait forever)"); + + } + + @Test + public void testDeploymentClientTooManyPars() { + final String[] eventArgs = + { "-t", "10", "-p", "12344", "aaa", "bbb" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[null], State=STOPPED) " + + "parameter error, too many command line arguments specified : [aaa, bbb]"); + } + + @Test + public void testDeploymentClientDefaultPars() { + assertThatCode(() -> { + ApexDeploymentRest monRest = new ApexDeploymentRest(); + monRest.shutdown(); + }).doesNotThrowAnyException(); + + } + + @Test + public void testDeploymentClientTtlNotNumber() { + final String[] eventArgs = + { "-t", "timetolive" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[null], State=STOPPED) " + + "parameter error, error parsing argument \"time-to-live\" :" + + "For input string: \"timetolive\""); + + } + + @Test + public void testDeploymentClientPortTooBig() { + final String[] eventArgs = + { "-p", "65536" }; + + Throwable thrown = catchThrowable(() -> new ApexDeploymentRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Services REST endpoint (ApexDeploymentRestMain: Config=[ApexDeploymentRestParameters: " + + "URI=http://localhost:65536/apexservices/, TTL=-1sec], State=STOPPED) parameters invalid, " + + "port must be greater than 1023 and less than 65536"); + } + + @Test + public void testDeploymentOneSecStart() { + final String[] eventArgs = + { "-t", "1" }; + + assertThatCode(() -> { + ApexDeploymentRestMain monRestMain = new ApexDeploymentRestMain(eventArgs, System.out); + monRestMain.init(); + monRestMain.shutdown(); + }).doesNotThrowAnyException(); + + } + + @Test + public void testDeploymentForeverStart() { + final String[] eventArgs = + { "-t", "-1" }; + + ApexDeploymentRestMain monRestMain = new ApexDeploymentRestMain(eventArgs, System.out); + + Thread monThread = new Thread() { + @Override + public void run() { + monRestMain.init(); + } + }; + + assertThatCode(() -> { + monThread.start(); + ThreadUtilities.sleep(2000); + monRestMain.shutdown(); + }).doesNotThrowAnyException(); + + } + + @After + public void cleanUpStreamSetting() { + System.setIn(systemInStream); + } + + /** + * Run the application. + * + * @param eventArgs the command arguments + * @return a string containing the command output + */ + private String testApexDeploymentRestMainConstructor(final String[] eventArgs) { + final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); + final ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); + + new ApexDeploymentRestMain(eventArgs, new PrintStream(baosOut, true)); + + InputStream testInput = new ByteArrayInputStream("Test Data for Input to WS".getBytes()); + System.setIn(testInput); + + String outString = baosOut.toString(); + String errString = baosErr.toString(); + + return "*** StdOut ***\n" + outString + "\n*** StdErr ***\n" + errString; + } +} diff --git a/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestParameterTest.java b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestParameterTest.java new file mode 100644 index 000000000..4fddffaef --- /dev/null +++ b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/DeploymentRestParameterTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.deployment.rest; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +/** + * Extra Deployment rest tests. + * + */ +public class DeploymentRestParameterTest { + + @Test + public void test() { + ApexDeploymentRestParameters parameters = new ApexDeploymentRestParameters(); + parameters.setRestPort(12345); + assertEquals(12345, parameters.getRestPort()); + } +} diff --git a/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/ParameterCheckTest.java b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/ParameterCheckTest.java new file mode 100644 index 000000000..a0c4c9c3e --- /dev/null +++ b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/ParameterCheckTest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.deployment.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; + +/** + * Test the parameter check class. + * + */ +public class ParameterCheckTest { + + @Test + public void testStartStop() { + assertEquals("START", ParameterCheck.StartStop.START.name()); + assertEquals("STOP", ParameterCheck.StartStop.STOP.name()); + } + + @Test + public void testHostName() { + assertNull(ParameterCheck.getHostName(null)); + + Map parameterMap = new LinkedHashMap<>(); + assertNull(ParameterCheck.getHostName(parameterMap)); + parameterMap.put("hostname", null); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameBlankValue0 = {"", ""}; + parameterMap.put("hostname", hostnameBlankValue0); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameBlankValue1 = {" ", " "}; + parameterMap.put("hostname", hostnameBlankValue1); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameValue = {"hostname0", "hostname1"}; + parameterMap.put("hostname", hostnameValue); + assertEquals("hostname0", ParameterCheck.getHostName(parameterMap)); + } + + @Test + public void testPort() { + assertEquals(-1, ParameterCheck.getPort(null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portBlankValue0 = {"", ""}; + parameterMap.put("port", portBlankValue0); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portBlankValue1 = {" ", " "}; + parameterMap.put("port", portBlankValue1); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueBad = {"port", "value"}; + parameterMap.put("port", portValueBad); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueRange0 = {"-1", "-1"}; + parameterMap.put("port", portValueRange0); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueRange1 = {"65536", "65536"}; + parameterMap.put("port", portValueRange1); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValue = {"12344", "23221"}; + parameterMap.put("port", portValue); + assertEquals(12344, ParameterCheck.getPort(parameterMap)); + } + + @Test + public void testEngineKey() { + assertEquals(null, ParameterCheck.getEngineKey(null)); + + Map parameterMap = new LinkedHashMap<>(); + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + + parameterMap.put("AxArtifactKey", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey"); + + parameterMap.put("AxArtifactKey#zooby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey#zooby"); + + parameterMap.put("AxArtifactKey#zooby#looby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey#zooby#looby"); + + parameterMap.put("AxArtifactKey#Name:0.0.1", null); + assertEquals(new AxArtifactKey("Name", "0.0.1"), ParameterCheck.getEngineKey(parameterMap)); + } + + @Test + public void testStartStopValue() { + assertEquals(null, ParameterCheck.getStartStop(null, null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, null)); + + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, null)); + + AxArtifactKey engineKey = new AxArtifactKey("Engine", "0.0.1"); + + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String key = "AxArtifactKey#" + engineKey.getId(); + + parameterMap.put(key, null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopBlankValue0 = {"", ""}; + parameterMap.put(key, startStopBlankValue0); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopBlankValue1 = {" ", " "}; + parameterMap.put(key, startStopBlankValue1); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopValueBad = {key, "value"}; + parameterMap.put(key, startStopValueBad); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startValue = {"START", "STOP"}; + parameterMap.put(key, startValue); + assertEquals(ParameterCheck.StartStop.START, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] stopValue = {"STOP", "START"}; + parameterMap.put(key, stopValue); + assertEquals(ParameterCheck.StartStop.STOP, ParameterCheck.getStartStop(parameterMap, engineKey)); + } + + @Test + public void testLong() { + assertEquals(-1, ParameterCheck.getLong(null, null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(-1, ParameterCheck.getLong(parameterMap, null)); + + parameterMap.put("long0", null); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "longx")); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long0")); + + String[] longBlankValue0 = {"", ""}; + parameterMap.put("long1", longBlankValue0); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long1")); + + String[] longBlankValue1 = {" ", " "}; + parameterMap.put("long2", longBlankValue1); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long2")); + + String[] longValueBad = {"long", "value"}; + parameterMap.put("long3", longValueBad); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long3")); + + String[] longValue = {"12345", "6789"}; + parameterMap.put("long4", longValue); + assertEquals(12345, ParameterCheck.getLong(parameterMap, "long4")); + } +} diff --git a/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/RestResourceTest.java b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/RestResourceTest.java new file mode 100644 index 000000000..e8625af5e --- /dev/null +++ b/client/client-deployment/src/test/java/org/onap/policy/apex/client/deployment/rest/RestResourceTest.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.deployment.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import javax.ws.rs.core.Response; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.policy.apex.core.deployment.ApexDeploymentException; +import org.onap.policy.apex.core.deployment.EngineServiceFacade; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel; + +/** + * Test the Deployment rest resource. + */ +public class RestResourceTest { + @Mock + private EngineServiceFacade engineServiceFacadeMock; + private ApexDeploymentRestResource restResource; + + /** + * Set up mocking of the engine service facade. + * + * @throws ApexException on engine service facade setup errors + */ + @Before + public void initializeMocking() throws ApexException { + MockitoAnnotations.initMocks(this); + + final AxArtifactKey engineServiceKey = new AxArtifactKey("EngineServiceKey", "0.0.1"); + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + final AxArtifactKey[] engineServiceKeyArray = {engineKey}; + final AxEngineModel engineModel = new AxEngineModel(engineServiceKeyArray[0]); + + restResource = Mockito.spy(new ApexDeploymentRestResource()); + Mockito.doReturn(engineServiceFacadeMock).when(restResource).getEngineServiceFacade("apexServer", 12345); + + Mockito.doReturn(engineServiceKey).when(engineServiceFacadeMock).getKey(); + Mockito.doReturn(engineServiceKeyArray).when(engineServiceFacadeMock).getEngineKeyArray(); + Mockito.doReturn(engineModel).when(engineServiceFacadeMock).getEngineStatus(engineKey); + } + + @Test + public void testRestResourceCreateSession() throws ApexException { + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionWithApexModelKey() throws ApexException { + Mockito.doReturn(new AxArtifactKey("ModelKey:0.0.1")).when(engineServiceFacadeMock).getApexModelKey(); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionConnectException() throws ApexException { + Mockito.doThrow(new ApexDeploymentException("Connection Failed")).when(engineServiceFacadeMock).init(); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(500, response.getStatus()); + assertTrue(((String) response.getEntity()).contains("Error connecting to Apex Engine Service")); + } + + @Test + public void testRestResourceCreateSessionGetException() throws ApexException { + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + Mockito.doThrow(new ApexException("Exception on get")).when(engineServiceFacadeMock).getEngineStatus(engineKey); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionInfo() throws ApexException { + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + Mockito.doReturn("{}").when(engineServiceFacadeMock).getEngineInfo(engineKey); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionNullInfo() throws ApexException { + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + Mockito.doReturn(null).when(engineServiceFacadeMock).getEngineInfo(engineKey); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionEmptyInfo() throws ApexException { + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + Mockito.doReturn(" ").when(engineServiceFacadeMock).getEngineInfo(engineKey); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourceCreateSessionExceptionInfo() throws ApexException { + final AxArtifactKey engineKey = new AxArtifactKey("Engine0", "0.0.1"); + Mockito.doThrow(new ApexException("Exception on info")).when(engineServiceFacadeMock).getEngineInfo(engineKey); + + Response response = restResource.createSession("apexServer", 12345); + assertEquals(200, response.getStatus()); + } + + @Test + public void testRestResourcemodelUpload() throws ApexException { + InputStream uploadedInputStream = + new ByteArrayInputStream("src/test/resources/models/SmallModel.json".getBytes()); + + Response response = restResource.modelUpload("apexServer", 12345, + uploadedInputStream, "SmallModel.json", false, false); + assertEquals(200, response.getStatus()); + assertTrue(((String) response.getEntity()).contains("SmallModel.json")); + } + + @Test + public void testRestResourcemodelUploadNoConnection() throws ApexException { + Mockito.doThrow(new ApexDeploymentException("Connection Failed")).when(engineServiceFacadeMock).init(); + + InputStream uploadedInputStream = + new ByteArrayInputStream("src/test/resources/models/SmallModel.json".getBytes()); + + Response response = + restResource.modelUpload("apexServer", 12345, uploadedInputStream, "SmallModel.json", false, false); + assertEquals(500, response.getStatus()); + } + + @Test + public void testRestResourcemodelUploadDeploy() throws ApexException { + + InputStream uploadedInputStream = + new ByteArrayInputStream("src/test/resources/models/SmallModel.json".getBytes()); + + Mockito.doThrow(new ApexDeploymentException("Connection Failed")).when(engineServiceFacadeMock) + .deployModel("SmallModel.json", uploadedInputStream, false, true); + + + Response response = + restResource.modelUpload("apexServer", 12345, uploadedInputStream, "SmallModel.json", false, true); + assertEquals(500, response.getStatus()); + assertTrue(((String) response.getEntity()).contains("Error updating model on engine service")); + } +} diff --git a/client/client-full/pom.xml b/client/client-full/pom.xml index 5dd505b9a..c4591af85 100644 --- a/client/client-full/pom.xml +++ b/client/client-full/pom.xml @@ -77,7 +77,12 @@ zip provided - + + org.assertj + assertj-core + 3.13.2 + test + diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java index 9832f4317..1fb01c86e 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +22,6 @@ package org.onap.policy.apex.client.full.rest; import java.util.Map; - import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -69,6 +69,10 @@ public final class ParameterCheck { * @return the host name */ public static String getHostName(final Map parameterMap) { + if (parameterMap == null) { + return null; + } + if (!parameterMap.containsKey(HOSTNAME_PAR)) { LOGGER.warn(PARAMETER + HOSTNAME_PAR + NOT_FOUND); return null; @@ -76,6 +80,10 @@ public final class ParameterCheck { final String[] hostNameValue = parameterMap.get(HOSTNAME_PAR); + if (hostNameValue == null) { + return null; + } + if (hostNameValue.length == 0 || hostNameValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"" + HOSTNAME_PAR + NOT_FOUND); return null; @@ -91,6 +99,10 @@ public final class ParameterCheck { * @return the port */ public static int getPort(final Map parameterMap) { + if (parameterMap == null) { + return -1; + } + if (!parameterMap.containsKey(PORT_PAR)) { LOGGER.warn(PARAMETER + PORT_PAR + NOT_FOUND); return -1; @@ -127,6 +139,10 @@ public final class ParameterCheck { * @return the engine key */ public static AxArtifactKey getEngineKey(final Map parameterMap) { + if (parameterMap == null) { + return null; + } + String artifactKeyParameter = null; for (final String parameter : parameterMap.keySet()) { // Check for an AxArtifactKey parameter @@ -147,7 +163,12 @@ public final class ParameterCheck { return null; } - return new AxArtifactKey(axArtifactKeyArray[1]); + try { + return new AxArtifactKey(axArtifactKeyArray[1]); + } catch (Exception apEx) { + LOGGER.trace("invalid artifact key ID {}", axArtifactKeyArray[1], apEx); + return null; + } } /** @@ -159,6 +180,10 @@ public final class ParameterCheck { */ public static ParameterCheck.StartStop getStartStop(final Map parameterMap, final AxArtifactKey engineKey) { + if (parameterMap == null || engineKey == null) { + return null; + } + final String startStopPar = AXARTIFACTKEY_PAR + '#' + engineKey.getId(); if (!parameterMap.containsKey(startStopPar)) { LOGGER.warn("parameter \"{}\" not found", startStopPar); @@ -167,6 +192,10 @@ public final class ParameterCheck { final String[] startStopValue = parameterMap.get(startStopPar); + if (startStopValue == null) { + return null; + } + if (startStopValue.length == 0 || startStopValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"{}\" not found", startStopPar); return null; @@ -193,6 +222,10 @@ public final class ParameterCheck { * @return The long value */ public static long getLong(final Map parameterMap, final String longName) { + if (parameterMap == null || longName == null) { + return -1; + } + if (!parameterMap.containsKey(longName)) { LOGGER.warn("parameter \"{}\" not found", longName); return -1; @@ -200,6 +233,10 @@ public final class ParameterCheck { final String[] longValue = parameterMap.get(longName); + if (longValue == null) { + return -1; + } + if (longValue.length == 0 || longValue[0].trim().length() == 0) { LOGGER.warn("value of parameter \"{}\" not found", longName); return -1; diff --git a/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ParameterCheckTest.java b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ParameterCheckTest.java new file mode 100644 index 000000000..0be0ac91c --- /dev/null +++ b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ParameterCheckTest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.full.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; + +/** + * Test the parameter check class. + * + */ +public class ParameterCheckTest { + + @Test + public void testStartStop() { + assertEquals("START", ParameterCheck.StartStop.START.name()); + assertEquals("STOP", ParameterCheck.StartStop.STOP.name()); + } + + @Test + public void testHostName() { + assertNull(ParameterCheck.getHostName(null)); + + Map parameterMap = new LinkedHashMap<>(); + assertNull(ParameterCheck.getHostName(parameterMap)); + parameterMap.put("hostname", null); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameBlankValue0 = {"", ""}; + parameterMap.put("hostname", hostnameBlankValue0); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameBlankValue1 = {" ", " "}; + parameterMap.put("hostname", hostnameBlankValue1); + assertNull(ParameterCheck.getHostName(parameterMap)); + + String[] hostnameValue = {"hostname0", "hostname1"}; + parameterMap.put("hostname", hostnameValue); + assertEquals("hostname0", ParameterCheck.getHostName(parameterMap)); + } + + @Test + public void testPort() { + assertEquals(-1, ParameterCheck.getPort(null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portBlankValue0 = {"", ""}; + parameterMap.put("port", portBlankValue0); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portBlankValue1 = {" ", " "}; + parameterMap.put("port", portBlankValue1); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueBad = {"port", "value"}; + parameterMap.put("port", portValueBad); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueRange0 = {"-1", "-1"}; + parameterMap.put("port", portValueRange0); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValueRange1 = {"65536", "65536"}; + parameterMap.put("port", portValueRange1); + assertEquals(-1, ParameterCheck.getPort(parameterMap)); + + String[] portValue = {"12344", "23221"}; + parameterMap.put("port", portValue); + assertEquals(12344, ParameterCheck.getPort(parameterMap)); + } + + @Test + public void testEngineKey() { + assertEquals(null, ParameterCheck.getEngineKey(null)); + + Map parameterMap = new LinkedHashMap<>(); + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + + parameterMap.put("AxArtifactKey", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey"); + + parameterMap.put("AxArtifactKey#zooby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey#zooby"); + + parameterMap.put("AxArtifactKey#zooby#looby", null); + assertEquals(null, ParameterCheck.getEngineKey(parameterMap)); + parameterMap.remove("AxArtifactKey#zooby#looby"); + + parameterMap.put("AxArtifactKey#Name:0.0.1", null); + assertEquals(new AxArtifactKey("Name", "0.0.1"), ParameterCheck.getEngineKey(parameterMap)); + } + + @Test + public void testStartStopValue() { + assertEquals(null, ParameterCheck.getStartStop(null, null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, null)); + + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, null)); + + AxArtifactKey engineKey = new AxArtifactKey("Engine", "0.0.1"); + + parameterMap.put("Zooby", null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String key = "AxArtifactKey#" + engineKey.getId(); + + parameterMap.put(key, null); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopBlankValue0 = {"", ""}; + parameterMap.put(key, startStopBlankValue0); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopBlankValue1 = {" ", " "}; + parameterMap.put(key, startStopBlankValue1); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startStopValueBad = {key, "value"}; + parameterMap.put(key, startStopValueBad); + assertEquals(null, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] startValue = {"START", "STOP"}; + parameterMap.put(key, startValue); + assertEquals(ParameterCheck.StartStop.START, ParameterCheck.getStartStop(parameterMap, engineKey)); + + String[] stopValue = {"STOP", "START"}; + parameterMap.put(key, stopValue); + assertEquals(ParameterCheck.StartStop.STOP, ParameterCheck.getStartStop(parameterMap, engineKey)); + } + + @Test + public void testLong() { + assertEquals(-1, ParameterCheck.getLong(null, null)); + + Map parameterMap = new LinkedHashMap<>(); + assertEquals(-1, ParameterCheck.getLong(parameterMap, null)); + + parameterMap.put("long0", null); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "longx")); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long0")); + + String[] longBlankValue0 = {"", ""}; + parameterMap.put("long1", longBlankValue0); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long1")); + + String[] longBlankValue1 = {" ", " "}; + parameterMap.put("long2", longBlankValue1); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long2")); + + String[] longValueBad = {"long", "value"}; + parameterMap.put("long3", longValueBad); + assertEquals(-1, ParameterCheck.getLong(parameterMap, "long3")); + + String[] longValue = {"12345", "6789"}; + parameterMap.put("long4", longValue); + assertEquals(12345, ParameterCheck.getLong(parameterMap, "long4")); + } +} diff --git a/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesExceptionTest.java b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesExceptionTest.java new file mode 100644 index 000000000..7ae8e7143 --- /dev/null +++ b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesExceptionTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.full.rest; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +/** + * Test the REST Services exception. + * + */ +public class ServicesExceptionTest { + + @Test + public void test() { + ApexServicesRestParameterException ame = new ApexServicesRestParameterException("a message"); + assertEquals("a message", ame.getMessage()); + } +} diff --git a/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestMainTest.java b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestMainTest.java new file mode 100644 index 000000000..f6b3373ce --- /dev/null +++ b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestMainTest.java @@ -0,0 +1,221 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.full.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.catchThrowable; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * Test the periodic event manager utility. + */ +public class ServicesRestMainTest { + private static InputStream systemInStream = System.in; + + @Test + public void testServicesMainClientOk() { + final String[] eventArgs = {"-t", "1", "-p", "1256"}; + assertThatCode(() -> ApexServicesRestMain.main(eventArgs)).doesNotThrowAnyException(); + } + + @Test + public void testServicesClientNoOptions() { + final String[] eventArgs = new String[] + {}; + + assertThat(testApexServicesRestMainConstructor(eventArgs)).isEqualTo("*** StdOut ***\n\n*** StdErr ***\n"); + + + } + + @Test + public void testServicesClientBadOptions() { + final String[] eventArgs = + { "-zabbu" }; + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Editor REST endpoint (ApexServicesRestMain: Config=[null], State=STOPPED) " + + "parameter error, invalid command line arguments specified " + + ": Unrecognized option: -zabbu"); + } + + @Test + public void testServicesClientHelp() { + final String[] eventArgs = + { "-h" }; + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class) + .hasMessageContaining("usage: org.onap.policy.apex.client.full.rest.ApexServicesRestMain [options...]"); + } + + @Test + public void testServicesClientPortBad() { + final String[] eventArgs = + { "-p", "hello" }; + + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class) + .hasMessageContaining("Apex Editor REST endpoint (ApexServicesRestMain: Config=[null], State=STOPPED) " + + "parameter error, error parsing argument \"port\" :For input string: \"hello\""); + + } + + @Test + public void testServicesClientPortNegative() { + final String[] eventArgs = + { "-p", "-1" }; + + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Editor REST endpoint (ApexServicesRestMain: Config=[ApexServicesRestParameters: " + + "URI=http://localhost:-1/apexservices/, TTL=-1sec], State=STOPPED) parameters invalid, " + + "port must be greater than 1023 and less than 65536"); + + } + + @Test + public void testServicesClientTtlTooSmall() { + final String[] eventArgs = + { "-t", "-2" }; + + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Editor REST endpoint (ApexServicesRestMain: Config=[ApexServicesRestParameters: " + + "URI=http://localhost:18989/apexservices/, TTL=-2sec], State=STOPPED) parameters invalid, " + + "time to live must be greater than -1 (set to -1 to wait forever)"); + } + + @Test + public void testServicesClientTooManyPars() { + final String[] eventArgs = + { "-t", "10", "-p", "12344", "aaa", "bbb" }; + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class) + .hasMessageContaining("Apex Editor REST endpoint (ApexServicesRestMain: Config=[null], State=STOPPED) " + + "parameter error, too many command line arguments specified : [aaa, bbb]"); + } + + + @Test + public void testServicesClientTtlNotNumber() { + final String[] eventArgs = + { "-t", "timetolive" }; + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class) + .hasMessageContaining("Apex Editor REST endpoint (ApexServicesRestMain: Config=[null], State=STOPPED) " + + "parameter error, error parsing argument \"time-to-live\" :" + + "For input string: \"timetolive\""); + } + + @Test + public void testServicesClientTtlSetValue() { + final String[] eventArgs = {"-t", "3", "-p", "1257"}; + assertThatCode(() -> { + ApexServicesRestMain monRestMain = new ApexServicesRestMain(eventArgs, System.out); + monRestMain.init(); + monRestMain.shutdown(); + }).doesNotThrowAnyException(); + + } + + @Test + public void testServicesClientPortTooBig() { + final String[] eventArgs = + { "-p", "65536" }; + Throwable thrown = catchThrowable(() -> new ApexServicesRestMain(eventArgs, System.out)); + + assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining( + "Apex Editor REST endpoint (ApexServicesRestMain: Config=[ApexServicesRestParameters: " + + "URI=http://localhost:65536/apexservices/, TTL=-1sec], State=STOPPED) parameters invalid, " + + "port must be greater than 1023 and less than 65536"); + } + + @Test + public void testServicesOneSecStart() { + final String[] eventArgs = {"-t", "1", "-p", "1258"}; + + assertThatCode(() -> { + ApexServicesRestMain monRestMain = new ApexServicesRestMain(eventArgs, System.out); + monRestMain.init(); + monRestMain.shutdown(); + }).doesNotThrowAnyException(); + } + + @Test + public void testServicesForeverStart() { + final String[] eventArgs = {"-t", "-1", "-p", "1259"}; + + ApexServicesRestMain monRestMain = new ApexServicesRestMain(eventArgs, System.out); + + Thread monThread = new Thread() { + @Override + public void run() { + monRestMain.init(); + } + }; + + assertThatCode(() -> { + monThread.start(); + ThreadUtilities.sleep(2000); + monRestMain.shutdown(); + }).doesNotThrowAnyException(); + } + + @After + public void cleanUpStreamSetting() { + System.setIn(systemInStream); + } + + /** + * Run the application. + * + * @param eventArgs the command arguments + * @return a string containing the command output + */ + private String testApexServicesRestMainConstructor(final String[] eventArgs) { + final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); + final ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); + + new ApexServicesRestMain(eventArgs, new PrintStream(baosOut, true)); + + InputStream testInput = new ByteArrayInputStream("Test Data for Input to WS".getBytes()); + System.setIn(testInput); + + String outString = baosOut.toString(); + String errString = baosErr.toString(); + + return "*** StdOut ***\n" + outString + "\n*** StdErr ***\n" + errString; + } +} diff --git a/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestParameterTest.java b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestParameterTest.java new file mode 100644 index 000000000..777a9c170 --- /dev/null +++ b/client/client-full/src/test/java/org/onap/policy/apex/client/full/rest/ServicesRestParameterTest.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.client.full.rest; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +/** + * Extra Services rest tests. + * + */ +public class ServicesRestParameterTest { + + @Test + public void test() { + ApexServicesRestParameters parameters = new ApexServicesRestParameters(); + parameters.setRestPort(12345); + assertEquals(12345, parameters.getRestPort()); + } + + @Test + public void testMainDefaultParameter() { + assertThatCode(() -> { + ApexServicesRest monRest = new ApexServicesRest(); + monRest.shutdown(); + }).doesNotThrowAnyException(); + } +} -- cgit 1.2.3-korg