2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * Modifications Copyright (C) 2019 AT&T Intellectual Property.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.main.rest;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.lang.reflect.Constructor;
30 import java.lang.reflect.Modifier;
31 import java.security.SecureRandom;
32 import java.security.cert.X509Certificate;
33 import java.util.Properties;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.TrustManager;
37 import javax.net.ssl.X509TrustManager;
38 import javax.ws.rs.client.Client;
39 import javax.ws.rs.client.ClientBuilder;
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.client.WebTarget;
42 import javax.ws.rs.core.MediaType;
44 import org.glassfish.jersey.client.ClientConfig;
45 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
46 import org.junit.After;
47 import org.junit.Test;
48 import org.onap.policy.common.endpoints.report.HealthCheckReport;
49 import org.onap.policy.common.utils.network.NetworkUtil;
50 import org.onap.policy.pap.main.PolicyPapException;
51 import org.onap.policy.pap.main.parameters.CommonTestData;
52 import org.onap.policy.pap.main.parameters.RestServerParameters;
53 import org.onap.policy.pap.main.startstop.Main;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Class to perform unit test of {@link PapRestServer}.
60 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
62 public class TestPapRestServer {
64 private static final Logger LOGGER = LoggerFactory.getLogger(TestPapRestServer.class);
65 private static final String NOT_ALIVE = "not alive";
66 private static final String ALIVE = "alive";
67 private static final String SELF = "self";
68 private static final String NAME = "Policy PAP";
69 private static final String HEALTHCHECK_ENDPOINT = "healthcheck";
70 private static final String STATISTICS_ENDPOINT = "statistics";
71 private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
73 private PapRestServer restServer;
76 * Method for cleanup after each test.
79 public void teardown() {
80 PapStatisticsManager.getInstance().resetAllStatistics();
83 if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) {
86 } else if (restServer != null) {
90 } catch (InterruptedException | IOException | PolicyPapException exp) {
91 LOGGER.error("teardown failed", exp);
96 public void testHealthCheckSuccess() {
98 main = startPapService(true);
99 final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
100 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
101 validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
102 } catch (final Exception exp) {
103 LOGGER.error("testHealthCheckSuccess failed", exp);
104 fail("Test should not throw an exception");
109 public void testHealthCheckFailure() throws Exception {
110 final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
111 restServerParams.setName(CommonTestData.PAP_GROUP_NAME);
112 restServer = new PapRestServer(restServerParams);
114 final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
115 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
116 validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report);
117 assertTrue(restServer.isAlive());
118 assertTrue(restServer.toString().startsWith("PapRestServer [servers="));
122 public void testHttpsHealthCheckSuccess() {
124 main = startPapService(false);
125 final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
126 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
127 validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
128 } catch (final Exception exp) {
129 LOGGER.error("testHttpsHealthCheckSuccess failed", exp);
130 fail("Test should not throw an exception");
135 public void testPapStatistics_200() {
137 main = startPapService(true);
138 Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
139 StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
140 validateStatisticsReport(report, 0, 200);
141 updateDistributionStatistics();
142 invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
143 report = invocationBuilder.get(StatisticsReport.class);
144 validateStatisticsReport(report, 1, 200);
145 } catch (final Exception exp) {
146 LOGGER.error("testPapStatistics_200 failed", exp);
147 fail("Test should not throw an exception");
152 public void testPapStatistics_500() {
153 final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
154 restServerParams.setName(CommonTestData.PAP_GROUP_NAME);
155 restServer = new PapRestServer(restServerParams);
158 final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
159 final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
160 validateStatisticsReport(report, 0, 500);
161 } catch (final Exception exp) {
162 LOGGER.error("testPapStatistics_500 failed", exp);
163 fail("Test should not throw an exception");
168 public void testHttpsPapStatistic() {
170 main = startPapService(false);
171 final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
172 final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
173 validateStatisticsReport(report, 0, 200);
174 } catch (final Exception exp) {
175 LOGGER.error("testHttpsDistributionStatistic failed", exp);
176 fail("Test should not throw an exception");
181 public void testPapStatisticsConstructorIsProtected() throws Exception {
182 final Constructor<PapStatisticsManager> constructor = PapStatisticsManager.class.getDeclaredConstructor();
183 assertTrue(Modifier.isProtected(constructor.getModifiers()));
186 private Main startPapService(final boolean http) {
187 final String[] papConfigParameters = new String[2];
189 papConfigParameters[0] = "-c";
190 papConfigParameters[1] = "parameters/PapConfigParameters.json";
192 final Properties systemProps = System.getProperties();
193 systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
194 systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
195 System.setProperties(systemProps);
196 papConfigParameters[0] = "-c";
197 papConfigParameters[1] = "parameters/PapConfigParameters_Https.json";
199 return new Main(papConfigParameters);
202 private void stopPapService(final Main main) throws PolicyPapException {
206 private Invocation.Builder sendHttpRequest(final String endpoint) throws Exception {
207 final ClientConfig clientConfig = new ClientConfig();
209 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
210 clientConfig.register(feature);
212 final Client client = ClientBuilder.newClient(clientConfig);
213 final WebTarget webTarget = client.target("http://localhost:6969/policy/pap/v1/" + endpoint);
215 final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
217 if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
218 throw new IllegalStateException("cannot connect to port 6969");
220 return invocationBuilder;
223 private Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
225 final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() {
228 public X509Certificate[] getAcceptedIssuers() {
229 return new X509Certificate[0];
233 public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
236 public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
239 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
240 sc.init(null, noopTrustManager, new SecureRandom());
241 final ClientBuilder clientBuilder = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host,
243 final Client client = clientBuilder.build();
244 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
245 client.register(feature);
247 final WebTarget webTarget = client.target("https://localhost:6969/policy/pap/v1/" + endpoint);
249 final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
251 if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
252 throw new IllegalStateException("cannot connect to port 6969");
254 return invocationBuilder;
257 private void updateDistributionStatistics() {
258 PapStatisticsManager mgr = PapStatisticsManager.getInstance();
260 mgr.updateTotalPdpCount();
261 mgr.updateTotalPdpGroupCount();
262 mgr.updateTotalPolicyDeployCount();
263 mgr.updatePolicyDeploySuccessCount();
264 mgr.updatePolicyDeployFailureCount();
265 mgr.updateTotalPolicyDownloadCount();
266 mgr.updatePolicyDownloadSuccessCount();
267 mgr.updatePolicyDownloadFailureCount();
270 private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) {
271 assertEquals(code, report.getCode());
272 assertEquals(count, report.getTotalPdpCount());
273 assertEquals(count, report.getTotalPdpGroupCount());
274 assertEquals(count, report.getTotalPolicyDeployCount());
275 assertEquals(count, report.getPolicyDeploySuccessCount());
276 assertEquals(count, report.getPolicyDeployFailureCount());
277 assertEquals(count, report.getTotalPolicyDownloadCount());
278 assertEquals(count, report.getPolicyDeploySuccessCount());
279 assertEquals(count, report.getPolicyDeployFailureCount());
282 private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
283 final String message, final HealthCheckReport report) {
284 assertEquals(name, report.getName());
285 assertEquals(url, report.getUrl());
286 assertEquals(healthy, report.isHealthy());
287 assertEquals(code, report.getCode());
288 assertEquals(message, report.getMessage());