diff options
author | Chenfei Gao <cgao@research.att.com> | 2019-02-18 16:28:54 -0500 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2019-02-27 11:58:53 +0000 |
commit | 0c117e6f8608ed902893364ee00123b0eb9f4a59 (patch) | |
tree | 9ee34faca705be2d3d6af840dafc52b314f67034 /main/src/test/java | |
parent | 8df02c884233f8842272ed69cb2c580a00d3df1d (diff) |
Add more endpoints and swagger annotations
Includes:
a) Organized swagger models into new rest.model package
b) Organized provider classes into new rest.provider package
c) Added policyType GET/POST/DELETE endpoints
d) Added policy GET/POST/DELETE endpoints
e) Added swagger annotations for the new endpoints
Issue-ID: POLICY-1515
Change-Id: Ia159a4cfebdad36cb1b4a5cc6456d07d2fde09ee
Signed-off-by: Chenfei Gao <cgao@research.att.com>
Diffstat (limited to 'main/src/test/java')
5 files changed, 213 insertions, 463 deletions
diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java index 1ea42e0e..3c8b251d 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java @@ -26,7 +26,15 @@ 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; @@ -35,6 +43,7 @@ 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.api.main.exception.PolicyApiException; import org.onap.policy.api.main.parameters.CommonTestData; @@ -46,8 +55,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Class to perform unit test of HealthCheckMonitor. + * Class to perform unit test of {@link ApiRestServer}. * + * @author Chenfei Gao (cgao@research.att.com) */ public class TestApiRestServer { @@ -56,15 +66,37 @@ public class TestApiRestServer { private static final String ALIVE = "alive"; private static final String SELF = "self"; private static final String NAME = "Policy API"; + 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 ApiRestServer restServer; + + /** + * Method for cleanup after each test. + */ + @After + public void teardown() { + try { + if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) { + if (main != null) { + stopApiService(main); + } else if (restServer != null) { + restServer.stop(); + } + } + } catch (InterruptedException | IOException | PolicyApiException exp) { + LOGGER.error("teardown failed", exp); + } + } @Test - public void testHealthCheckSuccess() throws PolicyApiException, InterruptedException { - final String reportString = "Report [name=Policy API, url=self, healthy=true, code=200, message=alive]"; + public void testHealthCheckSuccess() { try { - final Main main = startApiService(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); - stopApiService(main); + main = startApiService(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"); @@ -72,26 +104,109 @@ public class TestApiRestServer { } @Test - public void testHealthCheckFailure() throws InterruptedException { - final String reportString = "Report [name=Policy API, url=self, healthy=false, code=500, message=not alive]"; + public void testHealthCheckFailure() throws InterruptedException, IOException { final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); restServerParams.setName(CommonTestData.API_GROUP_NAME); - final ApiRestServer restServer = new ApiRestServer(restServerParams); + restServer = new ApiRestServer(restServerParams); try { restServer.start(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, report); + 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("ApiRestServer [servers=")); - restServer.shutdown(); } catch (final Exception exp) { LOGGER.error("testHealthCheckFailure failed", exp); fail("Test should not throw an exception"); } } - private Main startApiService() { - final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; + @Test + public void testHttpsHealthCheckSuccess() { + try { + main = startApiService(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 testApiStatistics_200() { + try { + main = startApiService(true); + Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 200); + updateApiStatistics(); + invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 1, 200); + ApiStatisticsManager.resetAllStatistics(); + } catch (final Exception exp) { + LOGGER.error("testApiStatistics_200 failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testApiStatistics_500() { + final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); + restServerParams.setName(CommonTestData.API_GROUP_NAME); + restServer = new ApiRestServer(restServerParams); + try { + restServer.start(); + final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 500); + ApiStatisticsManager.resetAllStatistics(); + } catch (final Exception exp) { + LOGGER.error("testApiStatistics_500 failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testHttpsApiStatistics() { + try { + main = startApiService(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("testHttpsApiStatistics failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testApiStatisticsConstructorIsPrivate() { + try { + final Constructor<ApiStatisticsManager> constructor = ApiStatisticsManager.class.getDeclaredConstructor(); + assertTrue(Modifier.isPrivate(constructor.getModifiers())); + constructor.setAccessible(true); + constructor.newInstance(); + } catch (final Exception exp) { + assertTrue(exp.getCause().toString().contains("Instantiation of the class is not allowed")); + } + } + + private Main startApiService(final boolean http) { + final String[] apiConfigParameters = new String[2]; + if (http) { + apiConfigParameters[0] = "-c"; + apiConfigParameters[1] = "parameters/ApiConfigParameters.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); + apiConfigParameters[0] = "-c"; + apiConfigParameters[1] = "parameters/ApiConfigParameters_Https.json"; + } return new Main(apiConfigParameters); } @@ -99,30 +214,100 @@ public class TestApiRestServer { main.shutdown(); } - private HealthCheckReport performHealthCheck() throws InterruptedException, IOException { + 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/healthcheck"); + final WebTarget webTarget = client.target("http://localhost:6969/policy/api/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.get(HealthCheckReport.class); + 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/api/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 updateApiStatistics() { + ApiStatisticsManager.updateTotalApiCallCount(); + ApiStatisticsManager.updateApiCallSuccessCount(); + ApiStatisticsManager.updateApiCallFailureCount(); + ApiStatisticsManager.updateTotalPolicyGetCount(); + ApiStatisticsManager.updateTotalPolicyPostCount(); + ApiStatisticsManager.updateTotalPolicyTypeGetCount(); + ApiStatisticsManager.updateTotalPolicyTypePostCount(); + ApiStatisticsManager.updatePolicyGetSuccessCount(); + ApiStatisticsManager.updatePolicyGetFailureCount(); + ApiStatisticsManager.updatePolicyPostSuccessCount(); + ApiStatisticsManager.updatePolicyPostFailureCount(); + ApiStatisticsManager.updatePolicyTypeGetSuccessCount(); + ApiStatisticsManager.updatePolicyTypeGetFailureCount(); + ApiStatisticsManager.updatePolicyTypePostSuccessCount(); + ApiStatisticsManager.updatePolicyTypePostFailureCount(); + } + + private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) { + assertEquals(code, report.getCode()); + assertEquals(count, report.getTotalApiCallCount()); + assertEquals(count, report.getApiCallSuccessCount()); + assertEquals(count, report.getApiCallFailureCount()); + assertEquals(count, report.getTotalPolicyGetCount()); + assertEquals(count, report.getTotalPolicyPostCount()); + assertEquals(count, report.getTotalPolicyTypeGetCount()); + assertEquals(count, report.getTotalPolicyTypePostCount()); + assertEquals(count, report.getPolicyGetSuccessCount()); + assertEquals(count, report.getPolicyGetFailureCount()); + assertEquals(count, report.getPolicyPostSuccessCount()); + assertEquals(count, report.getPolicyPostFailureCount()); + assertEquals(count, report.getPolicyTypeGetSuccessCount()); + assertEquals(count, report.getPolicyTypeGetFailureCount()); + assertEquals(count, report.getPolicyTypePostSuccessCount()); + assertEquals(count, report.getPolicyTypePostFailureCount()); } - private void validateReport(final String name, final String url, final boolean healthy, final int code, - final String message, final String reportString, final HealthCheckReport 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()); - assertEquals(reportString, report.toString()); } -} +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java deleted file mode 100644 index 5d535678..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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.api.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -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.Test; -import org.onap.policy.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.parameters.CommonTestData; -import org.onap.policy.api.main.parameters.RestServerParameters; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of {@link ApiRestController}. - */ -public class TestApiStatistics { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestApiStatistics.class); - - @Test - public void testApiStatistics_200() throws PolicyApiException, InterruptedException { - try { - final Main main = startApiService(); - StatisticsReport report = getApiStatistics(); - validateReport(report, 0, 200); - updateApiStatistics(); - report = getApiStatistics(); - validateReport(report, 1, 200); - stopApiService(main); - ApiStatisticsManager.resetAllStatistics(); - } catch (final Exception exp) { - LOGGER.error("testApiStatistics_200 failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testApiStatistics_500() throws InterruptedException { - final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); - restServerParams.setName(CommonTestData.API_GROUP_NAME); - - final ApiRestServer restServer = new ApiRestServer(restServerParams); - try { - restServer.start(); - final StatisticsReport report = getApiStatistics(); - validateReport(report, 0, 500); - restServer.shutdown(); - ApiStatisticsManager.resetAllStatistics(); - } catch (final Exception exp) { - LOGGER.error("testApiStatistics_500 failed", exp); - fail("Test should not throw an exception"); - } - } - - - private Main startApiService() { - final String[] distributionConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; - return new Main(distributionConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private StatisticsReport getApiStatistics() 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/statistics"); - - 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.get(StatisticsReport.class); - } - - private void updateApiStatistics() { - ApiStatisticsManager.updateTotalApiCallCount(); - ApiStatisticsManager.updateApiCallSuccessCount(); - ApiStatisticsManager.updateApiCallFailureCount(); - ApiStatisticsManager.updateTotalPolicyGetCount(); - ApiStatisticsManager.updateTotalPolicyPostCount(); - ApiStatisticsManager.updateTotalTemplateGetCount(); - ApiStatisticsManager.updateTotalTemplatePostCount(); - ApiStatisticsManager.updatePolicyGetSuccessCount(); - ApiStatisticsManager.updatePolicyGetFailureCount(); - ApiStatisticsManager.updatePolicyPostSuccessCount(); - ApiStatisticsManager.updatePolicyPostFailureCount(); - ApiStatisticsManager.updateTemplateGetSuccessCount(); - ApiStatisticsManager.updateTemplateGetFailureCount(); - ApiStatisticsManager.updateTemplatePostSuccessCount(); - ApiStatisticsManager.updateTemplatePostFailureCount(); - } - - private void validateReport(final StatisticsReport report, final int count, final int code) { - assertEquals(code, report.getCode()); - assertEquals(count, report.getTotalApiCallCount()); - assertEquals(count, report.getApiCallSuccessCount()); - assertEquals(count, report.getApiCallFailureCount()); - assertEquals(count, report.getTotalPolicyGetCount()); - assertEquals(count, report.getTotalPolicyPostCount()); - assertEquals(count, report.getTotalTemplateGetCount()); - assertEquals(count, report.getTotalTemplatePostCount()); - assertEquals(count, report.getPolicyGetSuccessCount()); - assertEquals(count, report.getPolicyGetFailureCount()); - assertEquals(count, report.getPolicyPostSuccessCount()); - assertEquals(count, report.getPolicyPostFailureCount()); - assertEquals(count, report.getTemplateGetSuccessCount()); - assertEquals(count, report.getTemplateGetFailureCount()); - assertEquals(count, report.getTemplatePostSuccessCount()); - assertEquals(count, report.getTemplatePostFailureCount()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java deleted file mode 100644 index d080350a..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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.api.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -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.authentication.HttpAuthenticationFeature; -import org.junit.Test; -import org.onap.policy.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of https set on API REST server. - */ -public class TestHttpsApiRestServer { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestHttpsApiRestServer.class); - private static final String ALIVE = "alive"; - private static final String SELF = "self"; - private static final String NAME = "Policy API"; - private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; - - @Test - public void testHttpsHealthCheckSuccess() { - final String reportString = "Report [name=Policy API, url=self, healthy=true, code=200, message=alive]"; - try { - final Main main = startApiService(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); - stopApiService(main); - } catch (final Exception exp) { - LOGGER.error("testHttpsHealthCheckSuccess failed", exp); - fail("Test should not throw an exception"); - } - } - - private Main startApiService() { - 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[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_Https.json" }; - return new Main(apiConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private HealthCheckReport performHealthCheck() 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/healthcheck"); - - 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.get(HealthCheckReport.class); - } - - private void validateReport(final String name, final String url, final boolean healthy, final int code, - final String message, final String reportString, final HealthCheckReport report) { - assertEquals(name, report.getName()); - assertEquals(url, report.getUrl()); - assertEquals(healthy, report.isHealthy()); - assertEquals(code, report.getCode()); - assertEquals(message, report.getMessage()); - assertEquals(reportString, report.toString()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java deleted file mode 100644 index 6b992442..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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.api.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -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.authentication.HttpAuthenticationFeature; -import org.junit.Test; -import org.onap.policy.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of API statistics via https set on API REST server. - */ -public class TestHttpsStatisticApiRestServer { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestHttpsStatisticApiRestServer.class); - private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; - - @Test - public void testHttpsApiStatistic() - throws PolicyApiException, InterruptedException, KeyManagementException, NoSuchAlgorithmException { - final String reportString = "StatisticsReport [code=200, totalApiCallCount=0, apiCallSuccessCount=0, " - + "apiCallFailureCount=0, " + "totalPolicyGetCount=0, totalPolicyPostCount=0, " - + "totalTemplateGetCount=0, totalTemplatePostCount=0, " - + "policyGetSuccessCount=0, policyGetFailureCount=0, " - + "policyPostSuccessCount=0, policyPostFailureCount=0, " - + "templateGetSuccessCount=0, templateGetFailureCount=0, " - + "templatePostSuccessCount=0, templatePostFailureCount=0]"; - try { - final Main main = startApiService(); - final StatisticsReport report = performStatisticCheck(); - validateReport(200, 0, reportString, report); - stopApiService(main); - } catch (final Exception exp) { - LOGGER.error("testHttpsApiStatistic failed", exp); - fail("Test should not throw an exception"); - } - } - - private Main startApiService() { - 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[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_Https.json" }; - return new Main(apiConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private StatisticsReport performStatisticCheck() 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/statistics"); - - 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.get(StatisticsReport.class); - } - - private void validateReport(final int code, final int count, - final String reportString, final StatisticsReport report) { - assertEquals(code, report.getCode()); - assertEquals(count, report.getTotalApiCallCount()); - assertEquals(count, report.getApiCallSuccessCount()); - assertEquals(count, report.getApiCallFailureCount()); - assertEquals(count, report.getTotalPolicyGetCount()); - assertEquals(count, report.getTotalPolicyPostCount()); - assertEquals(count, report.getTotalTemplateGetCount()); - assertEquals(count, report.getTotalTemplatePostCount()); - assertEquals(count, report.getPolicyGetSuccessCount()); - assertEquals(count, report.getPolicyGetFailureCount()); - assertEquals(count, report.getPolicyPostSuccessCount()); - assertEquals(count, report.getPolicyPostFailureCount()); - assertEquals(count, report.getTemplateGetSuccessCount()); - assertEquals(count, report.getTemplateGetFailureCount()); - assertEquals(count, report.getTemplatePostSuccessCount()); - assertEquals(count, report.getTemplatePostFailureCount()); - assertEquals(reportString, report.toString()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java b/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java index 75b89c15..e240f683 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,10 +30,13 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; import org.junit.Test; +import org.onap.policy.api.main.rest.StatisticsReport; import org.onap.policy.common.utils.validation.ToStringTester; /** * Class to perform unit testing of {@link StatisticsReport}. + * + * @author Chenfei Gao (cgao@research.att.com) */ public class TestStatisticsReport { |