diff options
Diffstat (limited to 'main')
11 files changed, 531 insertions, 342 deletions
diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java index 18b87641..687c5fb0 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java @@ -71,6 +71,10 @@ public class PapActivator { * @throws PolicyPapException on errors in initializing the service */ public void initialize() throws PolicyPapException { + if (isAlive()) { + throw new IllegalStateException("activator already initialized"); + } + try { LOGGER.debug("Policy pap starting as a service . . ."); startPapRestServer(); @@ -89,6 +93,10 @@ public class PapActivator { * @throws PolicyPapException on errors in terminating the service */ public void terminate() throws PolicyPapException { + if (!isAlive()) { + throw new IllegalStateException("activator is not running"); + } + try { deregisterToParameterService(papParameterGroup); setAlive(false); diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java index 0c28de62..27d8ac2a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +32,7 @@ public class CommonTestData { 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 = false; + private static final boolean REST_SERVER_HTTPS = true; private static final boolean REST_SERVER_AAF = false; public static final String PAP_GROUP_NAME = "PapGroup"; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java index 5569b65a..4759f646 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +48,7 @@ public class TestPapParameterGroup { assertEquals(restServerParameters.getPort(), papParameters.getRestServerParameters().getPort()); assertEquals(restServerParameters.getUserName(), papParameters.getRestServerParameters().getUserName()); assertEquals(restServerParameters.getPassword(), papParameters.getRestServerParameters().getPassword()); - assertFalse(papParameters.getRestServerParameters().isHttps()); + assertTrue(papParameters.getRestServerParameters().isHttps()); assertFalse(papParameters.getRestServerParameters().isAaf()); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java new file mode 100644 index 00000000..8f522740 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -0,0 +1,285 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ================================================================================ + * 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.pap.main.rest; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +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 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.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.network.NetworkUtil; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.startstop.Main; +import org.onap.policy.pap.main.startstop.PapActivator; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class to perform unit test of {@link PapRestServer}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class CommonPapRestServer { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.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 PAP"; + public static final String ENDPOINT_PREFIX = "policy/pap/v1/"; + + private static int port; + protected static String httpsPrefix; + + private static Main 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 { + allocPort(); + + httpsPrefix = "https://localhost:" + port + "/"; + + makeConfigFile(); + + startMain(); + } + + /** + * Stops Main. + */ + @AfterClass + public static void teardownAfterClass() { + try { + stopMain(); + + } catch (PolicyPapException 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 = PapActivator.getCurrent().isAlive(); + } + + /** + * Restores the activator's "alive" state. + */ + @After + public void tearDown() { + Whitebox.setInternalState(PapActivator.getCurrent(), "alive", 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"); + final String resp = invocationBuilder.get(String.class); + + assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":")); + } + + /** + * Allocates a port for the server. + * + * @throws IOException if an error occurs + */ + private static void allocPort() throws IOException { + ServerSocket socket = new ServerSocket(); + socket.bind(new InetSocketAddress("localhost", 0)); + + port = socket.getLocalPort(); + socket.close(); + } + + /** + * Makes a parameter configuration file. + * + * @throws Exception if an error occurs + */ + private static void makeConfigFile() throws Exception { + Map<String, Object> params = new HashMap<>(); + params.put("host", "0.0.0.0"); + params.put("port", port); + params.put("userName", "healthcheck"); + params.put("password", "zb!XztG34"); + params.put("https", true); + + Map<String, Object> config = new HashMap<>(); + config.put("name", "PapGroup"); + config.put("restServerParameters", params); + + File file = new File("src/test/resources/parameters/TestConfigParams.json"); + file.deleteOnExit(); + + coder.encode(file, config); + } + + /** + * Starts the "Main". + * + * @throws Exception if an error occurs + */ + private static void startMain() throws Exception { + // 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); + + final String[] papConfigParameters = new String[2]; + papConfigParameters[0] = "-c"; + papConfigParameters[1] = "src/test/resources/parameters/TestConfigParams.json"; + + main = new Main(papConfigParameters); + + 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 PolicyPapException { + if (main != null) { + Main main2 = main; + main = null; + + main2.shutdown(); + } + } + + /** + * Mark the activator as dead, but leave its REST server running. + */ + protected void markActivatorDead() { + Whitebox.setInternalState(PapActivator.getCurrent(), "alive", false); + } + + /** + * 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); + } + + /** + * Sends a request to a fully qualified endpoint. + * + * @param endpoint the fully qualified target endpoint + * @return a request builder + * @throws Exception if an error occurs + */ + protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint) throws Exception { + + // @formatter:off + final TrustManager[] noopTrustManager = new TrustManager[] { + new X509TrustManager() { + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + @Override + public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, + final String authType) {} + + @Override + public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, + final String authType) {} + } + }; + // @formatter:on + + final SSLContext sc = SSLContext.getInstance("TLSv1.2"); + sc.init(null, noopTrustManager, new SecureRandom()); + final ClientBuilder clientBuilder = + ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); + final Client client = clientBuilder.build(); + 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/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java new file mode 100644 index 00000000..0ddfb3b5 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java @@ -0,0 +1,69 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ================================================================================ + * 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.pap.main.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 PapRestServer}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { + + 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); + } + + @Test + public void testHealthCheck_500() throws Exception { + + markActivatorDead(); + + final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); + final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); + validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report); + } + + 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/main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java deleted file mode 100644 index 77ac8f1e..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java +++ /dev/null @@ -1,290 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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.pap.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Properties; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -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 org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.After; -import org.junit.Test; -import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.pap.main.PolicyPapException; -import org.onap.policy.pap.main.parameters.CommonTestData; -import org.onap.policy.pap.main.parameters.RestServerParameters; -import org.onap.policy.pap.main.startstop.Main; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of {@link PapRestServer}. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestPapRestServer { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestPapRestServer.class); - private static final String NOT_ALIVE = "not alive"; - private static final String ALIVE = "alive"; - private static final String SELF = "self"; - private static final String NAME = "Policy PAP"; - private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; - private static final String STATISTICS_ENDPOINT = "statistics"; - private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; - private Main main; - private PapRestServer restServer; - - /** - * Method for cleanup after each test. - */ - @After - public void teardown() { - PapStatisticsManager.getInstance().resetAllStatistics(); - - try { - if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) { - if (main != null) { - stopPapService(main); - } else if (restServer != null) { - restServer.stop(); - } - } - } catch (InterruptedException | IOException | PolicyPapException exp) { - LOGGER.error("teardown failed", exp); - } - } - - @Test - public void testHealthCheckSuccess() { - try { - main = startPapService(true); - final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT); - final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); - validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); - } catch (final Exception exp) { - LOGGER.error("testHealthCheckSuccess failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testHealthCheckFailure() throws Exception { - final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); - restServerParams.setName(CommonTestData.PAP_GROUP_NAME); - restServer = new PapRestServer(restServerParams); - restServer.start(); - final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT); - final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); - validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report); - assertTrue(restServer.isAlive()); - assertTrue(restServer.toString().startsWith("PapRestServer [servers=")); - } - - @Test - public void testHttpsHealthCheckSuccess() { - try { - main = startPapService(false); - final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT); - final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); - validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); - } catch (final Exception exp) { - LOGGER.error("testHttpsHealthCheckSuccess failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testPapStatistics_200() { - try { - main = startPapService(true); - Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); - StatisticsReport report = invocationBuilder.get(StatisticsReport.class); - validateStatisticsReport(report, 0, 200); - updateDistributionStatistics(); - invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); - report = invocationBuilder.get(StatisticsReport.class); - validateStatisticsReport(report, 1, 200); - } catch (final Exception exp) { - LOGGER.error("testPapStatistics_200 failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testPapStatistics_500() { - final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); - restServerParams.setName(CommonTestData.PAP_GROUP_NAME); - restServer = new PapRestServer(restServerParams); - try { - restServer.start(); - final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); - final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); - validateStatisticsReport(report, 0, 500); - } catch (final Exception exp) { - LOGGER.error("testPapStatistics_500 failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testHttpsPapStatistic() { - try { - main = startPapService(false); - final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT); - final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); - validateStatisticsReport(report, 0, 200); - } catch (final Exception exp) { - LOGGER.error("testHttpsDistributionStatistic failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testPapStatisticsConstructorIsProtected() throws Exception { - final Constructor<PapStatisticsManager> constructor = PapStatisticsManager.class.getDeclaredConstructor(); - assertTrue(Modifier.isProtected(constructor.getModifiers())); - } - - private Main startPapService(final boolean http) { - final String[] papConfigParameters = new String[2]; - if (http) { - papConfigParameters[0] = "-c"; - papConfigParameters[1] = "parameters/PapConfigParameters.json"; - } else { - final Properties systemProps = System.getProperties(); - systemProps.put("javax.net.ssl.keyStore", KEYSTORE); - systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); - System.setProperties(systemProps); - papConfigParameters[0] = "-c"; - papConfigParameters[1] = "parameters/PapConfigParameters_Https.json"; - } - return new Main(papConfigParameters); - } - - private void stopPapService(final Main main) throws PolicyPapException { - main.shutdown(); - } - - private Invocation.Builder sendHttpRequest(final String endpoint) throws Exception { - final ClientConfig clientConfig = new ClientConfig(); - - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); - clientConfig.register(feature); - - final Client client = ClientBuilder.newClient(clientConfig); - final WebTarget webTarget = client.target("http://localhost:6969/policy/pap/v1/" + endpoint); - - final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - - if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { - throw new IllegalStateException("cannot connect to port 6969"); - } - return invocationBuilder; - } - - private Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception { - - final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() { - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {} - - @Override - public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {} - } }; - - final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); - final ClientBuilder clientBuilder = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, - session) -> true); - final Client client = clientBuilder.build(); - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); - client.register(feature); - - final WebTarget webTarget = client.target("https://localhost:6969/policy/pap/v1/" + endpoint); - - final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - - if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { - throw new IllegalStateException("cannot connect to port 6969"); - } - return invocationBuilder; - } - - private void updateDistributionStatistics() { - PapStatisticsManager mgr = PapStatisticsManager.getInstance(); - - mgr.updateTotalPdpCount(); - mgr.updateTotalPdpGroupCount(); - mgr.updateTotalPolicyDeployCount(); - mgr.updatePolicyDeploySuccessCount(); - mgr.updatePolicyDeployFailureCount(); - mgr.updateTotalPolicyDownloadCount(); - mgr.updatePolicyDownloadSuccessCount(); - mgr.updatePolicyDownloadFailureCount(); - } - - private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) { - assertEquals(code, report.getCode()); - assertEquals(count, report.getTotalPdpCount()); - assertEquals(count, report.getTotalPdpGroupCount()); - assertEquals(count, report.getTotalPolicyDeployCount()); - assertEquals(count, report.getPolicyDeploySuccessCount()); - assertEquals(count, report.getPolicyDeployFailureCount()); - assertEquals(count, report.getTotalPolicyDownloadCount()); - assertEquals(count, report.getPolicyDeploySuccessCount()); - assertEquals(count, report.getPolicyDeployFailureCount()); - } - - 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/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java new file mode 100644 index 00000000..de142b51 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ================================================================================ + * 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.pap.main.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import javax.ws.rs.client.Invocation; +import org.junit.Before; +import org.junit.Test; + +/** + * Class to perform unit test of {@link PapRestServer}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestStatisticsRestControllerV1 extends CommonPapRestServer { + + private static final String STATISTICS_ENDPOINT = "statistics"; + + /** + * Set up. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + super.setUp(); + + PapStatisticsManager.getInstance().resetAllStatistics(); + } + + @Test + public void testSwagger() throws Exception { + super.testSwagger(STATISTICS_ENDPOINT); + } + + @Test + public void testPapStatistics_200() throws Exception { + Invocation.Builder invocationBuilder = sendRequest(STATISTICS_ENDPOINT); + StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 200); + updateDistributionStatistics(); + + invocationBuilder = sendRequest(STATISTICS_ENDPOINT); + report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 1, 200); + } + + @Test + public void testPapStatistics_500() throws Exception { + + markActivatorDead(); + + PapStatisticsManager.getInstance().resetAllStatistics(); + + Invocation.Builder invocationBuilder = sendRequest(STATISTICS_ENDPOINT); + StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 500); + } + + @Test + public void testPapStatisticsConstructorIsProtected() throws Exception { + final Constructor<PapStatisticsManager> constructor = PapStatisticsManager.class.getDeclaredConstructor(); + assertTrue(Modifier.isProtected(constructor.getModifiers())); + } + + private void updateDistributionStatistics() { + PapStatisticsManager mgr = PapStatisticsManager.getInstance(); + + mgr.updateTotalPdpCount(); + mgr.updateTotalPdpGroupCount(); + mgr.updateTotalPolicyDeployCount(); + mgr.updatePolicyDeploySuccessCount(); + mgr.updatePolicyDeployFailureCount(); + mgr.updateTotalPolicyDownloadCount(); + mgr.updatePolicyDownloadSuccessCount(); + mgr.updatePolicyDownloadFailureCount(); + } + + private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) { + assertEquals(code, report.getCode()); + assertEquals(count, report.getTotalPdpCount()); + assertEquals(count, report.getTotalPdpGroupCount()); + assertEquals(count, report.getTotalPolicyDeployCount()); + assertEquals(count, report.getPolicyDeploySuccessCount()); + assertEquals(count, report.getPolicyDeployFailureCount()); + assertEquals(count, report.getTotalPolicyDownloadCount()); + assertEquals(count, report.getPolicyDeploySuccessCount()); + assertEquals(count, report.getPolicyDeployFailureCount()); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java index 8bc544b0..1f6b2baf 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java @@ -1,6 +1,7 @@ -/*- +/* * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.policy.pap.main.startstop; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import org.junit.After; import org.junit.Test; import org.onap.policy.pap.main.PolicyPapException; import org.onap.policy.pap.main.parameters.CommonTestData; @@ -33,40 +35,55 @@ import org.onap.policy.pap.main.parameters.CommonTestData; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ public class TestMain { + private Main main; + + /** + * Shuts "main" down. + * @throws Exception if an error occurs + */ + @After + public void tearDown() throws Exception { + // shut down activator + PapActivator activator = PapActivator.getCurrent(); + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } @Test public void testMain() throws PolicyPapException { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; - final Main main = new Main(papConfigParameters); + final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters.json"}; + main = new Main(papConfigParameters); assertTrue(main.getParameters().isValid()); assertEquals(CommonTestData.PAP_GROUP_NAME, main.getParameters().getName()); + main.shutdown(); } @Test public void testMain_NoArguments() { final String[] papConfigParameters = {}; - final Main main = new Main(papConfigParameters); + main = new Main(papConfigParameters); assertTrue(main.getParameters() == null); } @Test public void testMain_InvalidArguments() { - final String[] papConfigParameters = { "parameters/PapConfigParameters.json" }; - final Main main = new Main(papConfigParameters); + final String[] papConfigParameters = {"parameters/PapConfigParameters.json"}; + main = new Main(papConfigParameters); assertTrue(main.getParameters() == null); } @Test public void testMain_Help() { - final String[] papConfigParameters = { "-h" }; + final String[] papConfigParameters = {"-h"}; Main.main(papConfigParameters); } @Test public void testMain_InvalidParameters() { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters_InvalidName.json" }; - final Main main = new Main(papConfigParameters); + final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters_InvalidName.json"}; + main = new Main(papConfigParameters); assertTrue(main.getParameters() == null); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 8e8e6c09..5e611673 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -21,12 +21,11 @@ package org.onap.policy.pap.main.startstop; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import org.junit.After; import org.junit.Before; @@ -35,8 +34,6 @@ import org.onap.policy.pap.main.PolicyPapException; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PapParameterHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** @@ -46,7 +43,6 @@ import org.slf4j.LoggerFactory; */ public class TestPapActivator { - private static final Logger LOGGER = LoggerFactory.getLogger(TestPapActivator.class); private PapActivator activator; /** @@ -63,45 +59,43 @@ public class TestPapActivator { /** * Method for cleanup after each test. + * @throws Exception if an error occurs */ @After - public void teardown() { - try { - if (activator != null) { - activator.terminate(); - } - } catch (final PolicyPapException exp) { - LOGGER.error("teardown failed", exp); + public void teardown() throws Exception { + if (activator != null && activator.isAlive()) { + activator.terminate(); } } @Test public void testPapActivator() throws PolicyPapException { - try { - assertFalse(activator.isAlive()); - activator.initialize(); - assertTrue(activator.isAlive()); - assertTrue(activator.getParameterGroup().isValid()); - assertEquals(CommonTestData.PAP_GROUP_NAME, activator.getParameterGroup().getName()); - } catch (final Exception exp) { - LOGGER.error("testPapActivator failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test(expected = PolicyPapException.class) - public void testPapActivatorError() throws PolicyPapException { + assertFalse(activator.isAlive()); activator.initialize(); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameterGroup().isValid()); + assertEquals(CommonTestData.PAP_GROUP_NAME, activator.getParameterGroup().getName()); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.initialize()); + assertTrue(activator.isAlive()); assertTrue(activator.getParameterGroup().isValid()); - activator.initialize(); } @Test public void testGetCurrent_testSetCurrent() { - assertNotNull(PapActivator.getCurrent()); - PapActivator.setCurrent(activator); - assertSame(activator, PapActivator.getCurrent()); } + + @Test + public void testTerminate() throws Exception { + activator.initialize(); + activator.terminate(); + assertFalse(activator.isAlive()); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.terminate()); + assertFalse(activator.isAlive()); + } } diff --git a/main/src/test/resources/parameters/PapConfigParameters.json b/main/src/test/resources/parameters/PapConfigParameters.json index 7e415591..08d4f4a5 100644 --- a/main/src/test/resources/parameters/PapConfigParameters.json +++ b/main/src/test/resources/parameters/PapConfigParameters.json @@ -4,6 +4,7 @@ "host":"0.0.0.0", "port":6969, "userName":"healthcheck", - "password":"zb!XztG34" + "password":"zb!XztG34", + "https":true } } diff --git a/main/src/test/resources/parameters/PapConfigParameters_Https.json b/main/src/test/resources/parameters/PapConfigParameters_Https.json deleted file mode 100644 index 08d4f4a5..00000000 --- a/main/src/test/resources/parameters/PapConfigParameters_Https.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name":"PapGroup", - "restServerParameters":{ - "host":"0.0.0.0", - "port":6969, - "userName":"healthcheck", - "password":"zb!XztG34", - "https":true - } -} |