aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'main/src/test/java')
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java216
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java17
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java251
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java123
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java72
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java40
6 files changed, 355 insertions, 364 deletions
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java
new file mode 100644
index 00000000..0c84419f
--- /dev/null
+++ b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java
@@ -0,0 +1,216 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pdpx.main;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.SecureRandom;
+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 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.network.NetworkUtil;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
+import org.onap.policy.pdpx.main.startstop.Main;
+import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
+import org.powermock.reflect.Whitebox;
+
+/**
+ * Common base class for REST service tests.
+ */
+public class CommonRest {
+ private static final String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
+
+ /**
+ * Full path to the config file.
+ */
+ public static final String CONFIG_FILE;
+
+ /**
+ * Path corresponding to {@link #CONFIG_FILE}.
+ */
+ private static final Path CONFIG_PATH;
+
+ /**
+ * Contents read from the "standard" config file, which still contains ${xxx}
+ * place-holders.
+ */
+ private static final String STD_CONFIG;
+
+ /**
+ * Port that was last allocated for the server.
+ */
+ protected static int port;
+
+ /**
+ * "Main" that was last started.
+ */
+ private static Main main;
+
+ /**
+ * Records the "alive" state of the activator while it's temporarily updated by
+ * various junit tests. The {@link #tearDown()} method restores the "alive" state back
+ * to this value.
+ */
+ private boolean activatorWasAlive;
+
+ static {
+ try {
+ File file = new File(ResourceUtils.getFilePath4Resource("parameters/XacmlPdpConfigParameters_Std.json"));
+ STD_CONFIG = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+
+ file = new File(file.getParentFile(), "Test_XacmlPdpConfigParameters.json");
+ file.deleteOnExit();
+
+ CONFIG_FILE = file.getAbsolutePath();
+ CONFIG_PATH = new File(CONFIG_FILE).toPath();
+
+ } catch (IOException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ /**
+ * Configures system properties and creates a JSON config file.
+ *
+ * @throws Exception if an error occurs
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
+ System.setProperty("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
+
+ System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
+ System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
+
+ writeJsonConfig();
+
+ final String[] xacmlPdpConfigParameters = {"-c", CommonRest.CONFIG_FILE, "-p", "parameters/topic.properties"};
+ main = new Main(xacmlPdpConfigParameters);
+
+ if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
+ throw new IllegalStateException("server is not listening on port " + port);
+ }
+ }
+
+ /**
+ * Stops the "Main".
+ */
+ @AfterClass
+ public static void tearDownAfterClass() {
+ stopMain();
+ }
+
+ /**
+ * Resets the statistics.
+ */
+ @Before
+ public void setUp() {
+ activatorWasAlive = XacmlPdpActivator.getCurrent().isAlive();
+ XacmlPdpStatisticsManager.getCurrent().resetAllStatistics();
+ }
+
+ /**
+ * Restores the "alive" status of the activator.
+ */
+ @After
+ public void tearDown() {
+ markActivator(activatorWasAlive);
+ }
+
+ /**
+ * Stops the "main".
+ */
+ protected static void stopMain() {
+ main.shutdown();
+ }
+
+ /**
+ * Writes a JSON config file, substituting an allocated port number for occurrences of
+ * "${port}".
+ *
+ * @return the allocated server port
+ * @throws IOException if the config file cannot be created
+ */
+ public static int writeJsonConfig() throws IOException {
+ port = NetworkUtil.allocPort();
+
+ String config = STD_CONFIG.replace("${port}", String.valueOf(port));
+ Files.write(CONFIG_PATH, config.getBytes(StandardCharsets.UTF_8));
+
+ return port;
+ }
+
+ /**
+ * Sends an HTTPS request to an endpoint of the PDP's REST API.
+ *
+ * @param endpoint target endpoint
+ * @return a request builder
+ * @throws Exception if an error occurs
+ */
+ protected Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
+ // always trust the certificate
+ final SSLContext sc = SSLContext.getInstance("TLSv1.2");
+ sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
+
+ // always trust the host name
+ 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:" + port + "/policy/pdpx/v1/" + endpoint);
+
+ return webTarget.request(MediaType.APPLICATION_JSON);
+ }
+
+ /**
+ * Mark the activator as dead, but leave its REST server running.
+ */
+ protected void markActivatorDead() {
+ markActivator(false);
+ }
+
+ /**
+ * Changes the internal "alive" status of the activator to a new value.
+ *
+ * @param newAlive the new "alive" status
+ */
+ private void markActivator(boolean newAlive) {
+ Object manager = Whitebox.getInternalState(XacmlPdpActivator.getCurrent(), "serviceManager");
+ Whitebox.setInternalState(manager, "running", newAlive);
+ }
+}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
index 3a1e98b1..5f7eb78c 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
@@ -67,6 +67,7 @@ public class TestDecision {
private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
+ private static int port;
private static Main main;
private static HttpClient client;
@@ -82,6 +83,9 @@ public class TestDecision {
public static void beforeClass() throws Exception {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
+
+ port = NetworkUtil.allocPort();
+
//
// Copy test directory over of the application directories
//
@@ -94,7 +98,7 @@ public class TestDecision {
// Get the parameters file correct.
//
RestServerParameters rest = new RestServerParameters(new RestServerBuilder()
- .setHost("0.0.0.0").setPort(6969).setUserName("healthcheck").setPassword("zb!XztG34"));
+ .setHost("0.0.0.0").setPort(port).setUserName("healthcheck").setPassword("zb!XztG34"));
XacmlPdpParameterGroup params = new XacmlPdpParameterGroup("XacmlPdpGroup", rest, apps.getAbsolutePath());
final Gson gson = new GsonBuilder().create();
File fileParams = appsFolder.newFile("params.json");
@@ -108,8 +112,8 @@ public class TestDecision {
//
// Make sure it is running
//
- if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
- throw new IllegalStateException("Cannot connect to port 6969");
+ if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
+ throw new IllegalStateException("Cannot connect to port " + port);
}
//
// Create a client
@@ -123,8 +127,7 @@ public class TestDecision {
}
@Test
- public void testDecision_UnsupportedAction() throws KeyManagementException, NoSuchAlgorithmException,
- ClassNotFoundException {
+ public void testDecision_UnsupportedAction() throws Exception {
LOGGER.info("Running test testDecision_UnsupportedAction");
@@ -165,7 +168,7 @@ public class TestDecision {
assertThat(response.getStatus()).isEqualTo("Permit");
}
- private static Main startXacmlPdpService(File params) {
+ private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath(), "-p",
"parameters/topic.properties"};
return new Main(XacmlPdpConfigParameters);
@@ -200,7 +203,7 @@ public class TestDecision {
return HttpClient.factory.build(BusTopicParams.builder()
.clientName("testDecisionClient")
.serializationProvider(GsonMessageBodyHandler.class.getName())
- .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(6969)
+ .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
.basePath("policy/pdpx/v1/decision")
.userName("healthcheck").password("zb!XztG34").managed(true).build());
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
index f9f2abf3..ba8f0044 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
@@ -21,41 +21,12 @@
package org.onap.policy.pdpx.main.rest;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import java.io.File;
-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.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
-import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
import org.onap.policy.common.endpoints.report.HealthCheckReport;
-import org.onap.policy.common.utils.network.NetworkUtil;
-import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
-import org.onap.policy.pdpx.main.parameters.CommonTestData;
-import org.onap.policy.pdpx.main.parameters.RestServerParameters;
+import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.rest.model.StatisticsReport;
-import org.onap.policy.pdpx.main.startstop.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -63,8 +34,7 @@ import org.slf4j.LoggerFactory;
* Class to perform unit test of {@link XacmlPdpRestServer}.
*
*/
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class TestXacmlPdpRestServer {
+public class TestXacmlPdpRestServer extends CommonRest {
private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpRestServer.class);
private static final String NOT_ALIVE = "not alive";
@@ -73,224 +43,79 @@ public class TestXacmlPdpRestServer {
private static final String NAME = "Policy Xacml PDP";
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 XacmlPdpRestServer restServer;
- private static File applicationPath;
-
- @ClassRule
- public static final TemporaryFolder applicationFolder = new TemporaryFolder();
-
- /**
- * setup.
- *
- * @throws IOException exception if cannot create temporary folder
- */
- @BeforeClass
- public static void setUp() throws IOException {
- System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
- System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
- applicationPath = applicationFolder.newFolder();
- }
-
- /**
- * Method for cleanup after each test.
- */
- @After
- public void teardown() {
- try {
- if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) {
- if (main != null) {
- stopXacmlPdpService(main);
- main = null;
- }
-
- if (restServer != null) {
- restServer.stop();
- restServer = null;
- }
- }
- } catch (IOException | PolicyXacmlPdpException e) {
- LOGGER.error("teardown failed", e);
- } catch (InterruptedException ie) {
- Thread.interrupted();
- LOGGER.error("teardown failed", ie);
- }
- }
@Test
- public void test1HealthCheckSuccess() throws IOException, InterruptedException, TopicSinkClientException {
- LOGGER.info("***************************** Running test1HealthCheckSuccess *****************************");
- main = startXacmlPdpService(true);
- final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
+ public void testHealthCheckSuccess() throws Exception {
+ LOGGER.info("***************************** Running testHealthCheckSuccess *****************************");
+ final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
LOGGER.info("test1HealthCheckSuccess health report {}", report);
validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
}
@Test
- public void test7HealthCheckFailure() throws InterruptedException, IOException {
- LOGGER.info("***************************** Running test7HealthCheckFailure *****************************");
- final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
- restServerParams.setName(CommonTestData.PDPX_GROUP_NAME);
- restServer = new XacmlPdpRestServer(restServerParams, applicationPath.getAbsolutePath());
- restServer.start();
- final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
+ public void testHealthCheckFailure() throws Exception {
+ LOGGER.info("***************************** Running testHealthCheckFailure *****************************");
+
+ markActivatorDead();
+
+ final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
- LOGGER.info("test7HealthCheckFailure health report {}", report);
+ LOGGER.info("testHealthCheckFailure health report {}", report);
validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report);
- assertTrue(restServer.isAlive());
- assertTrue(restServer.toString().startsWith("XacmlPdpRestServer [servers="));
}
@Test
- public void test2HttpsHealthCheckSuccess() throws Exception {
- LOGGER.info("**************************** Running test2HttpsHealthCheckSuccess ****************************");
- main = startXacmlPdpService(false);
+ public void testHttpsHealthCheckSuccess() throws Exception {
+ LOGGER.info("***************************** Running testHttpsHealthCheckSuccess *****************************");
final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
- LOGGER.info("test2HttpsHealthCheckSuccess health report {}", report);
+ LOGGER.info("testHttpsHealthCheckSuccess health report {}", report);
validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
}
@Test
- public void test4Statistics_200() throws IOException, InterruptedException, TopicSinkClientException {
- LOGGER.info("***************************** Running test4Statistics_200 *****************************");
- XacmlPdpStatisticsManager.resetAllStatistics();
- main = startXacmlPdpService(true);
- Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
+ public void testStatistics_200() throws Exception {
+ LOGGER.info("***************************** Running testStatistics_200 *****************************");
+ Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
- LOGGER.info("test4Statistics_200 health report {}", report);
+ LOGGER.info("testStatistics_200 health report {}", report);
validateStatisticsReport(report, 0, 200);
updateXacmlPdpStatistics();
- invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
+ invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
report = invocationBuilder.get(StatisticsReport.class);
- LOGGER.info("test4Statistics_200 health report {}", report);
+ LOGGER.info("testStatistics_200 health report {}", report);
validateStatisticsReport(report, 1, 200);
- XacmlPdpStatisticsManager.resetAllStatistics();
}
@Test
- public void test5Statistics_500() throws IOException, InterruptedException {
- LOGGER.info("***************************** Running test5Statistics_500 *****************************");
- final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
- restServerParams.setName(CommonTestData.PDPX_GROUP_NAME);
- restServer = new XacmlPdpRestServer(restServerParams, applicationPath.getAbsolutePath());
- restServer.start();
- final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
+ public void testStatistics_500() throws Exception {
+ LOGGER.info("***************************** Running testStatistics_500 *****************************");
+
+ markActivatorDead();
+
+ final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
- LOGGER.info("test5Statistics_500 health report {}", report);
+ LOGGER.info("testStatistics_500 health report {}", report);
validateStatisticsReport(report, 0, 500);
- XacmlPdpStatisticsManager.resetAllStatistics();
}
@Test
- public void test6HttpsStatistic() throws Exception {
- LOGGER.info("***************************** Running test6HttpsStatistic *****************************");
- main = startXacmlPdpService(false);
+ public void testHttpsStatistic() throws Exception {
+ LOGGER.info("***************************** Running testHttpsStatistic *****************************");
final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
- LOGGER.info("test6HttpsStatistic health report {}", report);
+ LOGGER.info("testHttpsStatistic health report {}", report);
validateStatisticsReport(report, 0, 200);
}
- @Test
- public void test3StatisticsConstructorIsPrivate() {
- LOGGER.info("************************* Running test3StatisticsConstructorIsPrivate *************************");
- try {
- final Constructor<XacmlPdpStatisticsManager> constructor =
- XacmlPdpStatisticsManager.class.getDeclaredConstructor();
- assertTrue(Modifier.isPrivate(constructor.getModifiers()));
- constructor.setAccessible(true);
- constructor.newInstance();
- fail("Expected an InstantiationException to be thrown");
- } catch (final Exception exp) {
- assertTrue(exp.getCause().toString().contains("Instantiation of the class is not allowed"));
- }
- }
-
- private Main startXacmlPdpService(final boolean http) throws TopicSinkClientException {
- final String[] xacmlPdpConfigParameters = new String[4];
- if (http) {
- xacmlPdpConfigParameters[0] = "-c";
- xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters.json";
- xacmlPdpConfigParameters[2] = "-p";
- xacmlPdpConfigParameters[3] = "parameters/topic.properties";
- } else {
- final Properties systemProps = System.getProperties();
- systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
- systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
- System.setProperties(systemProps);
- xacmlPdpConfigParameters[0] = "-c";
- xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_Https.json";
- xacmlPdpConfigParameters[2] = "-p";
- xacmlPdpConfigParameters[3] = "parameters/topic.properties";
- }
- return new Main(xacmlPdpConfigParameters);
- }
-
- private void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
- main.shutdown();
- }
-
- private Invocation.Builder sendHttpRequest(final String endpoint) throws IOException, InterruptedException {
- 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/pdpx/v1/" + endpoint);
-
- final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
-
- if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
- 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/pdpx/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 updateXacmlPdpStatistics() {
- XacmlPdpStatisticsManager.updateTotalPoliciesCount();
- XacmlPdpStatisticsManager.updatePermitDecisionsCount();
- XacmlPdpStatisticsManager.updateDenyDecisionsCount();
- XacmlPdpStatisticsManager.updateIndeterminantDecisionsCount();
- XacmlPdpStatisticsManager.updateNotApplicableDecisionsCount();
+ XacmlPdpStatisticsManager stats = XacmlPdpStatisticsManager.getCurrent();
+ stats.updateTotalPoliciesCount();
+ stats.updatePermitDecisionsCount();
+ stats.updateDenyDecisionsCount();
+ stats.updateIndeterminantDecisionsCount();
+ stats.updateNotApplicableDecisionsCount();
}
private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) {
@@ -303,7 +128,7 @@ public class TestXacmlPdpRestServer {
}
private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
- final String message, final HealthCheckReport report) {
+ final String message, final HealthCheckReport report) {
assertEquals(name, report.getName());
assertEquals(url, report.getUrl());
assertEquals(healthy, report.isHealthy());
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
index 6a762924..250f21e6 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
@@ -21,31 +21,11 @@
package org.onap.policy.pdpx.main.rest;
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import java.io.File;
-import java.io.IOException;
-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.BeforeClass;
-import org.junit.ClassRule;
import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
-import org.onap.policy.common.utils.network.NetworkUtil;
-import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
-import org.onap.policy.pdpx.main.parameters.CommonTestData;
-import org.onap.policy.pdpx.main.parameters.RestServerParameters;
-import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
+import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.rest.model.StatisticsReport;
-import org.onap.policy.pdpx.main.startstop.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -53,101 +33,42 @@ import org.slf4j.LoggerFactory;
* Class to perform unit test of {@link XacmlPdpRestController}.
*
*/
-public class TestXacmlPdpStatistics {
+public class TestXacmlPdpStatistics extends CommonRest {
private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpStatistics.class);
- private static File applicationPath;
-
- @ClassRule
- public static final TemporaryFolder applicationFolder = new TemporaryFolder();
-
- /**
- * Turn off some debugging and create temporary folder for applications.
- *
- * @throws IOException If temporary folder fails
- */
- @BeforeClass
- public static void beforeClass() throws IOException {
- System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
- System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
- applicationPath = applicationFolder.newFolder();
- }
@Test
- public void testXacmlPdpStatistics_200() throws PolicyXacmlPdpException, InterruptedException {
- try {
- LOGGER.info("*************************** Running testXacmlPdpStatistics_200 ***************************");
- final Main main = startXacmlPdpService();
- StatisticsReport report = getXacmlPdpStatistics();
- validateReport(report, 0, 200);
- assertThat(report.getTotalPolicyTypesCount()).isGreaterThan(0);
- updateXacmlPdpStatistics();
- report = getXacmlPdpStatistics();
- validateReport(report, 1, 200);
- stopXacmlPdpService(main);
- XacmlPdpStatisticsManager.resetAllStatistics();
- } catch (final Exception e) {
- LOGGER.error("testApiStatistics_200 failed", e);
- fail("Test should not throw an exception");
- }
+ public void testXacmlPdpStatistics_200() throws Exception {
+ LOGGER.info("*************************** Running testXacmlPdpStatistics_200 ***************************");
+ StatisticsReport report = getXacmlPdpStatistics();
+ validateReport(report, 0, 200);
+ updateXacmlPdpStatistics();
+ report = getXacmlPdpStatistics();
+ validateReport(report, 1, 200);
}
@Test
- public void testXacmlPdpStatistics_500() throws InterruptedException {
+ public void testXacmlPdpStatistics_500() throws Exception {
LOGGER.info("***************************** Running testXacmlPdpStatistics_500 *****************************");
- final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
- restServerParams.setName(CommonTestData.PDPX_GROUP_NAME);
- final XacmlPdpRestServer restServer = new XacmlPdpRestServer(restServerParams,
- applicationPath.getAbsolutePath());
- try {
- restServer.start();
- final StatisticsReport report = getXacmlPdpStatistics();
- validateReport(report, 0, 500);
- restServer.shutdown();
- XacmlPdpStatisticsManager.resetAllStatistics();
- } catch (final Exception e) {
- LOGGER.error("testApiStatistics_500 failed", e);
- fail("Test should not throw an exception");
- }
- }
-
-
- private Main startXacmlPdpService() throws TopicSinkClientException {
- final String[] XacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json", "-p",
- "parameters/topic.properties"};
- return new Main(XacmlPdpConfigParameters);
- }
+ markActivatorDead();
- private void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
- main.shutdown();
+ final StatisticsReport report = getXacmlPdpStatistics();
+ validateReport(report, 0, 500);
}
- private StatisticsReport getXacmlPdpStatistics() throws InterruptedException, IOException {
-
- 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/pdpx/v1/statistics");
-
- final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
-
- if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
- throw new IllegalStateException("Cannot connect to port 6969");
- }
-
- return invocationBuilder.get(StatisticsReport.class);
+ private StatisticsReport getXacmlPdpStatistics() throws Exception {
+ return sendHttpsRequest("statistics").get(StatisticsReport.class);
}
private void updateXacmlPdpStatistics() {
- XacmlPdpStatisticsManager.updateTotalPoliciesCount();
- XacmlPdpStatisticsManager.updatePermitDecisionsCount();
- XacmlPdpStatisticsManager.updateDenyDecisionsCount();
- XacmlPdpStatisticsManager.updateIndeterminantDecisionsCount();
- XacmlPdpStatisticsManager.updateNotApplicableDecisionsCount();
+ XacmlPdpStatisticsManager stats = XacmlPdpStatisticsManager.getCurrent();
+
+ stats.updateTotalPoliciesCount();
+ stats.updatePermitDecisionsCount();
+ stats.updateDenyDecisionsCount();
+ stats.updateIndeterminantDecisionsCount();
+ stats.updateNotApplicableDecisionsCount();
}
private void validateReport(final StatisticsReport report, final int count, final int code) {
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
index 80ee95f6..e8448ab2 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
@@ -20,70 +20,84 @@
package org.onap.policy.pdpx.main.startstop;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.junit.After;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
+import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
-import org.onap.policy.pdpx.main.parameters.CommonTestData;
/**
* Class to perform unit test of Main.
*
*/
-public class TestMain {
+public class TestMain extends CommonRest {
+
+ private Main main;
/**
- * setup.
+ * Sets up properties and configuration.
+ * @throws Exception if an error occurs
*/
@BeforeClass
- public static void setUp() {
- System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
- System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
+ public static void setUpBeforeClass() throws Exception {
+ CommonRest.setUpBeforeClass();
+
+ // don't want the common "main" running
+ CommonRest.stopMain();
+ }
+
+ @Before
+ public void setUp() {
+ main = null;
+ }
+ /**
+ * Shuts "main" down.
+ */
+ @After
+ public void tearDown() {
+ if (main != null) {
+ main.shutdown();
+ }
}
@Test
- public void testMain() throws PolicyXacmlPdpException, TopicSinkClientException {
- final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"};
- final Main main = new Main(xacmlPdpConfigParameters);
- assertTrue(main.getParameters().isValid());
- assertEquals(CommonTestData.PDPX_GROUP_NAME, main.getParameters().getName());
+ public void testMain() throws PolicyXacmlPdpException {
+ final String[] xacmlPdpConfigParameters = {"-c", CONFIG_FILE, "-p", "parameters/topic.properties"};
+ main = new Main(xacmlPdpConfigParameters);
main.shutdown();
+ main = null;
}
@Test
- public void testMain_NoArguments() throws PolicyXacmlPdpException, TopicSinkClientException {
+ public void testMain_NoArguments() {
final String[] xacmlPdpConfigParameters = {};
- final Main main = new Main(xacmlPdpConfigParameters);
- assertNull(main.getParameters());
- main.shutdown();
+ assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
+ .hasMessage("policy xacml pdp configuration file was not specified as an argument");
}
@Test
- public void testMain_InvalidArguments() throws TopicSinkClientException {
+ public void testMain_InvalidArguments() {
final String[] xacmlPdpConfigParameters = {"parameters/XacmlPdpConfigParameters.json"};
- final Main main = new Main(xacmlPdpConfigParameters);
- assertNull(main.getParameters());
+ assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
+ .hasMessage("too many command line arguments specified : [parameters/XacmlPdpConfigParameters.json]");
}
@Test
- public void testMain_Help() throws TopicSinkClientException {
+ public void testMain_Help() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-h"};
- final Main main = new Main(xacmlPdpConfigParameters);
- final String message = "-h,--help outputs the usage of this command";
- Assert.assertTrue(main.getArgumentMessage().contains(message));
+ Assert.assertTrue(new Main(xacmlPdpConfigParameters).getArgumentMessage().contains("-h,--help"));
}
@Test
- public void testMain_InvalidParameters() throws TopicSinkClientException {
+ public void testMain_InvalidParameters() {
final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"};
- final Main main = new Main(xacmlPdpConfigParameters);
- assertNull(main.getParameters());
+ assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
+ .hasMessageContaining("validation error");
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
index 5930dd5e..b60f4589 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
@@ -26,13 +26,12 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.FileInputStream;
-import java.net.UnknownHostException;
import java.util.Properties;
-
import org.junit.After;
+import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
+import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
import org.onap.policy.pdpx.main.parameters.CommonTestData;
import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
@@ -43,30 +42,44 @@ import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterHandler;
* Class to perform unit test of XacmlPdpActivator.
*
*/
-public class TestXacmlPdpActivator {
- private static XacmlPdpActivator activator = null;
+public class TestXacmlPdpActivator extends CommonRest {
+ private static XacmlPdpParameterGroup parGroup;
+ private static Properties props;
+
+ private XacmlPdpActivator activator = null;
/**
- * Setup the tests.
+ * Loads properties.
*/
@BeforeClass
- public static void setup() throws Exception {
+ public static void setUpBeforeClass() throws Exception {
+ CommonRest.setUpBeforeClass();
+
final String[] xacmlPdpConfigParameters =
- {"-c", "parameters/XacmlPdpConfigParameters.json", "-p", "parameters/topic.properties"};
+ {"-c", CommonRest.CONFIG_FILE, "-p", "parameters/topic.properties"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(xacmlPdpConfigParameters);
- final XacmlPdpParameterGroup parGroup = new XacmlPdpParameterHandler().getParameters(arguments);
+ parGroup = new XacmlPdpParameterHandler().getParameters(arguments);
- Properties props = new Properties();
+ props = new Properties();
String propFile = arguments.getFullPropertyFilePath();
try (FileInputStream stream = new FileInputStream(propFile)) {
props.load(stream);
}
+ // don't want the common "main" running
+ CommonRest.stopMain();
+ }
+
+ /**
+ * Creates the activator.
+ */
+ @Before
+ public void setUp() {
activator = new XacmlPdpActivator(parGroup, props);
}
@Test
- public void testXacmlPdpActivator() throws PolicyXacmlPdpException, TopicSinkClientException, UnknownHostException {
+ public void testXacmlPdpActivator() throws Exception {
assertFalse(activator.isAlive());
activator.start();
assertTrue(activator.isAlive());
@@ -77,14 +90,13 @@ public class TestXacmlPdpActivator {
@Test
public void testGetCurrent_testSetCurrent() {
+ XacmlPdpActivator.setCurrent(activator);
assertSame(activator, XacmlPdpActivator.getCurrent());
}
@Test
public void testTerminate() throws Exception {
- if (!activator.isAlive()) {
- activator.start();
- }
+ activator.start();
activator.stop();
assertFalse(activator.isAlive());
}