From 4694c152f69380f4d3d64bde0a13d15fb59a71f3 Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Fri, 3 Dec 2021 11:27:32 +0000 Subject: Migrate pap startup & controllers to spring boot This commit migrates pap config, startup and controllers to spring boot. Change-Id: Icf91d728160a23db614dfba6b40ddccd2f6163a5 Issue-ID: POLICY-3754 Signed-off-by: a.sreekumar --- .../onap/policy/pap/main/comm/PublisherTest.java | 8 +- .../policy/pap/main/parameters/CommonTestData.java | 3 +- .../pap/main/parameters/TestPapParameterGroup.java | 19 +-- .../main/parameters/TestPapParameterHandler.java | 145 ------------------ .../policy/pap/main/rest/CommonPapRestServer.java | 138 +++++------------ .../pap/main/rest/PapRestControllerV1Test.java | 44 ++---- .../rest/TestPdpGroupCreateOrUpdateProvider.java | 2 + .../pap/main/rest/TestPdpGroupDeleteProvider.java | 9 +- .../pap/main/rest/TestPdpGroupDeployProvider.java | 2 + .../main/rest/TestPdpGroupHealthCheckProvider.java | 9 +- .../pap/main/rest/TestPolicyAuditProvider.java | 1 + ...estPolicyComponentsHealthCheckControllerV1.java | 39 ++--- .../TestPolicyComponentsHealthCheckProvider.java | 32 ++-- .../pap/main/rest/TestPolicyStatusProvider.java | 1 + .../policy/pap/main/rest/TestProviderBase.java | 2 + .../onap/policy/pap/main/rest/e2e/End2EndBase.java | 6 +- .../policy/pap/main/rest/e2e/PolicyAuditTest.java | 21 +-- .../policy/pap/main/rest/e2e/StatisticsTest.java | 13 +- .../onap/policy/pap/main/startstop/TestMain.java | 163 --------------------- .../pap/main/startstop/TestPapActivator.java | 6 +- main/src/test/resources/config/application.yaml | 81 ++++++++++ 21 files changed, 211 insertions(+), 533 deletions(-) delete mode 100644 main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java delete mode 100644 main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java create mode 100644 main/src/test/resources/config/application.yaml (limited to 'main/src/test') diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java index 2c0479b1..51ced7bd 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -44,9 +45,8 @@ import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.onap.policy.pap.main.parameters.PapParameterHandler; -import org.onap.policy.pap.main.startstop.PapCommandLineArguments; public class PublisherTest extends Threaded { @@ -85,9 +85,7 @@ public class PublisherTest extends Threaded { */ @BeforeClass public static void setUpBeforeClass() throws Exception { - final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters.json"}; - final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); - final PapParameterGroup parameterGroup = new PapParameterHandler().getParameters(arguments); + final PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); TopicEndpointManager.getManager().shutdown(); TopicEndpointManager.getManager().addTopics(parameterGroup.getTopicParameterGroup()); diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java index 14000e60..34d72203 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -41,7 +42,7 @@ public class CommonTestData { private static final Coder coder = new StandardCoder(); - private static int dbNum = 0; + public static int dbNum = 0; public static void newDb() { ++dbNum; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java index 8962f45b..926a1f49 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -27,7 +28,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; @@ -52,17 +52,10 @@ public class TestPapParameterGroup { @Test public void testPapParameterGroup() { final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(1); - final RestServerParameters restServerParameters = papParameters.getRestServerParameters(); final TopicParameterGroup topicParameterGroup = papParameters.getTopicParameterGroup(); final ValidationResult validationResult = papParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.PAP_GROUP_NAME, papParameters.getName()); - assertEquals(restServerParameters.getHost(), papParameters.getRestServerParameters().getHost()); - assertEquals(restServerParameters.getPort(), papParameters.getRestServerParameters().getPort()); - assertEquals(restServerParameters.getUserName(), papParameters.getRestServerParameters().getUserName()); - assertEquals(restServerParameters.getPassword(), papParameters.getRestServerParameters().getPassword()); - assertTrue(papParameters.getRestServerParameters().isHttps()); - assertFalse(papParameters.getRestServerParameters().isAaf()); assertEquals(topicParameterGroup.getTopicSinks(), papParameters.getTopicParameterGroup().getTopicSinks()); assertEquals(topicParameterGroup.getTopicSources(), papParameters.getTopicParameterGroup().getTopicSources()); } @@ -96,14 +89,4 @@ public class TestPapParameterGroup { assertEquals("PapNewGroup", papParameters.getName()); } - @Test - public void testApiParameterGroup_EmptyRestServerParameters() throws Exception { - String json = commonTestData.getPapParameterGroupAsString(1); - json = commonTestData.nullifyField(json, "restServerParameters"); - final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(0); - final ValidationResult validationResult = papParameters.validate(); - assertFalse(validationResult.isValid()); - assertThat(validationResult.getResult()) - .contains("\"RestServerParameters\" INVALID, item has status INVALID"); - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java deleted file mode 100644 index 6b6431fa..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import org.junit.Test; -import org.onap.policy.common.utils.cmd.CommandLineException; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.pap.main.PolicyPapException; -import org.onap.policy.pap.main.startstop.PapCommandLineArguments; - -/** - * Class to perform unit test of {@link PapParameterHandler}. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestPapParameterHandler { - - @Test - public void testParameterHandlerNoParameterFile() throws PolicyPapException, CommandLineException { - final String[] noArgumentString = { "-c", "parameters/NoParameterFile.json" }; - - final PapCommandLineArguments noArguments = new PapCommandLineArguments(); - noArguments.parse(noArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(noArguments)) - .hasCauseInstanceOf(CoderException.class) - .hasRootCauseInstanceOf(FileNotFoundException.class); - } - - @Test - public void testParameterHandlerEmptyParameters() throws PolicyPapException, CommandLineException { - final String[] emptyArgumentString = { "-c", "parameters/EmptyParameters.json" }; - - final PapCommandLineArguments emptyArguments = new PapCommandLineArguments(); - emptyArguments.parse(emptyArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(emptyArguments)) - .hasMessageContaining("no parameters found in \"parameters/EmptyParameters.json\""); - } - - @Test - public void testParameterHandlerInvalidParameters() throws PolicyPapException, CommandLineException { - final String[] invalidArgumentString = { "-c", "parameters/InvalidParameters.json" }; - - final PapCommandLineArguments invalidArguments = new PapCommandLineArguments(); - invalidArguments.parse(invalidArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(invalidArguments)) - .hasMessageStartingWith("error reading parameters from \"parameters/InvalidParameters.json\"") - .hasCauseInstanceOf(CoderException.class); - } - - @Test - public void testParameterHandlerNoParameters() throws PolicyPapException, CommandLineException { - final String[] noArgumentString = { "-c", "parameters/NoParameters.json" }; - - final PapCommandLineArguments noArguments = new PapCommandLineArguments(); - noArguments.parse(noArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(noArguments)).hasMessageContaining("is null"); - } - - @Test - public void testParameterHandlerMinumumParameters() throws PolicyPapException, CommandLineException { - final String[] minArgumentString = { "-c", "parameters/MinimumParameters.json" }; - - final PapCommandLineArguments minArguments = new PapCommandLineArguments(); - minArguments.parse(minArgumentString); - - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(minArguments); - assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); - } - - @Test - public void testPapParameterGroup() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; - - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - arguments.parse(papConfigParameters); - - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); - assertTrue(arguments.checkSetConfigurationFilePath()); - assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); - } - - @Test - public void testPapParameterGroup_InvalidName() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters_InvalidName.json" }; - - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - arguments.parse(papConfigParameters); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(arguments)) - .hasMessageContaining("\"name\" value \" \" INVALID, is blank"); - } - - @Test - public void testPapVersion() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-v" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - final String version = arguments.parse(papConfigParameters); - assertTrue(version.startsWith("ONAP Policy Framework PAP Service")); - } - - @Test - public void testPapHelp() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-h" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - final String help = arguments.parse(papConfigParameters); - assertTrue(help.startsWith("usage:")); - } - - @Test - public void testPapInvalidOption() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-d" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - assertThatThrownBy(() -> arguments.parse(papConfigParameters)) - .hasMessageStartingWith("invalid command line arguments specified"); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index 98a24a62..9673c295 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -28,7 +29,6 @@ import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; -import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.net.ssl.SSLContext; @@ -41,35 +41,41 @@ import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientProperties; 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.junit.runner.RunWith; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.gson.GsonMessageBodyHandler; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.security.SelfSignedKeyStore; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.PolicyPapApplication; import org.onap.policy.pap.main.parameters.CommonTestData; -import org.onap.policy.pap.main.startstop.Main; import org.onap.policy.pap.main.startstop.PapActivator; import org.powermock.reflect.Whitebox; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.junit4.SpringRunner; /** * Class to perform unit test of {@link PapRestControllerV1}. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class CommonPapRestServer { +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"db.initialize=false"}) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +public abstract class CommonPapRestServer { protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json"; - private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.class); - public static final String NOT_ALIVE = "not alive"; public static final String ALIVE = "alive"; public static final String SELF = NetworkUtil.getHostname(); @@ -77,59 +83,38 @@ public class CommonPapRestServer { public static final String ENDPOINT_PREFIX = "policy/pap/v1/"; private static SelfSignedKeyStore keystore; - private static int port; - protected static String httpsPrefix; - - private static Main main; private boolean activatorWasAlive; + protected String httpsPrefix; + + @LocalServerPort + private int port; + + @Autowired + private PapActivator papActivator; /** - * Allocates a port for the server, writes a config file, and then starts Main. + * Allocates a new db url, writes a config file. * * @throws Exception if an error occurs */ @BeforeClass public static void setUpBeforeClass() throws Exception { - setUpBeforeClass(true); - } - - /** - * Allocates a port for the server, writes a config file, and then starts Main, if - * specified. - * - * @param shouldStart {@code true} if Main should be started, {@code false} otherwise - * @throws Exception if an error occurs - */ - public static void setUpBeforeClass(boolean shouldStart) throws Exception { keystore = new SelfSignedKeyStore(); - port = NetworkUtil.allocPort(); - - httpsPrefix = "https://localhost:" + port + "/"; - + CommonTestData.newDb(); makeConfigFile(); HttpServletServerFactoryInstance.getServerFactory().destroy(); TopicEndpointManager.getManager().shutdown(); - - CommonTestData.newDb(); - - if (shouldStart) { - startMain(); - } + Registry.newRegistry(); } - /** - * Stops Main. - */ - @AfterClass - public static void teardownAfterClass() { - try { - stopMain(); - - } catch (PolicyPapException exp) { - LOGGER.error("cannot stop main", exp); - } + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("pap.databaseProviderParameters.databaseUrl", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); + registry.add("server.ssl.enabled", () -> "true"); + registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); + registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); } /** @@ -139,12 +124,8 @@ public class CommonPapRestServer { */ @Before public void setUp() throws Exception { - // restart, if not currently running - if (main == null) { - startMain(); - } - - activatorWasAlive = Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive(); + httpsPrefix = "https://localhost:" + port + "/"; + activatorWasAlive = papActivator.isAlive(); } /** @@ -162,10 +143,9 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ protected void testSwagger(final String endpoint) throws Exception { - final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true); + final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "v2/api-docs", true); final String resp = invocationBuilder.get(String.class); - - assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":")); + assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint)); } /** @@ -174,7 +154,7 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ private static void makeConfigFile() throws Exception { - String json = new CommonTestData().getPapParameterGroupAsString(port); + String json = new CommonTestData().getPapParameterGroupAsString(6969); File file = new File(CONFIG_FILE); file.deleteOnExit(); @@ -184,47 +164,6 @@ public class CommonPapRestServer { } } - /** - * Starts the "Main". - * - * @throws Exception if an error occurs - */ - protected static void startMain() throws Exception { - Registry.newRegistry(); - - // make sure port is available - if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) { - throw new IllegalStateException("port " + port + " is still in use"); - } - - final Properties systemProps = System.getProperties(); - systemProps.put("javax.net.ssl.keyStore", keystore.getKeystoreName()); - systemProps.put("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD); - System.setProperties(systemProps); - - final String[] papConfigParameters = { "-c", CONFIG_FILE }; - - main = new Main(papConfigParameters); - - if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) { - throw new IllegalStateException("server is not listening on port " + port); - } - } - - /** - * Stops the "Main". - * - * @throws PolicyPapException if an error occurs - */ - private static void stopMain() throws PolicyPapException { - if (main != null) { - Main main2 = main; - main = null; - - main2.shutdown(); - } - } - /** * Mark the activator as dead, but leave its REST server running. */ @@ -233,8 +172,7 @@ public class CommonPapRestServer { } private void markActivator(boolean wasAlive) { - Object manager = Whitebox.getInternalState(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class), - "serviceManager"); + Object manager = Whitebox.getInternalState(papActivator, "serviceManager"); AtomicBoolean running = Whitebox.getInternalState(manager, "running"); running.set(wasAlive); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java index aafcd40f..f8e47ef4 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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,15 +25,8 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import java.security.Principal; import java.util.UUID; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.SecurityContext; import org.junit.After; import org.junit.Before; @@ -40,7 +34,8 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.internal.stubbing.answers.Returns; +import org.springframework.http.ResponseEntity; +import org.springframework.http.ResponseEntity.BodyBuilder; public class PapRestControllerV1Test { @@ -51,11 +46,11 @@ public class PapRestControllerV1Test { PapRestControllerV1 mockController; private AutoCloseable closeable; - private ResponseBuilder bldr; + private BodyBuilder bldr; @Before public void setUp() { - bldr = Response.status(Response.Status.OK); + bldr = ResponseEntity.ok(); closeable = MockitoAnnotations.openMocks(this); } @@ -64,42 +59,29 @@ public class PapRestControllerV1Test { closeable.close(); } - @Test - public void testProduces() { - Produces annotation = PapRestControllerV1.class.getAnnotation(Produces.class); - assertNotNull(annotation); - assertThat(annotation.value()).contains(MediaType.APPLICATION_JSON) - .contains(PapRestControllerV1.APPLICATION_YAML); - } - @Test public void testAddVersionControlHeaders() { - Response resp = mockController.addVersionControlHeaders(bldr).build(); - assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_MINOR_NAME)); - assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_PATCH_NAME)); - assertEquals("1.0.0", resp.getHeaderString(PapRestControllerV1.VERSION_LATEST_NAME)); + ResponseEntity resp = mockController.addVersionControlHeaders(bldr).build(); + assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_MINOR_NAME).get(0)); + assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_PATCH_NAME).get(0)); + assertEquals("1.0.0", resp.getHeaders().get(PapRestControllerV1.VERSION_LATEST_NAME).get(0)); } @Test public void testAddLoggingHeaders_Null() { - Response resp = mockController.addLoggingHeaders(bldr, null).build(); - assertNotNull(resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + ResponseEntity resp = mockController.addLoggingHeaders(bldr, null).build(); + assertNotNull(resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME)); } @Test public void testAddLoggingHeaders_NonNull() { UUID uuid = UUID.randomUUID(); - Response resp = mockController.addLoggingHeaders(bldr, uuid).build(); - assertEquals(uuid.toString(), resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + ResponseEntity resp = mockController.addLoggingHeaders(bldr, uuid).build(); + assertEquals(uuid.toString(), resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME).get(0)); } @Test public void testGetPrincipal() { assertThat(new PapRestControllerV1().getPrincipal()).isEmpty(); - - Principal mockUser = mock(Principal.class, new Returns("myFakeUser")); - when(mockSecurityContext.getUserPrincipal()).thenReturn(mockUser); - - assertEquals("myFakeUser", mockController.getPrincipal()); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index f64a77b3..9a0f5702 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -78,6 +79,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); prov = new PdpGroupCreateOrUpdateProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index 4041de90..3e9eda8a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -91,7 +92,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion()); prov = new MyProvider(); - updater = prov.makeUpdater(session, policy1, fullIdent); } @@ -169,7 +169,9 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); - new PdpGroupDeleteProvider().undeploy(fullIdent, DEFAULT_USER); + PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider(); + deleteProvider.initialize(); + deleteProvider.undeploy(fullIdent, DEFAULT_USER); // should have updated the old group List updates = getGroupUpdates(); @@ -279,6 +281,9 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } private class MyProvider extends PdpGroupDeleteProvider { + private MyProvider() { + super.initialize(); + } @Override protected void process(T request, BiConsumerWithEx processor) throws PfModelException { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index d0039c6d..40e37e4f 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -92,6 +93,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); prov = new PdpGroupDeployProvider(); + prov.initialize(); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index a5f974be..b236c56b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,8 +29,6 @@ import static org.mockito.Mockito.when; import java.io.File; import java.util.List; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.junit.Before; import org.junit.Test; @@ -50,6 +48,7 @@ import org.onap.policy.models.pdp.concepts.Pdps; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.springframework.http.HttpStatus; /** * Class to perform unit test of {@link PdpGroupHealthCheckProvider}. @@ -85,8 +84,8 @@ public class TestPdpGroupHealthCheckProvider { @Test public void testFetchPdpGroupHealthStatus() throws Exception { final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(); - final Pair pair = provider.fetchPdpGroupHealthStatus(); - assertEquals(Response.Status.OK, pair.getLeft()); + final Pair pair = provider.fetchPdpGroupHealthStatus(); + assertEquals(HttpStatus.OK, pair.getLeft()); verifyPdps(pair.getRight().getPdpList(), groups); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java index 7d42912f..51bea02a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java @@ -53,6 +53,7 @@ public class TestPolicyAuditProvider extends ProviderSuper { super.setUp(); provider = new PolicyAuditProvider(); + provider.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java index b49d7704..e07d35c1 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2020 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Inc. + * Modifications Copyright (C) 2021 Bell Canada. 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,20 +25,16 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.parameters.RestClientParameters; -import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.powermock.reflect.Whitebox; +import org.springframework.beans.factory.annotation.Autowired; /** * Class to perform unit test of {@link PolicyComponentsHealthCheckControllerV1}. @@ -47,29 +44,10 @@ import org.powermock.reflect.Whitebox; public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestServer { private static final String ENDPOINT = "components/healthcheck"; - private static List savedRestClientParameters; + private List savedRestClientParameters; - /** - * Set up for the test class. - */ - @BeforeClass - public static void setUpClass() { - // To skip calling to the remote components - PapParameterGroup papParameterGroup = ParameterService.get("PapGroup"); - List lo = Whitebox.getInternalState(papParameterGroup, "healthCheckRestClientParameters"); - savedRestClientParameters = new ArrayList<>(lo); - lo.clear(); - } - - /** - * Tear down for the test class. - */ - @AfterClass - public static void tearDownClass() { - PapParameterGroup papParameterGroup = ParameterService.get("PapGroup"); - List lo = Whitebox.getInternalState(papParameterGroup, "healthCheckRestClientParameters"); - lo.addAll(savedRestClientParameters); - } + @Autowired + private PapParameterGroup papParameterGroup; @Test public void testSwagger() throws Exception { @@ -79,6 +57,10 @@ public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestSe @Test @SuppressWarnings("unchecked") public void testPolicyComponentsHealthCheck() throws Exception { + // take out the other components for healthcheck + savedRestClientParameters = papParameterGroup.getHealthCheckRestClientParameters(); + papParameterGroup.setHealthCheckRestClientParameters(null); + Invocation.Builder invocationBuilder = sendRequest(ENDPOINT); Response response = invocationBuilder.get(); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -86,5 +68,8 @@ public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestSe result = (Map) response.readEntity(GenericType.forInstance(result)); // No PDP configured, healthy is false assertFalse((Boolean) result.get("healthy")); + + // put back the other components + papParameterGroup.setHealthCheckRestClientParameters(savedRestClientParameters); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java index f27a8d32..13deef40 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java @@ -30,11 +30,11 @@ import static org.mockito.Mockito.when; import java.io.File; import java.net.HttpURLConnection; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.junit.After; import org.junit.Before; @@ -44,7 +44,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; -import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.report.HealthCheckReport; import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.coder.Coder; @@ -62,6 +61,8 @@ import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.startstop.PapActivator; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) public class TestPolicyComponentsHealthCheckProvider { @@ -105,6 +106,8 @@ public class TestPolicyComponentsHealthCheckProvider { private PapParameterGroup savedPapParameterGroup; + private PolicyComponentsHealthCheckProvider provider; + /** * Configures mocks and objects. * @@ -145,15 +148,15 @@ public class TestPolicyComponentsHealthCheckProvider { when(response3.getStatus()).thenReturn(HttpURLConnection.HTTP_OK); when(response3.readEntity(DmaapGetTopicResponse.class)).thenReturn(createDmaapResponse()); when(client3.get()).thenReturn(response3); - + List clients = new ArrayList<>(); + clients.add(client1); + clients.add(client2); + clients.add(client3); PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME); - List params = papParameterGroup.getHealthCheckRestClientParameters(); - when(clientFactory.build(params.get(0))).thenReturn(client1); - when(clientFactory.build(params.get(1))).thenReturn(client2); - when(clientFactory.build(params.get(2))).thenReturn(client3); - - PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup, - clientFactory); + provider = new PolicyComponentsHealthCheckProvider(); + ReflectionTestUtils.setField(provider, "papParameterGroup", papParameterGroup); + provider.initializeClientHealthCheckExecutorService(); + ReflectionTestUtils.setField(provider, "clients", clients); } /** @@ -166,15 +169,14 @@ public class TestPolicyComponentsHealthCheckProvider { } else { ParameterService.deregister(PAP_GROUP_PARAMS_NAME); } - PolicyComponentsHealthCheckProvider.cleanup(); + provider.cleanup(); } @Test public void testFetchPolicyComponentsHealthStatus_allHealthy() { - PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider(); - Pair> ret = provider.fetchPolicyComponentsHealthStatus(); - assertEquals(Response.Status.OK, ret.getLeft()); + Pair> ret = provider.fetchPolicyComponentsHealthStatus(); + assertEquals(HttpStatus.OK, ret.getLeft()); assertTrue((Boolean) ret.getRight().get(HEALTHY)); } @@ -239,7 +241,7 @@ public class TestPolicyComponentsHealthCheckProvider { } private Map callFetchPolicyComponentsHealthStatus() { - PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider(); + return provider.fetchPolicyComponentsHealthStatus().getRight(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index d3ff4ea6..8f09b7e3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -77,6 +77,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { super.setUp(); prov = new PolicyStatusProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index 0ca2d4fa..5046181c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -90,6 +91,7 @@ public class TestProviderBase extends ProviderSuper { when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); prov = new MyProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index 0f668bef..e51aa776 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -50,7 +51,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -public class End2EndBase extends CommonPapRestServer { +public abstract class End2EndBase extends CommonPapRestServer { private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class); private static final Coder coder = new StandardCoder(); @@ -79,7 +80,7 @@ public class End2EndBase extends CommonPapRestServer { */ @BeforeClass public static void setUpBeforeClass() throws Exception { - CommonPapRestServer.setUpBeforeClass(true); + CommonPapRestServer.setUpBeforeClass(); final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class); daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters()); @@ -103,7 +104,6 @@ public class End2EndBase extends CommonPapRestServer { logger.warn("failed to close DAO factory", e); } - CommonPapRestServer.teardownAfterClass(); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java index d010f1db..d98a4ba3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java @@ -50,6 +50,9 @@ public class PolicyAuditTest extends End2EndBase { private static final String QUERY_PARAMS_INVALID = "?recordCount=5&startTime=2021-07-25T01:25:15"; private static final String QUERY_PARAMS_CORRECT = "?recordCount=5&startTime=1627219515&endTime=1627478715"; private static final String QUERY_PARAMS_INCORRECT = "?recordCount=5&startTime=1627478715&endTime=1627565115"; + private static int NOT_FOUND_STATUS_CODE = 404; + private static int BAD_REQUEST_STATUS_CODE = 400; + private static final String BAD_REQUEST_MSG = "NumberFormatException For"; @Override @Before @@ -97,7 +100,7 @@ public class PolicyAuditTest extends End2EndBase { // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -114,11 +117,11 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -138,12 +141,12 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -162,12 +165,12 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } private void sendAndValidateSuccess(String uri, int count) throws Exception { @@ -193,10 +196,10 @@ public class PolicyAuditTest extends End2EndBase { } } - private void sendAndValidateError(String uri, String errorMessage) throws Exception { + private void sendAndValidateError(String uri, String errorMessage, int statusCode) throws Exception { Invocation.Builder invocationBuilder = sendRequest(uri); Response rawresp = invocationBuilder.get(); - assertThat(rawresp.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); + assertThat(rawresp.getStatus()).isEqualTo(statusCode); String resp = rawresp.readEntity(String.class); assertThat(resp).contains(errorMessage); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java index 0f1b560f..1331e458 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -38,8 +39,10 @@ import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.parameters.CommonTestData; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.rest.PapStatisticsManager; import org.onap.policy.pap.main.rest.StatisticsReport; @@ -57,10 +60,10 @@ public class StatisticsTest extends End2EndBase { public static void setUpBeforeClass() throws Exception { End2EndBase.setUpBeforeClass(); - PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { + PolicyModelsProviderFactory modelProviderWrapper = new PolicyModelsProviderFactory(); + PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); + try (PolicyModelsProvider databaseProvider = + modelProviderWrapper.createPolicyModelsProvider(parameterGroup.getDatabaseProviderParameters())) { PdpStatistics pdpStatisticsRecord = new PdpStatistics(); pdpStatisticsRecord.setPdpGroupName("defaultGroup"); pdpStatisticsRecord.setPdpSubGroupName("apex"); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java deleted file mode 100644 index a83be4fb..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2020 Bell Canada. 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.pap.main.startstop; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.charset.StandardCharsets; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.common.utils.resources.MessageConstants; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapRuntimeException; -import org.onap.policy.pap.main.parameters.CommonTestData; - -/** - * Class to perform unit test of {@link Main}}. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestMain { - private static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json"; - - private static int port; - - private Main main; - - /** - * Allocates a new DB name, server port, and creates a config file. - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - CommonTestData.newDb(); - port = NetworkUtil.allocPort(); - - String json = new CommonTestData().getPapParameterGroupAsString(port); - - File file = new File(CONFIG_FILE); - file.deleteOnExit(); - - try (FileOutputStream output = new FileOutputStream(file)) { - output.write(json.getBytes(StandardCharsets.UTF_8)); - } - } - - /** - * Set up. - */ - @Before - public void setUp() throws Exception { - Registry.newRegistry(); - HttpServletServerFactoryInstance.getServerFactory().destroy(); - } - - /** - * Shuts "main" down. - * - */ - @After - public void tearDown() { - // shut down activator - PapActivator activator = Registry.getOrDefault(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class, null); - if (activator != null && activator.isAlive()) { - activator.stop(); - } - } - - private void testMainBody(String[] papConfigParameters) { - main = new Main(papConfigParameters); - assertTrue(main.getParameters().isValid()); - assertEquals(CommonTestData.PAP_GROUP_NAME, main.getParameters().getName()); - - // ensure items were added to the registry - assertNotNull(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class)); - main.shutdown(); - } - - @Test - public void testMain() { - final String[] papConfigParameters = {"-c", CONFIG_FILE}; - testMainBody(papConfigParameters); - } - - @Test - public void testMainCustomGroup() { - final String[] papConfigParameters = { - "-c", - CONFIG_FILE, - "-g", - "parameters/PapDbGroup1.json" - }; - testMainBody(papConfigParameters); - } - - @Test - public void testMainPapDb() { - final String[] papConfigParameters = { - "-c", - CONFIG_FILE, - "-g", - "PapDb.json" - }; - testMainBody(papConfigParameters); - } - - @Test - public void testMain_NoArguments() { - final String[] papConfigParameters = {}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } - - @Test - public void testMain_InvalidArguments() { - final String[] papConfigParameters = {CONFIG_FILE}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } - - @Test - public void testMain_Help() { - final String[] papConfigParameters = {"-h"}; - main = new Main(papConfigParameters); - assertNull(main.getParameters()); - } - - @Test - public void testMain_InvalidParameters() { - final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters_InvalidName.json"}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 63ca52a8..1a1415a5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -44,7 +45,6 @@ import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.onap.policy.pap.main.parameters.PapParameterHandler; import org.onap.policy.pap.main.rest.PapStatisticsManager; @@ -89,9 +89,7 @@ public class TestPapActivator { output.write(json.getBytes(StandardCharsets.UTF_8)); } - final String[] papConfigParameters = {"-c", CONFIG_FILE}; - final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); + final PapParameterGroup parGroup = new CommonTestData().getPapParameterGroup(6969); activator = new PapActivator(parGroup); } diff --git a/main/src/test/resources/config/application.yaml b/main/src/test/resources/config/application.yaml new file mode 100644 index 00000000..1444a7d2 --- /dev/null +++ b/main/src/test/resources/config/application.yaml @@ -0,0 +1,81 @@ +spring: + security: + user: + name: policyadmin + password: zb!XztG34 + http: + converters: + preferred-json-mapper: gson + +server: + port: 6969 + +pap: + name: "PapGroup" + pdpParameters: + updateParameters: + maxRetryCount: 1 + maxWaitMs: 3000 + stateChangeParameters: + maxRetryCount: 1 + maxWaitMs: 3000 + heartBeatMs: 6000 + maxMessageAgeMs: 20000 + databaseProviderParameters: + name: PolicyModelsProviderParameters + implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl + databaseDriver: org.h2.Driver + databaseUrl: jdbc:h2:mem:testdb0 + databaseUser: policy + databasePassword: UDAxaWNZ + persistenceUnit: ToscaConceptTest + savePdpStatisticsInDb: true + topicParameterGroup: + topicSources: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: noop + - topic: POLICY-HEARTBEAT + effectiveTopic: POLICY-PDP-PAP + consumerGroup: policy-pap + servers: + - message-router + topicCommInfrastructure: noop + topicSinks: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: noop + - topic: POLICY-NOTIFICATION + servers: + - message-router + topicCommInfrastructure: noop + healthCheckRestClientParameters: + - clientName: api + hostname: policy-api + port: 6969 + userName: policyadmin + password: zb!XztG34 + useHttps: true + basePath: policy/api/v1/healthcheck + - clientName: distribution + hostname: policy-distribution + port: 6969 + userName: healthcheck + password: zb!XztG34 + useHttps: true + basePath: healthcheck + - clientName: dmaap + hostname: message-router + port: 3905 + useHttps: true + basePath: topics + +management: + endpoints: + web: + base-path: / + exposure: + include: health, metrics, prometheus + path-mapping.prometheus: metrics -- cgit 1.2.3-korg