diff options
author | a.sreekumar <ajith.sreekumar@est.tech> | 2019-04-16 09:40:48 +0000 |
---|---|---|
committer | a.sreekumar <ajith.sreekumar@est.tech> | 2019-04-16 09:40:48 +0000 |
commit | 00ee73f723560c825818eab41a4d3db9785627d4 (patch) | |
tree | 66b1cc9cd8d9544a68b5d2012835ad6efb12c249 /services/services-onappf/src/test | |
parent | 2ba499f11094cfd1321e59789869a0c475406b58 (diff) |
Changes for RestServer support and some sonar fix
1) Changes to add RestServer to the PDP-A for healthcheck.
2) Adding Junit testcases.
3) Fixing some sonar issues.
4) Fixing checkstyle issues.
Change-Id: I03530190c733432d219284dda9d9d4cc32ab0773
Issue-ID: POLICY-1632
Signed-off-by: a.sreekumar <ajith.sreekumar@est.tech>
Diffstat (limited to 'services/services-onappf/src/test')
9 files changed, 440 insertions, 7 deletions
diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java index 34025a1ad..c6ed44556 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java @@ -40,8 +40,6 @@ import org.junit.Test; import org.onap.policy.apex.services.onappf.ApexStarterActivator; import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; import org.onap.policy.apex.services.onappf.ApexStarterConstants; -import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener; -import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener; import org.onap.policy.apex.services.onappf.exception.ApexStarterException; import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; @@ -65,6 +63,13 @@ public class TestPdpStateChangeListener { private static final String TOPIC = "my-topic"; private ApexStarterActivator activator; + /** + * Method for setup before each test. + * + * @throws ApexStarterException if some error occurs while starting up the apex starter + * @throws FileNotFoundException if the file is missing + * @throws IOException if IO exception occurs + */ @Before public void setUp() throws ApexStarterException, FileNotFoundException, IOException { pdpUpdateMessageListener = new PdpUpdateListener(); @@ -112,8 +117,10 @@ public class TestPdpStateChangeListener { } /** - * @param instance - * @return + * Method to initiate a PdpUpdate. + * + * @param instance the instance id + * @return PdpUpdate the pdp update message */ private PdpUpdate performPdpUpdate(final String instance) { final PdpUpdate pdpUpdateMsg = new PdpUpdate(); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java index 921cfd283..ebe0fc957 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java @@ -40,7 +40,6 @@ import org.junit.Test; import org.onap.policy.apex.services.onappf.ApexStarterActivator; import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; import org.onap.policy.apex.services.onappf.ApexStarterConstants; -import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener; import org.onap.policy.apex.services.onappf.exception.ApexStarterException; import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler; import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; @@ -62,6 +61,13 @@ public class TestPdpUpdateListener { private static final String TOPIC = "my-topic"; private ApexStarterActivator activator; + /** + * Method for setup before each test. + * + * @throws ApexStarterException if some error occurs while starting up the apex starter + * @throws FileNotFoundException if the file is missing + * @throws IOException if IO exception occurs + */ @Before public void setUp() throws ApexStarterException, FileNotFoundException, IOException { Registry.newRegistry(); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java index e4946dd2b..7e668e9b2 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters; import org.onap.policy.common.parameters.ParameterGroup; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; @@ -48,6 +47,12 @@ public class CommonTestData { public static final String POLICY_VERSION = "0.0.1"; public static final List<ToscaPolicyTypeIdentifierParameters> SUPPORTED_POLICY_TYPES = Arrays.asList(getSupportedPolicyTypes(POLICY_NAME, POLICY_VERSION)); + private static final String REST_SERVER_PASSWORD = "zb!XztG34"; + private static final String REST_SERVER_USER = "healthcheck"; + private static final int REST_SERVER_PORT = 6969; + private static final String REST_SERVER_HOST = "0.0.0.0"; + private static final boolean REST_SERVER_HTTPS = true; + private static final boolean REST_SERVER_AAF = false; public static final Coder coder = new StandardCoder(); @@ -90,12 +95,34 @@ public class CommonTestData { final Map<String, Object> map = new TreeMap<>(); map.put("name", name); + map.put("restServerParameters", getRestServerParametersMap(false)); map.put("pdpStatusParameters", getPdpStatusParametersMap(false)); return map; } /** + * Returns a property map for a RestServerParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getRestServerParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + map.put("https", REST_SERVER_HTTPS); + map.put("aaf", REST_SERVER_AAF); + + if (!isEmpty) { + map.put("host", REST_SERVER_HOST); + map.put("port", REST_SERVER_PORT); + map.put("userName", REST_SERVER_USER); + map.put("password", REST_SERVER_PASSWORD); + } + + return map; + } + + /** * Returns a property map for a PdpStatusParameters map for test cases. * * @param isEmpty boolean value to represent that object created should be empty or not diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java index c843c6787..dd9e83f52 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java @@ -48,6 +48,7 @@ public class TestApexStarterParameterGroup { final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), ApexStarterParameterGroup.class); + final RestServerParameters restServerParameters = apexStarterParameters.getRestServerParameters(); final PdpStatusParameters pdpStatusParameters = apexStarterParameters.getPdpStatusParameters(); final GroupValidationResult validationResult = apexStarterParameters.validate(); assertTrue(validationResult.isValid()); @@ -56,6 +57,12 @@ public class TestApexStarterParameterGroup { assertEquals(CommonTestData.PDP_TYPE, pdpStatusParameters.getPdpType()); assertEquals(CommonTestData.DESCRIPTION, pdpStatusParameters.getDescription()); assertEquals(CommonTestData.SUPPORTED_POLICY_TYPES, pdpStatusParameters.getSupportedPolicyTypes()); + assertEquals(restServerParameters.getHost(), apexStarterParameters.getRestServerParameters().getHost()); + assertEquals(restServerParameters.getPort(), apexStarterParameters.getRestServerParameters().getPort()); + assertEquals(restServerParameters.getUserName(), apexStarterParameters.getRestServerParameters().getUserName()); + assertEquals(restServerParameters.getPassword(), apexStarterParameters.getRestServerParameters().getPassword()); + assertTrue(apexStarterParameters.getRestServerParameters().isHttps()); + assertFalse(apexStarterParameters.getRestServerParameters().isAaf()); } @Test @@ -103,4 +110,19 @@ public class TestApexStarterParameterGroup { .contains("\"org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup\" INVALID, " + "parameter group has status INVALID")); } + + @Test + public void testApexStarterParameterGroupp_EmptyRestServerParameters() { + final Map<String, Object> map = + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); + map.put("restServerParameters", commonTestData.getRestServerParametersMap(true)); + + final ApexStarterParameterGroup apexStarterParameters = + commonTestData.toObject(map, ApexStarterParameterGroup.class); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertFalse(validationResult.isValid()); + assertTrue(validationResult.getResult() + .contains("\"org.onap.policy.apex.services.onappf.parameters.RestServerParameters\" INVALID, " + + "parameter group has status INVALID")); + } } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java new file mode 100644 index 000000000..72db6e091 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java @@ -0,0 +1,286 @@ +/*- + * ============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.services.onappf.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.security.SecureRandom; +import java.util.Map; +import java.util.Properties; +import java.util.function.Function; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.onap.policy.apex.services.onappf.ApexStarterActivator; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.ApexStarterMain; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.CommonTestData; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.network.NetworkUtil; +import org.onap.policy.common.utils.services.Registry; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class to perform unit test of {@link ApexStarterRestServer}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class CommonApexStarterRestServer { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommonApexStarterRestServer.class); + + private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; + + private static Coder coder = new StandardCoder(); + + public static final String NOT_ALIVE = "not alive"; + public static final String ALIVE = "alive"; + public static final String SELF = "self"; + public static final String NAME = "Policy PDP-A"; + public static final String ENDPOINT_PREFIX = "policy/apex-pdp/v1/"; + + private static int port; + protected static String httpsPrefix; + + private static ApexStarterMain main; + + private boolean activatorWasAlive; + + /** + * Allocates a port for the server, writes a config file, and then starts Main. + * + * @throws Exception if an error occurs + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + port = NetworkUtil.allocPort(); + + httpsPrefix = "https://localhost:" + port + "/"; + + makeConfigFile(); + + startMain(); + } + + /** + * Stops Main. + */ + @AfterClass + public static void teardownAfterClass() { + try { + stopMain(); + + } catch (final ApexStarterException exp) { + LOGGER.error("cannot stop main", exp); + } + } + + /** + * Set up. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + // restart, if not currently running + if (main == null) { + startMain(); + } + + activatorWasAlive = + Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class).isAlive(); + } + + /** + * Restores the activator's "alive" state. + */ + @After + public void tearDown() { + markActivator(activatorWasAlive); + } + + /** + * Verifies that an endpoint appears within the swagger response. + * + * @param endpoint the endpoint of interest + * @throws Exception if an error occurs + */ + protected void testSwagger(final String endpoint) throws Exception { + final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true); + final String resp = invocationBuilder.get(String.class); + + assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":")); + } + + /** + * Makes a parameter configuration file. + * + * @throws Exception if an error occurs + */ + private static void makeConfigFile() throws Exception { + final Map<String, Object> config = + new CommonTestData().getApexStarterParameterGroupMap("ApexStarterParameterGroup"); + + @SuppressWarnings("unchecked") + final Map<String, Object> restParams = (Map<String, Object>) config.get("restServerParameters"); + restParams.put("port", port); + + final File file = new File("src/test/resources/TestConfigParams.json"); + file.deleteOnExit(); + + coder.encode(file, config); + } + + /** + * Starts the "Main". + * + * @throws Exception if an error occurs + */ + private static void startMain() throws Exception { + Registry.newRegistry(); + + // make sure port is available + if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) { + throw new IllegalStateException("port " + port + " is still in use"); + } + + final Properties systemProps = System.getProperties(); + systemProps.put("javax.net.ssl.keyStore", KEYSTORE); + systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); + System.setProperties(systemProps); + + // @formatter:off + final String[] apexStarterConfigParameters = { + "-c", "src/test/resources/TestConfigParams.json", + "-p", "src/test/resources/topic.properties" + }; + // @formatter:on + + main = new ApexStarterMain(apexStarterConfigParameters); + + if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) { + throw new IllegalStateException("server is not listening on port " + port); + } + } + + /** + * Stops the "Main". + * + * @throws Exception if an error occurs + */ + private static void stopMain() throws ApexStarterException { + if (main != null) { + final ApexStarterMain main2 = main; + main = null; + + main2.shutdown(); + } + } + + private void markActivator(final boolean wasAlive) { + final Object manager = Whitebox.getInternalState( + Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class), "manager"); + Whitebox.setInternalState(manager, "running", wasAlive); + } + + /** + * Verifies that unauthorized requests fail. + * + * @param endpoint the target end point + * @param sender function that sends the requests to the target + * @throws Exception if an error occurs + */ + protected void checkUnauthRequest(final String endpoint, final Function<Invocation.Builder, Response> sender) + throws Exception { + assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), + sender.apply(sendNoAuthRequest(endpoint)).getStatus()); + } + + /** + * Sends a request to an endpoint. + * + * @param endpoint the target endpoint + * @return a request builder + * @throws Exception if an error occurs + */ + protected Invocation.Builder sendRequest(final String endpoint) throws Exception { + return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true); + } + + /** + * Sends a request to an endpoint, without any authorization header. + * + * @param endpoint the target endpoint + * @return a request builder + * @throws Exception if an error occurs + */ + protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception { + return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false); + } + + /** + * Sends a request to a fully qualified endpoint. + * + * @param fullyQualifiedEndpoint the fully qualified target endpoint + * @param includeAuth if authorization header should be included + * @return a request builder + * @throws Exception if an error occurs + */ + protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, final boolean includeAuth) + throws Exception { + final SSLContext sc = SSLContext.getInstance("TLSv1.2"); + sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom()); + final ClientBuilder clientBuilder = + ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); + final Client client = clientBuilder.build(); + + client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); + client.register(GsonMessageBodyHandler.class); + + if (includeAuth) { + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); + client.register(feature); + } + + final WebTarget webTarget = client.target(fullyQualifiedEndpoint); + + return webTarget.request(MediaType.APPLICATION_JSON); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java new file mode 100644 index 000000000..cd625c8dd --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java @@ -0,0 +1,62 @@ +/*- + * ============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.services.onappf.rest; + +import static org.junit.Assert.assertEquals; + +import javax.ws.rs.client.Invocation; + +import org.junit.Test; +import org.onap.policy.common.endpoints.report.HealthCheckReport; + +/** + * Class to perform unit test of {@link ApexStarterRestServer}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestHealthCheckRestControllerV1 extends CommonApexStarterRestServer { + + private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; + + @Test + public void testSwagger() throws Exception { + super.testSwagger(HEALTHCHECK_ENDPOINT); + } + + @Test + public void testHealthCheckSuccess() throws Exception { + final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); + final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); + validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); + + // verify it fails when no authorization info is included + checkUnauthRequest(HEALTHCHECK_ENDPOINT, req -> req.get()); + } + + private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code, + final String message, final HealthCheckReport report) { + assertEquals(name, report.getName()); + assertEquals(url, report.getUrl()); + assertEquals(healthy, report.isHealthy()); + assertEquals(code, report.getCode()); + assertEquals(message, report.getMessage()); + } +} diff --git a/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json b/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json index b1ea14de7..d38031d41 100644 --- a/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json +++ b/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json @@ -1,9 +1,16 @@ { "name":"ApexStarterParameterGroup", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34", + "https": true + }, "pdpStatusParameters":{ "timeIntervalMs": 120000, "pdpType":"apex", - "description":"Pdp status for HealthCheck", + "description":"Pdp Heartbeat", "supportedPolicyTypes":[{"name":"onap.policies.controlloop.Operational","version":"1.0.0"}] } }
\ No newline at end of file diff --git a/services/services-onappf/src/test/resources/TestConfigParameters.json b/services/services-onappf/src/test/resources/TestConfigParameters.json new file mode 100644 index 000000000..d9f095f21 --- /dev/null +++ b/services/services-onappf/src/test/resources/TestConfigParameters.json @@ -0,0 +1,16 @@ +{ + "name":"ApexStarterParameterGroup", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34", + "https": true + }, + "pdpStatusParameters":{ + "timeIntervalMs": 120000, + "pdpType":"apex", + "description":"Pdp heartbeat", + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.Operational","version":"1.0.0"}] + } +}
\ No newline at end of file diff --git a/services/services-onappf/src/test/resources/ssl/policy-keystore b/services/services-onappf/src/test/resources/ssl/policy-keystore Binary files differnew file mode 100644 index 000000000..7d2b1ecce --- /dev/null +++ b/services/services-onappf/src/test/resources/ssl/policy-keystore |