diff options
author | Chenfei Gao <cgao@research.att.com> | 2019-01-31 16:09:09 -0500 |
---|---|---|
committer | Chenfei Gao <cgao@research.att.com> | 2019-02-07 09:19:38 -0500 |
commit | 6ea2e1bb9f7ee330f04fe8e28fd94fbf398a06ec (patch) | |
tree | 9c2f3845f222a31b080929763446ef1cb20858bd /main/src/test | |
parent | f437d629aac23467dc505d081bbe1634a5ef63b8 (diff) |
Add changes to basic structure of api component
Includes:
1) Changed logging from FlexLogger to slf4j and used the logback.xml aligned with
v1.2 logging requirements.
2) Added https as a configurable parameter of api rest server.
3) Added aaf as a condfigurable parameter of api rest server.
4) Added AafFilter classes for healthcheck and statistics.
5) Added api statistics REST entry point.
6) Created related junit tests.
7) Packaged docker
Issue-ID: POLICY-1270
Change-Id: I638f61361bb052545e8597531ba3d58019bf1f24
Signed-off-by: Chenfei Gao <cgao@research.att.com>
Diffstat (limited to 'main/src/test')
12 files changed, 571 insertions, 84 deletions
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java index f86c8570..8ff2f98e 100644 --- a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java +++ b/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java @@ -1,6 +1,9 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * ONAP Policy API + * ================================================================================ + * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -30,21 +33,23 @@ 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_AAF = false; public static final String API_GROUP_NAME = "ApiGroup"; /** - * Returns an instance of ReceptionHandlerParameters for test cases. + * Returns an instance of RestServerParameters for test cases. * * @param isEmpty boolean value to represent that object created should be empty or not - * @return the restServerParameters object + * @return the RestServerParameters object */ public RestServerParameters getRestServerParameters(final boolean isEmpty) { final RestServerParameters restServerParameters; if (!isEmpty) { restServerParameters = new RestServerParameters(REST_SERVER_HOST, REST_SERVER_PORT, REST_SERVER_USER, - REST_SERVER_PASSWORD); + REST_SERVER_PASSWORD, REST_SERVER_HTTPS, REST_SERVER_AAF); } else { - restServerParameters = new RestServerParameters(null, 0, null, null); + restServerParameters = new RestServerParameters(null, 0, null, null, false, false); } return restServerParameters; } diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java index 7a59dad6..93fbfc64 100644 --- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java +++ b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java @@ -1,6 +1,9 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * ONAP Policy API + * ================================================================================ + * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -47,6 +50,8 @@ public class TestApiParameterGroup { apiParameters.getRestServerParameters().getUserName()); assertEquals(restServerParameters.getPassword(), apiParameters.getRestServerParameters().getPassword()); + assertEquals(restServerParameters.isHttps(), apiParameters.getRestServerParameters().isHttps()); + assertEquals(restServerParameters.isAaf(), apiParameters.getRestServerParameters().isAaf()); assertEquals(CommonTestData.API_GROUP_NAME, apiParameters.getName()); } diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java index 7a065240..71d8c357 100644 --- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java +++ b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -29,7 +30,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Test; -import org.onap.policy.api.main.PolicyApiException; +import org.onap.policy.api.main.exception.PolicyApiException; import org.onap.policy.api.main.startstop.ApiCommandLineArguments; /** @@ -39,9 +40,7 @@ import org.onap.policy.api.main.startstop.ApiCommandLineArguments; public class TestApiParameterHandler { @Test public void testParameterHandlerNoParameterFile() throws PolicyApiException { - final String[] noArgumentString = - { "-c", "parameters/NoParameterFile.json" }; - + final String[] noArgumentString = { "-c", "parameters/NoParameterFile.json" }; final ApiCommandLineArguments noArguments = new ApiCommandLineArguments(); noArguments.parse(noArgumentString); @@ -55,9 +54,7 @@ public class TestApiParameterHandler { @Test public void testParameterHandlerEmptyParameters() throws PolicyApiException { - final String[] emptyArgumentString = - { "-c", "parameters/EmptyParameters.json" }; - + final String[] emptyArgumentString = { "-c", "parameters/EmptyParameters.json" }; final ApiCommandLineArguments emptyArguments = new ApiCommandLineArguments(); emptyArguments.parse(emptyArgumentString); @@ -71,9 +68,7 @@ public class TestApiParameterHandler { @Test public void testParameterHandlerBadParameters() throws PolicyApiException { - final String[] badArgumentString = - { "-c", "parameters/BadParameters.json" }; - + final String[] badArgumentString = { "-c", "parameters/BadParameters.json" }; final ApiCommandLineArguments badArguments = new ApiCommandLineArguments(); badArguments.parse(badArgumentString); @@ -89,9 +84,7 @@ public class TestApiParameterHandler { @Test public void testParameterHandlerInvalidParameters() throws PolicyApiException { - final String[] invalidArgumentString = - { "-c", "parameters/InvalidParameters.json" }; - + final String[] invalidArgumentString = { "-c", "parameters/InvalidParameters.json" }; final ApiCommandLineArguments invalidArguments = new ApiCommandLineArguments(); invalidArguments.parse(invalidArgumentString); @@ -107,9 +100,7 @@ public class TestApiParameterHandler { @Test public void testParameterHandlerNoParameters() throws PolicyApiException { - final String[] noArgumentString = - { "-c", "parameters/NoParameters.json" }; - + final String[] noArgumentString = { "-c", "parameters/NoParameters.json" }; final ApiCommandLineArguments noArguments = new ApiCommandLineArguments(); noArguments.parse(noArgumentString); @@ -127,24 +118,18 @@ public class TestApiParameterHandler { @Test public void testParameterHandlerMinumumParameters() throws PolicyApiException { - final String[] minArgumentString = - { "-c", "parameters/MinimumParameters.json" }; - + final String[] minArgumentString = { "-c", "parameters/MinimumParameters.json" }; final ApiCommandLineArguments minArguments = new ApiCommandLineArguments(); minArguments.parse(minArgumentString); - final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(minArguments); assertEquals(CommonTestData.API_GROUP_NAME, parGroup.getName()); } @Test public void testApiParameterGroup() throws PolicyApiException { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters.json" }; - + final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); arguments.parse(apiConfigParameters); - final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(arguments); assertTrue(arguments.checkSetConfigurationFilePath()); assertEquals(CommonTestData.API_GROUP_NAME, parGroup.getName()); @@ -152,9 +137,7 @@ public class TestApiParameterHandler { @Test public void testApiParameterGroup_InvalidName() throws PolicyApiException { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters_InvalidName.json" }; - + final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_InvalidName.json" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); arguments.parse(apiConfigParameters); @@ -170,9 +153,8 @@ public class TestApiParameterHandler { @Test public void testApiParameterGroup_InvalidRestServerParameters() throws PolicyApiException, IOException { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters_InvalidRestServerParameters.json" }; - + final String[] apiConfigParameters = + { "-c", "parameters/ApiConfigParameters_InvalidRestServerParameters.json" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); arguments.parse(apiConfigParameters); @@ -189,8 +171,7 @@ public class TestApiParameterHandler { @Test public void testApiVersion() throws PolicyApiException { - final String[] apiConfigParameters = - { "-v" }; + final String[] apiConfigParameters = { "-v" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); final String version = arguments.parse(apiConfigParameters); assertTrue(version.startsWith("ONAP Policy Framework Api Service")); @@ -198,8 +179,7 @@ public class TestApiParameterHandler { @Test public void testApiHelp() throws PolicyApiException { - final String[] apiConfigParameters = - { "-h" }; + final String[] apiConfigParameters = { "-h" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); final String help = arguments.parse(apiConfigParameters); assertTrue(help.startsWith("usage:")); @@ -207,8 +187,7 @@ public class TestApiParameterHandler { @Test public void testApiInvalidOption() throws PolicyApiException { - final String[] apiConfigParameters = - { "-d" }; + final String[] apiConfigParameters = { "-d" }; final ApiCommandLineArguments arguments = new ApiCommandLineArguments(); try { arguments.parse(apiConfigParameters); 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 ad63d0f1..1ea42e0e 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -22,6 +23,9 @@ package org.onap.policy.api.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 javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -32,13 +36,14 @@ 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.PolicyApiException; +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.endpoints.report.HealthCheckReport; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.common.utils.network.NetworkUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Class to perform unit test of HealthCheckMonitor. @@ -46,7 +51,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; */ public class TestApiRestServer { - private static final Logger LOGGER = FlexLogger.getLogger(TestApiRestServer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TestApiRestServer.class); private static final String NOT_ALIVE = "not alive"; private static final String ALIVE = "alive"; private static final String SELF = "self"; @@ -55,10 +60,15 @@ public class TestApiRestServer { @Test public void testHealthCheckSuccess() throws PolicyApiException, InterruptedException { final String reportString = "Report [name=Policy API, url=self, healthy=true, code=200, message=alive]"; - final Main main = startApiService(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); - stopApiService(main); + 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("testHealthCheckSuccess failed", exp); + fail("Test should not throw an exception"); + } } @Test @@ -67,12 +77,17 @@ public class TestApiRestServer { final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); restServerParams.setName(CommonTestData.API_GROUP_NAME); final ApiRestServer restServer = new ApiRestServer(restServerParams); - restServer.start(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, report); - assertTrue(restServer.isAlive()); - assertTrue(restServer.toString().startsWith("ApiRestServer [servers=")); - restServer.shutdown(); + try { + restServer.start(); + final HealthCheckReport report = performHealthCheck(); + validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, 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() { @@ -84,8 +99,7 @@ public class TestApiRestServer { main.shutdown(); } - private HealthCheckReport performHealthCheck() throws InterruptedException { - HealthCheckReport response = null; + private HealthCheckReport performHealthCheck() throws InterruptedException, IOException { final ClientConfig clientConfig = new ClientConfig(); final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); @@ -95,14 +109,11 @@ public class TestApiRestServer { final WebTarget webTarget = client.target("http://localhost:6969/healthcheck"); final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - while (response == null) { - try { - response = invocationBuilder.get(HealthCheckReport.class); - } catch (final Exception exp) { - LOGGER.info("the server is not started yet. We will retry again"); - } + + if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { + throw new IllegalStateException("cannot connect to port 6969"); } - return response; + return invocationBuilder.get(HealthCheckReport.class); } private void validateReport(final String name, final String url, final boolean healthy, final int code, 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 new file mode 100644 index 00000000..5d535678 --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java @@ -0,0 +1,152 @@ +/*- + * ============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 new file mode 100644 index 00000000..d080350a --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java @@ -0,0 +1,135 @@ +/*- + * ============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 new file mode 100644 index 00000000..6b992442 --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java @@ -0,0 +1,151 @@ +/*- + * ============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 new file mode 100644 index 00000000..75b89c15 --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java @@ -0,0 +1,47 @@ +/*- + * ============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 com.openpojo.reflection.filters.FilterClassName; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.rule.impl.SetterMustExistRule; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +import org.junit.Test; +import org.onap.policy.common.utils.validation.ToStringTester; + +/** + * Class to perform unit testing of {@link StatisticsReport}. + */ +public class TestStatisticsReport { + + @Test + public void testStatisticsReport() { + final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterMustExistRule()) + .with(new SetterTester()).with(new GetterTester()).build(); + validator.validate(StatisticsReport.class.getPackage().getName(), + new FilterClassName(StatisticsReport.class.getName())); + } +} diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java b/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java index e5ab8101..01cd77c6 100644 --- a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java +++ b/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -24,7 +25,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.onap.policy.api.main.PolicyApiException; +import org.onap.policy.api.main.exception.PolicyApiException; import org.onap.policy.api.main.parameters.ApiParameterGroup; import org.onap.policy.api.main.parameters.ApiParameterHandler; import org.onap.policy.api.main.parameters.CommonTestData; @@ -38,14 +39,9 @@ public class TestApiActivator { @Test public void testApiActivator() throws PolicyApiException { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters.json" }; - - final ApiCommandLineArguments arguments = - new ApiCommandLineArguments(apiConfigParameters); - + final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; + final ApiCommandLineArguments arguments = new ApiCommandLineArguments(apiConfigParameters); final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(arguments); - final ApiActivator activator = new ApiActivator(parGroup); activator.initialize(); assertTrue(activator.getParameterGroup().isValid()); diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java index 47725349..2f68e852 100644 --- a/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java +++ b/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * 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. @@ -24,7 +25,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.onap.policy.api.main.PolicyApiException; +import org.onap.policy.api.main.exception.PolicyApiException; import org.onap.policy.api.main.parameters.CommonTestData; /** @@ -35,8 +36,7 @@ public class TestMain { @Test public void testMain() throws PolicyApiException { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters.json" }; + final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; final Main main = new Main(apiConfigParameters); assertTrue(main.getParameters().isValid()); assertEquals(CommonTestData.API_GROUP_NAME, main.getParameters().getName()); @@ -45,31 +45,27 @@ public class TestMain { @Test public void testMain_NoArguments() { - final String[] apiConfigParameters = - {}; + final String[] apiConfigParameters = {}; final Main main = new Main(apiConfigParameters); assertTrue(main.getParameters() == null); } @Test public void testMain_InvalidArguments() { - final String[] apiConfigParameters = - { "parameters/ApiConfigParameters.json" }; + final String[] apiConfigParameters = { "parameters/ApiConfigParameters.json" }; final Main main = new Main(apiConfigParameters); assertTrue(main.getParameters() == null); } @Test public void testMain_Help() { - final String[] apiConfigParameters = - { "-h" }; + final String[] apiConfigParameters = { "-h" }; Main.main(apiConfigParameters); } @Test public void testMain_InvalidParameters() { - final String[] apiConfigParameters = - { "-c", "parameters/ApiConfigParameters_InvalidName.json" }; + final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_InvalidName.json" }; final Main main = new Main(apiConfigParameters); assertTrue(main.getParameters() == null); } diff --git a/main/src/test/resources/parameters/ApiConfigParameters_Https.json b/main/src/test/resources/parameters/ApiConfigParameters_Https.json new file mode 100644 index 00000000..ec732132 --- /dev/null +++ b/main/src/test/resources/parameters/ApiConfigParameters_Https.json @@ -0,0 +1,10 @@ +{ + "name":"ApiGroup", + "restServerParameters":{ + "host":"0.0.0.0", + "port":6969, + "userName":"healthcheck", + "password":"zb!XztG34", + "https":true + } +} diff --git a/main/src/test/resources/ssl/policy-keystore b/main/src/test/resources/ssl/policy-keystore Binary files differnew file mode 100644 index 00000000..7d2b1ecc --- /dev/null +++ b/main/src/test/resources/ssl/policy-keystore |