diff options
Diffstat (limited to 'main')
31 files changed, 546 insertions, 576 deletions
diff --git a/main/pom.xml b/main/pom.xml index a5df6928..f6b0595d 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -26,7 +26,7 @@ <parent> <groupId>org.onap.policy.xacml-pdp</groupId> <artifactId>policy-xacml-pdp</artifactId> - <version>4.0.0-SNAPSHOT</version> + <version>4.0.1-SNAPSHOT</version> </parent> <artifactId>xacml-main</artifactId> @@ -135,11 +135,6 @@ <scope>test</scope> </dependency> <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <scope>test</scope> - </dependency> - <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> diff --git a/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java b/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java index a00eba90..b6801d82 100644 --- a/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java +++ b/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,8 +93,8 @@ public class XacmlPdpUpdatePublisher { } catch (XacmlApplicationException e) { // Failed to load policy, return error(s) to PAP LOGGER.error("Failed to load policy: {}", policy, e); - errorMessage.append("Failed to load policy: " + policy + ": " - + e.getMessage() + XacmlPolicyUtils.LINE_SEPARATOR); + errorMessage.append("Failed to load policy: ").append(policy).append(": ").append(e.getMessage()) + .append(XacmlPolicyUtils.LINE_SEPARATOR); stats.updateDeployFailureCount(); } } diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java index 996d2276..fd84c9ba 100644 --- a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,6 +52,7 @@ public class XacmlPdpApplicationManager { private final ServiceLoader<XacmlApplicationServiceProvider> applicationLoader; private final Map<String, XacmlApplicationServiceProvider> providerActionMap = new HashMap<>(); + @Getter private final List<ToscaConceptIdentifier> toscaPolicyTypeIdents = new ArrayList<>(); private final Map<ToscaPolicy, XacmlApplicationServiceProvider> mapLoadedPolicies = new HashMap<>(); @@ -89,7 +90,7 @@ public class XacmlPdpApplicationManager { // var applicationInitialized = false; // - // Have it initialize at a path + // Have it initialized at a path // try { initializeApplicationPath(Paths.get(applicationParameters.getApplicationPath()), application, @@ -148,15 +149,11 @@ public class XacmlPdpApplicationManager { */ public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers() { // - // converting map to return List of ToscaPolicyIdentiers + // converting map to return List of ToscaPolicyIdentifiers // return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList()); } - public List<ToscaConceptIdentifier> getToscaPolicyTypeIdents() { - return toscaPolicyTypeIdents; - } - /** * Finds the appropriate application and removes the policy. * diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml index c2d7d078..d9bb55a5 100644 --- a/main/src/main/resources/META-INF/persistence.xml +++ b/main/src/main/resources/META-INF/persistence.xml @@ -4,7 +4,7 @@ ONAP ================================================================================ Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - Modifications Copyright (C) 2023 Nordix Foundation. + Modifications Copyright (C) 2023-2024 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,17 +20,15 @@ ============LICENSE_END========================================================= --> -<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> - +<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd"> <persistence-unit name="OperationsHistoryPU" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - + <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>org.onap.policy.guard.OperationsHistory</class> - <properties> - <property name="jakarta.persistence.schema-generation.database.action" value="create" /> - <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/> - <property name="hibernate.show_sql" value="false" /> + <property name="jakarta.persistence.schema-generation.database.action" value="none"/> + <property name="hibernate.show_sql" value="false"/> </properties> </persistence-unit> diff --git a/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java index 89312cf5..d2baff20 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019,2023 Nordix Foundation. + * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,10 +37,10 @@ import java.security.SecureRandom; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLContext; 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.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.common.utils.security.SelfSignedKeyStore; @@ -108,7 +108,7 @@ public class CommonRest { * * @throws Exception if an error occurs */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { System.setProperty("javax.net.ssl.keyStore", new SelfSignedKeyStore().getKeystoreName()); System.setProperty("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD); @@ -132,7 +132,7 @@ public class CommonRest { /** * Stops the "Main". */ - @AfterClass + @AfterAll public static void tearDownAfterClass() { stopMain(); } @@ -140,7 +140,7 @@ public class CommonRest { /** * Resets the statistics. */ - @Before + @BeforeEach public void setUp() { activatorWasAlive = XacmlPdpActivator.getCurrent().isAlive(); XacmlPdpStatisticsManager.getCurrent().resetAllStatistics(); @@ -149,7 +149,7 @@ public class CommonRest { /** * Restores the "alive" status of the activator. */ - @After + @AfterEach public void tearDown() { markActivator(activatorWasAlive); } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java index 4dd02c62..e2d7d0dd 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +23,15 @@ package org.onap.policy.pdpx.main; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; -public class PolicyXacmlPdpExceptionTest { +class PolicyXacmlPdpExceptionTest { @Test - public void test() { + void test() { assertEquals(2, new ExceptionsTester().test(PolicyXacmlPdpException.class)); } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java index 80e69747..d1cc98d5 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +23,15 @@ package org.onap.policy.pdpx.main; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; -public class PolicyXacmlPdpRuntimeExceptionTest { +class PolicyXacmlPdpRuntimeExceptionTest { @Test - public void test() { + void test() { assertEquals(2, new ExceptionsTester().test(PolicyXacmlPdpRuntimeException.class)); } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java b/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java index 62c90f54..6479b6e7 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2023 Bell Canada. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,20 +22,20 @@ package org.onap.policy.pdpx.main; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.models.pdp.concepts.PdpResponseDetails; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpStatus; @@ -46,8 +46,8 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager; import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator; -@RunWith(MockitoJUnitRunner.class) -public class XacmlStateTest { +@ExtendWith(MockitoExtension.class) +class XacmlStateTest { private static final String PDP_TYPE = "xacml-flavor"; private static final String GROUP = "my-group"; private static final String SUBGROUP = "my-subgroup"; @@ -66,21 +66,21 @@ public class XacmlStateTest { /** * Initializes objects, including the state. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { pdpName = XacmlState.PDP_NAME; XacmlPdpActivator.setCurrent(act); state = new XacmlState(appmgr, GROUP, PDP_TYPE); } - @AfterClass - public static void tearDownAfterClass() { + @AfterAll + static void tearDownAfterClass() { XacmlPdpActivator.setCurrent(null); } @Test - public void testShouldHandle() { + void testShouldHandle() { PdpUpdate msg = new PdpUpdate(); assertFalse(state.shouldHandle(msg)); @@ -89,7 +89,7 @@ public class XacmlStateTest { } @Test - public void testGenHeartbeat() { + void testGenHeartbeat() { // not healthy PdpStatus status = state.genHeartbeat(); assertEquals(PdpHealthStatus.NOT_HEALTHY, status.getHealthy()); @@ -107,7 +107,7 @@ public class XacmlStateTest { } @Test - public void testUpdateInternalStatePdpStateChange() { + void testUpdateInternalStatePdpStateChange() { PdpStateChange req = new PdpStateChange(); req.setName(pdpName); req.setPdpGroup("wrong-pdp-group"); @@ -139,7 +139,7 @@ public class XacmlStateTest { } @Test - public void testUpdateInternalStatePdpUpdate() { + void testUpdateInternalStatePdpUpdate() { PdpUpdate req = new PdpUpdate(); req.setPdpGroup("wrong-pdp-group"); req.setPdpSubgroup(SUBGROUP); @@ -164,7 +164,7 @@ public class XacmlStateTest { } @Test - public void testTerminatePdpMessage() { + void testTerminatePdpMessage() { PdpStatus status = state.terminatePdpMessage(); assertEquals(PdpState.TERMINATED, status.getState()); } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java index 51689584..29dc10e7 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +22,15 @@ package org.onap.policy.pdpx.main.comm; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.LinkedList; @@ -37,19 +38,19 @@ import java.util.Queue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.event.comm.client.BidirectionalTopicClient; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.pdpx.main.XacmlState; -@RunWith(MockitoJUnitRunner.class) -public class XacmlPdpHearbeatPublisherTest { +@ExtendWith(MockitoExtension.class) +class XacmlPdpHearbeatPublisherTest { private static final long INTERVAL1 = 1000L; private static final long INTERVAL2 = 2000L; @@ -83,23 +84,24 @@ public class XacmlPdpHearbeatPublisherTest { /** * Initializes objects, including the publisher. */ - @Before - public void setUp() { - when(sink.getTopic()).thenReturn("my-topic"); - when(checker.getSink()).thenReturn(sink); - when(checker.isReady()).thenReturn(true); - when(state.genHeartbeat()).thenReturn(status); + @BeforeEach + void setUp() { + lenient().when(sink.getTopic()).thenReturn("my-topic"); + lenient().when(checker.getSink()).thenReturn(sink); + lenient().when(checker.isReady()).thenReturn(true); + lenient().when(state.genHeartbeat()).thenReturn(status); status = new PdpStatus(); timers = new LinkedList<>(Arrays.asList(timer1, timer2)); - when(executor.scheduleWithFixedDelay(any(), anyLong(), anyLong(), any())).thenAnswer(args -> timers.remove()); + lenient().when(executor.scheduleWithFixedDelay(any(), anyLong(), anyLong(), any())) + .thenAnswer(args -> timers.remove()); publisher = new MyPublisher(checker, 10, state); } @Test - public void testRun() { + void testRun() { publisher.run(); verify(state).genHeartbeat(); @@ -110,7 +112,7 @@ public class XacmlPdpHearbeatPublisherTest { * Tests the run() method when the probe is disabled. */ @Test - public void testRunNoProbe() throws CoderException { + void testRunNoProbe() throws CoderException { publisher = new MyPublisher(checker, 0, state); publisher.run(); @@ -126,24 +128,24 @@ public class XacmlPdpHearbeatPublisherTest { * Tests the run() method when the topic is not ready, and then becomes ready. */ @Test - public void testRunNotReady() throws CoderException { + void testRunNotReady() throws CoderException { // not ready yet - when(checker.isReady()).thenReturn(false); - when(checker.awaitReady(any(), anyLong())).thenReturn(false); + lenient().when(checker.isReady()).thenReturn(false); + lenient().when(checker.awaitReady(any(), anyLong())).thenReturn(false); publisher.run(); verify(state, never()).genHeartbeat(); verify(checker, never()).send(any()); // isReady is still false, but awaitReady is now true - should generate heartbeat - when(checker.awaitReady(any(), anyLong())).thenReturn(true); + lenient().when(checker.awaitReady(any(), anyLong())).thenReturn(true); publisher.run(); verify(state).genHeartbeat(); verify(checker).send(any()); // now isReady is true, too - should not rerun awaitReady - when(checker.isReady()).thenReturn(true); + lenient().when(checker.isReady()).thenReturn(true); publisher.run(); verify(state, times(2)).genHeartbeat(); @@ -155,11 +157,11 @@ public class XacmlPdpHearbeatPublisherTest { * Tests the run() method when the checker throws an exception. */ @Test - public void testRunCheckerEx() throws CoderException { + void testRunCheckerEx() throws CoderException { // force it to call awaitReady - when(checker.isReady()).thenReturn(false); + lenient().when(checker.isReady()).thenReturn(false); - when(checker.awaitReady(any(), anyLong())) + lenient().when(checker.awaitReady(any(), anyLong())) .thenThrow(new CoderException("expected exception")) .thenReturn(true); @@ -175,7 +177,7 @@ public class XacmlPdpHearbeatPublisherTest { } @Test - public void testTerminate() { + void testTerminate() { // not yet started publisher.terminate(); @@ -198,7 +200,7 @@ public class XacmlPdpHearbeatPublisherTest { } @Test - public void testRestart() { + void testRestart() { // not started yet - should only update the interval publisher.restart(INTERVAL1); @@ -231,11 +233,11 @@ public class XacmlPdpHearbeatPublisherTest { } @Test - public void testStart() { + void testStart() { publisher.start(); verify(executor).scheduleWithFixedDelay(publisher, 0, XacmlPdpHearbeatPublisher.DEFAULT_HB_INTERVAL_MS, - TimeUnit.MILLISECONDS); + TimeUnit.MILLISECONDS); // repeat - nothing more should happen publisher.start(); @@ -244,7 +246,7 @@ public class XacmlPdpHearbeatPublisherTest { } @Test - public void testMakeTimerThread() { + void testMakeTimerThread() { // create a plain listener to test the "real" makeTimer() method publisher = new XacmlPdpHearbeatPublisher(checker, 1, state); @@ -257,7 +259,7 @@ public class XacmlPdpHearbeatPublisherTest { private class MyPublisher extends XacmlPdpHearbeatPublisher { - public MyPublisher(BidirectionalTopicClient topicChecker, long probeHeartbeatTopicMs, XacmlState state) { + MyPublisher(BidirectionalTopicClient topicChecker, long probeHeartbeatTopicMs, XacmlState state) { super(topicChecker, probeHeartbeatTopicMs, state); } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java index 9f4d80bc..3d3ed864 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,17 +24,16 @@ package org.onap.policy.pdpx.main.comm; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; -import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException; import org.onap.policy.models.pdp.concepts.PdpStatus; -@RunWith(MockitoJUnitRunner.class) -public class XacmlPdpPapRegistrationTest { +@ExtendWith(MockitoExtension.class) +class XacmlPdpPapRegistrationTest { @Mock private TopicSinkClient client; @@ -46,22 +46,22 @@ public class XacmlPdpPapRegistrationTest { /** * Initializes objects, including the registration object. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { when(client.send(status)).thenReturn(true); reg = new XacmlPdpPapRegistration(client); } @Test - public void testPdpRegistration_SendOk() throws TopicSinkClientException { + void testPdpRegistration_SendOk() { assertThatCode(() -> reg.pdpRegistration(status) ).doesNotThrowAnyException(); } @Test - public void testPdpRegistration_SendFail() throws TopicSinkClientException { + void testPdpRegistration_SendFail() { when(client.send(status)).thenReturn(false); assertThatCode(() -> reg.pdpRegistration(status) @@ -69,7 +69,7 @@ public class XacmlPdpPapRegistrationTest { } @Test - public void testPdpRegistration_SendEx() throws TopicSinkClientException { + void testPdpRegistration_SendEx() { when(client.send(status)).thenThrow(new IllegalStateException()); assertThatCode(() -> reg.pdpRegistration(status) diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java index 872bec15..0a10eb7a 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,22 +21,21 @@ package org.onap.policy.pdpx.main.comm; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -51,8 +51,8 @@ import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager; /** * Initializes objects, including the publisher. */ -@RunWith(MockitoJUnitRunner.class) -public class XacmlPdpUpdatePublisherTest { +@ExtendWith(MockitoExtension.class) +class XacmlPdpUpdatePublisherTest { private static final int NEW_COUNT = 5; @@ -108,8 +108,8 @@ public class XacmlPdpUpdatePublisherTest { /** * Initializes objects, including the publisher. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { ToscaConceptIdentifier deployedId1 = new ToscaConceptIdentifier("deployed-1", "1.0.0"); ToscaConceptIdentifier deployedId2 = new ToscaConceptIdentifier("deployed-2", "1.0.0"); ToscaConceptIdentifier deployedId4 = new ToscaConceptIdentifier("deployed-4", "1.0.0"); @@ -117,15 +117,15 @@ public class XacmlPdpUpdatePublisherTest { ToscaConceptIdentifier addedId1 = new ToscaConceptIdentifier("added-1", "1.0.0"); ToscaConceptIdentifier addedId2 = new ToscaConceptIdentifier("added-2", "1.0.0"); - when(deployed1.getIdentifier()).thenReturn(deployedId1); - when(deployed2.getIdentifier()).thenReturn(deployedId2); - when(deployed3.getIdentifier()).thenReturn(new ToscaConceptIdentifier("deployed-3", "1.0.0")); - when(deployed4.getIdentifier()).thenReturn(deployedId4); - when(deployed5.getIdentifier()).thenReturn(deployedId5); - when(added1.getIdentifier()).thenReturn(addedId1); - when(added2.getIdentifier()).thenReturn(addedId2); - when(failPolicy1.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-1", "1.0.0")); - when(failPolicy2.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-2", "1.0.0")); + lenient().when(deployed1.getIdentifier()).thenReturn(deployedId1); + lenient().when(deployed2.getIdentifier()).thenReturn(deployedId2); + lenient().when(deployed3.getIdentifier()).thenReturn(new ToscaConceptIdentifier("deployed-3", "1.0.0")); + lenient().when(deployed4.getIdentifier()).thenReturn(deployedId4); + lenient().when(deployed5.getIdentifier()).thenReturn(deployedId5); + lenient().when(added1.getIdentifier()).thenReturn(addedId1); + lenient().when(added2.getIdentifier()).thenReturn(addedId2); + lenient().when(failPolicy1.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-1", "1.0.0")); + lenient().when(failPolicy2.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-2", "1.0.0")); Map<ToscaPolicy, XacmlApplicationServiceProvider> deployedPolicies = new HashMap<>(); deployedPolicies.put(deployed1, null); @@ -133,22 +133,23 @@ public class XacmlPdpUpdatePublisherTest { deployedPolicies.put(deployed3, null); deployedPolicies.put(deployed4, null); deployedPolicies.put(deployed5, null); - when(appmgr.getToscaPolicies()).thenReturn(deployedPolicies); + lenient().when(appmgr.getToscaPolicies()).thenReturn(deployedPolicies); // update includes one overlap with existing and one overlap between the two - when(update.getPoliciesToBeDeployed()).thenReturn(List.of(added1, deployed2, deployed5, added2)); - when(update.getPoliciesToBeUndeployed()).thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4)); + lenient().when(update.getPoliciesToBeDeployed()).thenReturn(List.of(added1, deployed2, deployed5, added2)); + lenient().when(update.getPoliciesToBeUndeployed()) + .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4)); - when(failurePdpUpdate.getPoliciesToBeDeployed()) - .thenReturn(List.of(added1, deployed2, deployed5, failPolicy1, failPolicy2)); - when(failurePdpUpdate.getPoliciesToBeUndeployed()) - .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4)); + lenient().when(failurePdpUpdate.getPoliciesToBeDeployed()) + .thenReturn(List.of(added1, deployed2, deployed5, failPolicy1, failPolicy2)); + lenient().when(failurePdpUpdate.getPoliciesToBeUndeployed()) + .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4)); - when(appmgr.getPolicyCount()).thenReturn(NEW_COUNT); + lenient().when(appmgr.getPolicyCount()).thenReturn(NEW_COUNT); - when(state.updateInternalState(any(), any())).thenReturn(status); + lenient().when(state.updateInternalState(any(), any())).thenReturn(status); - when(client.send(any())).thenReturn(true); + lenient().when(client.send(any())).thenReturn(true); publisher = new XacmlPdpUpdatePublisher(client, state, appmgr); @@ -157,7 +158,7 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate() throws XacmlApplicationException { + void testHandlePdpUpdate() throws XacmlApplicationException { publisher.handlePdpUpdate(update); // two removed @@ -182,8 +183,8 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate_Deploy() throws XacmlApplicationException { - when(update.getPoliciesToBeUndeployed()).thenReturn(null); + void testHandlePdpUpdate_Deploy() throws XacmlApplicationException { + lenient().when(update.getPoliciesToBeUndeployed()).thenReturn(null); publisher.handlePdpUpdate(update); @@ -201,8 +202,8 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate_Undeploy() throws XacmlApplicationException { - when(update.getPoliciesToBeDeployed()).thenReturn(null); + void testHandlePdpUpdate_Undeploy() throws XacmlApplicationException { + lenient().when(update.getPoliciesToBeDeployed()).thenReturn(null); publisher.handlePdpUpdate(update); @@ -220,10 +221,10 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate_LoadPolicyFailed() throws XacmlApplicationException { + void testHandlePdpUpdate_LoadPolicyFailed() throws XacmlApplicationException { // Set loadPolicy to fail - doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy1); - doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy2); + lenient().doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy1); + lenient().doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy2); publisher.handlePdpUpdate(failurePdpUpdate); @@ -239,9 +240,9 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate_NullPolicies() throws XacmlApplicationException { - when(update.getPoliciesToBeDeployed()).thenReturn(null); - when(update.getPoliciesToBeUndeployed()).thenReturn(null); + void testHandlePdpUpdate_NullPolicies() throws XacmlApplicationException { + lenient().when(update.getPoliciesToBeDeployed()).thenReturn(null); + lenient().when(update.getPoliciesToBeUndeployed()).thenReturn(null); publisher.handlePdpUpdate(update); @@ -255,9 +256,9 @@ public class XacmlPdpUpdatePublisherTest { } @Test - public void testHandlePdpUpdate_SendFail() { + void testHandlePdpUpdate_SendFail() { - when(client.send(any())).thenReturn(false); + lenient().when(client.send(any())).thenReturn(false); publisher.handlePdpUpdate(update); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java index dbc065a1..f646ef29 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,23 +22,23 @@ package org.onap.policy.pdpx.main.comm.listeners; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.pdpx.main.XacmlState; -@RunWith(MockitoJUnitRunner.class) -public class XacmlPdpStateChangeListenerTest { +@ExtendWith(MockitoExtension.class) +class XacmlPdpStateChangeListenerTest { private static final String TOPIC = "my-topic"; @Mock @@ -57,19 +58,19 @@ public class XacmlPdpStateChangeListenerTest { /** * Initializes objects, including the listener. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { listener = new XacmlPdpStateChangeListener(client, state); - when(state.shouldHandle(change)).thenReturn(true); - when(state.updateInternalState(change)).thenReturn(status); + lenient().when(state.shouldHandle(change)).thenReturn(true); + lenient().when(state.updateInternalState(change)).thenReturn(status); - when(client.send(status)).thenReturn(true); + lenient().when(client.send(status)).thenReturn(true); } @Test - public void testOnTopicEvent_Unhandled() { - when(state.shouldHandle(change)).thenReturn(false); + void testOnTopicEvent_Unhandled() { + lenient().when(state.shouldHandle(change)).thenReturn(false); listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change); verify(state, never()).updateInternalState(any(PdpStateChange.class)); @@ -77,8 +78,8 @@ public class XacmlPdpStateChangeListenerTest { } @Test - public void testOnTopicEvent_SendFailed() { - when(client.send(status)).thenReturn(false); + void testOnTopicEvent_SendFailed() { + lenient().when(client.send(status)).thenReturn(false); listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change); @@ -87,7 +88,7 @@ public class XacmlPdpStateChangeListenerTest { } @Test - public void testOnTopicEvent_SendOk() { + void testOnTopicEvent_SendOk() { listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change); verify(state).updateInternalState(change); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java index 7a9dc4d7..7d23b742 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,18 @@ package org.onap.policy.pdpx.main.comm.listeners; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -43,8 +42,8 @@ import org.onap.policy.pdpx.main.comm.XacmlPdpUpdatePublisher; import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class XacmlPdpUpdateListenerTest { +@ExtendWith(MockitoExtension.class) +class XacmlPdpUpdateListenerTest { private static final String EXPECTED_EXCEPTION = "expected exception"; private static final String TOPIC = "my-topic"; private static final long HB_INTERVAL = 100L; @@ -71,19 +70,19 @@ public class XacmlPdpUpdateListenerTest { /** * Initializes objects, including the listener. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { listener = new MyListener(client, state, heartbeat, appmgr); update = new PdpUpdate(); - when(state.shouldHandle(update)).thenReturn(true); + lenient().when(state.shouldHandle(update)).thenReturn(true); update.setPdpHeartbeatIntervalMs(HB_INTERVAL); } @Test - public void testOnTopicEvent_Unhandled() { - when(state.shouldHandle(update)).thenReturn(false); + void testOnTopicEvent_Unhandled() { + lenient().when(state.shouldHandle(update)).thenReturn(false); listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update); verify(publisher, never()).handlePdpUpdate(any()); @@ -91,7 +90,7 @@ public class XacmlPdpUpdateListenerTest { } @Test - public void testOnTopicEvent_SendOk() { + void testOnTopicEvent_SendOk() { listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update); verify(publisher).handlePdpUpdate(update); @@ -99,8 +98,8 @@ public class XacmlPdpUpdateListenerTest { } @Test - public void testOnTopicEvent_SendEx() { - doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(publisher).handlePdpUpdate(update); + void testOnTopicEvent_SendEx() { + lenient().doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(publisher).handlePdpUpdate(update); listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update); @@ -109,7 +108,7 @@ public class XacmlPdpUpdateListenerTest { } @Test - public void testMakePublisher() { + void testMakePublisher() { // create a plain listener to test the "real" makePublisher() method listener = new XacmlPdpUpdateListener(client, state, heartbeat, appmgr); assertNotNull(ReflectionTestUtils.getField(listener, "publisher")); @@ -117,14 +116,14 @@ public class XacmlPdpUpdateListenerTest { private class MyListener extends XacmlPdpUpdateListener { - public MyListener(TopicSinkClient client, XacmlState state, XacmlPdpHearbeatPublisher heartbeat, - XacmlPdpApplicationManager appManager) { + MyListener(TopicSinkClient client, XacmlState state, XacmlPdpHearbeatPublisher heartbeat, + XacmlPdpApplicationManager appManager) { super(client, state, heartbeat, appManager); } @Override protected XacmlPdpUpdatePublisher makePublisher(TopicSinkClient client, XacmlState state, - XacmlPdpApplicationManager appManager) { + XacmlPdpApplicationManager appManager) { return publisher; } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java index f39061a6..614f9bee 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019, 2023 Nordix Foundation. + * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,17 +23,16 @@ package org.onap.policy.pdpx.main.parameters; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.io.IOException; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import java.nio.file.Path; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; @@ -41,35 +40,34 @@ import org.onap.policy.common.parameters.ValidationResult; /** * Class to perform unit test of XacmlPdpParameterGroup. - * */ -public class TestXacmlPdpParameterGroup { +class TestXacmlPdpParameterGroup { private static File applicationPath; private static final CommonTestData testData = new CommonTestData(); - @ClassRule - public static final TemporaryFolder applicationFolder = new TemporaryFolder(); + @TempDir + static Path applicationFolder; - @Before - public void setupPath() throws IOException { - applicationPath = applicationFolder.newFolder(); + @BeforeEach + void setupPath() { + applicationPath = applicationFolder.toFile(); } @Test - public void testXacmlPdpParameterGroup() throws IOException { + void testXacmlPdpParameterGroup() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, - CommonTestData.PDPX_GROUP, "flavor", restServerParameters, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, + CommonTestData.PDPX_GROUP, "flavor", restServerParameters, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertThat(validationResult.getResult()).isNull(); assertTrue(validationResult.isValid()); @@ -84,18 +82,18 @@ public class TestXacmlPdpParameterGroup { } @Test - public void testXacmlPdpParameterGroup_NullParameterGroupName() { + void testXacmlPdpParameterGroup_NullParameterGroupName() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup(null, CommonTestData.PDPX_GROUP, - null, restServerParameters, policyApiParameters, topicParameterGroup, xacmlApplicationParameters); + null, restServerParameters, policyApiParameters, topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertNull(pdpxParameters.getName()); @@ -103,19 +101,19 @@ public class TestXacmlPdpParameterGroup { } @Test - public void testXacmlPdpParameterGroup_EmptyParameterGroupName() { + void testXacmlPdpParameterGroup_EmptyParameterGroupName() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup("", CommonTestData.PDPX_GROUP, - CommonTestData.PDPX_TYPE, restServerParameters, policyApiParameters, topicParameterGroup, - xacmlApplicationParameters); + CommonTestData.PDPX_TYPE, restServerParameters, policyApiParameters, topicParameterGroup, + xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertEquals("", pdpxParameters.getName()); @@ -123,19 +121,19 @@ public class TestXacmlPdpParameterGroup { } @Test - public void testXacmlPdpParameterGroup_NullPdpGroup() { + void testXacmlPdpParameterGroup_NullPdpGroup() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, null, null, restServerParameters, - policyApiParameters, topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, null, null, restServerParameters, + policyApiParameters, topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertNull(pdpxParameters.getPdpGroup()); @@ -143,19 +141,19 @@ public class TestXacmlPdpParameterGroup { } @Test - public void testXacmlPdpParameterGroup_EmptyPdpGroup() { + void testXacmlPdpParameterGroup_EmptyPdpGroup() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, "", null, restServerParameters, - policyApiParameters, topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, "", null, restServerParameters, + policyApiParameters, topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertEquals("", pdpxParameters.getPdpGroup()); @@ -163,80 +161,80 @@ public class TestXacmlPdpParameterGroup { } @Test - public void testXacmlPdpParameterGroup_EmptyRestServerParameters() { + void testXacmlPdpParameterGroup_EmptyRestServerParameters() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(true), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, - null, restServerParameters, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, + null, restServerParameters, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"RestServerParameters\""); } @Test - public void testXacmlPdpParameterGroup_EmptyPolicyApiParameters() { + void testXacmlPdpParameterGroup_EmptyPolicyApiParameters() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(true), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(true), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, - null, restServerParameters, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, + null, restServerParameters, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"policyApiParameters\""); } @Test - public void testXacmlPdpParameterGroup_EmptyTopicParameterGroup() { + void testXacmlPdpParameterGroup_EmptyTopicParameterGroup() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(true), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, - null, restServerParameters, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, + null, restServerParameters, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"TopicParameterGroup\""); } @Test - public void testXacmlPdpParameterGroup_EmptyApplicationParameterGroup() { + void testXacmlPdpParameterGroup_EmptyApplicationParameterGroup() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); final RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); final TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(true, - applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(true, + applicationPath.getAbsolutePath()), XacmlApplicationParameters.class); final XacmlPdpParameterGroup pdpxParameters = - new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, - null, restServerParameters, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP, + null, restServerParameters, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final ValidationResult validationResult = pdpxParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"XacmlApplicationParameters\""); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java index 00e95db7..d64c39fa 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation + * Modifications Copyright (C) 2020, 2024 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,88 +23,87 @@ package org.onap.policy.pdpx.main.parameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.pdpx.main.PolicyXacmlPdpException; import org.onap.policy.pdpx.main.startstop.XacmlPdpCommandLineArguments; /** * Class to perform unit test of XacmlPdpParameterHandler. - * */ -public class TestXacmlPdpParameterHandler { +class TestXacmlPdpParameterHandler { @Test - public void testParameterHandlerNoParameterFile() throws PolicyXacmlPdpException { + void testParameterHandlerNoParameterFile() throws PolicyXacmlPdpException { final String[] noArgumentString = {"-c", "parameters/NoParameterFile.json"}; final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments(); noArguments.parse(noArgumentString); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments)) - .isInstanceOf(PolicyXacmlPdpException.class); + .isInstanceOf(PolicyXacmlPdpException.class); } @Test - public void testParameterHandlerEmptyParameters() throws PolicyXacmlPdpException { + void testParameterHandlerEmptyParameters() throws PolicyXacmlPdpException { final String[] emptyArgumentString = {"-c", "parameters/EmptyParameters.json"}; final XacmlPdpCommandLineArguments emptyArguments = new XacmlPdpCommandLineArguments(); emptyArguments.parse(emptyArgumentString); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(emptyArguments)) - .hasMessage("no parameters found in \"parameters/EmptyParameters.json\""); + .hasMessage("no parameters found in \"parameters/EmptyParameters.json\""); } @Test - public void testParameterHandlerBadParameters() throws PolicyXacmlPdpException { + void testParameterHandlerBadParameters() throws PolicyXacmlPdpException { final String[] badArgumentString = {"-c", "parameters/BadParameters.json"}; final XacmlPdpCommandLineArguments badArguments = new XacmlPdpCommandLineArguments(); badArguments.parse(badArgumentString); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(badArguments)) - .hasMessageContaining("error reading parameters from", "parameters/BadParameters.json", - "JsonSyntaxException", "java.lang.IllegalStateException", - "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); + .hasMessageContaining("error reading parameters from", "parameters/BadParameters.json", + "JsonSyntaxException", "java.lang.IllegalStateException", + "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); } @Test - public void testParameterHandlerInvalidParameters() throws PolicyXacmlPdpException { + void testParameterHandlerInvalidParameters() throws PolicyXacmlPdpException { final String[] invalidArgumentString = {"-c", "parameters/InvalidParameters.json"}; final XacmlPdpCommandLineArguments invalidArguments = new XacmlPdpCommandLineArguments(); invalidArguments.parse(invalidArgumentString); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(invalidArguments)) - .hasMessageContaining("error reading parameters from", "parameters/InvalidParameters.json", - "JsonSyntaxException", "java.lang.IllegalStateException", - "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); + .hasMessageContaining("error reading parameters from", "parameters/InvalidParameters.json", + "JsonSyntaxException", "java.lang.IllegalStateException", + "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); } @Test - public void testParameterHandlerNoParameters() throws PolicyXacmlPdpException { + void testParameterHandlerNoParameters() throws PolicyXacmlPdpException { final String[] noArgumentString = {"-c", "parameters/NoParameters.json"}; final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments(); noArguments.parse(noArgumentString); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments)) - .hasMessageContaining("validation error(s) on parameters from \"parameters/NoParameters.json\"", - "\"XacmlPdpParameterGroup\" INVALID, item has status INVALID", - "\"name\" value \"null\" INVALID, is null", - "\"pdpGroup\" value \"null\" INVALID, is null", - "\"pdpType\" value \"null\" INVALID, is null", - "\"applicationPath\" value \"null\" INVALID, is null"); + .hasMessageContaining("validation error(s) on parameters from \"parameters/NoParameters.json\"", + "\"XacmlPdpParameterGroup\" INVALID, item has status INVALID", + "\"name\" value \"null\" INVALID, is null", + "\"pdpGroup\" value \"null\" INVALID, is null", + "\"pdpType\" value \"null\" INVALID, is null", + "\"applicationPath\" value \"null\" INVALID, is null"); } @Test - public void testParameterHandlerMinumumParameters() throws PolicyXacmlPdpException { + void testParameterHandlerMinumumParameters() throws PolicyXacmlPdpException { final String[] minArgumentString = {"-c", "parameters/MinimumParameters.json"}; final XacmlPdpCommandLineArguments minArguments = new XacmlPdpCommandLineArguments(); @@ -117,7 +116,7 @@ public class TestXacmlPdpParameterHandler { } @Test - public void testXacmlPdpParameterGroup() throws PolicyXacmlPdpException { + void testXacmlPdpParameterGroup() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); @@ -130,31 +129,31 @@ public class TestXacmlPdpParameterHandler { } @Test - public void testXacmlPdpParameterGroup_Invalid() throws PolicyXacmlPdpException { + void testXacmlPdpParameterGroup_Invalid() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); arguments.parse(xacmlPdpConfigParameters); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining( - "\"name\" value \" \" INVALID, is blank"); + "\"name\" value \" \" INVALID, is blank"); xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_InvalidPdpGroup.json"; arguments.parse(xacmlPdpConfigParameters); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining( - "\"pdpGroup\" value \" \" INVALID, is blank"); + "\"pdpGroup\" value \" \" INVALID, is blank"); xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_InvalidPdpType.json"; arguments.parse(xacmlPdpConfigParameters); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining( - "\"pdpType\" value \"\" INVALID, is blank"); + "\"pdpType\" value \"\" INVALID, is blank"); } @Test - public void testXacmlPdpParameterGroup_InvalidRestServerParameters() throws PolicyXacmlPdpException, IOException { + void testXacmlPdpParameterGroup_InvalidRestServerParameters() throws PolicyXacmlPdpException, IOException { final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json"}; @@ -162,15 +161,15 @@ public class TestXacmlPdpParameterHandler { arguments.parse(xacmlPdpConfigParameters); new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt"))); + Paths.get("src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt"))); assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)) - .hasMessageContaining("validation error(s) on parameters from " - + "\"parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json\""); + .hasMessageContaining("validation error(s) on parameters from " + + "\"parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json\""); } @Test - public void testXacmlPdpParameterGroup_Exclusions() throws PolicyXacmlPdpException { + void testXacmlPdpParameterGroup_Exclusions() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_Exclusions.json"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); @@ -184,7 +183,7 @@ public class TestXacmlPdpParameterHandler { } @Test - public void testXacmlPdpVersion() throws PolicyXacmlPdpException { + void testXacmlPdpVersion() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-v"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); final String version = arguments.parse(xacmlPdpConfigParameters); @@ -192,7 +191,7 @@ public class TestXacmlPdpParameterHandler { } @Test - public void testXacmlPdpHelp() throws PolicyXacmlPdpException { + void testXacmlPdpHelp() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-h"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); final String help = arguments.parse(xacmlPdpConfigParameters); @@ -200,12 +199,12 @@ public class TestXacmlPdpParameterHandler { } @Test - public void testXacmlPdpInvalidOption() { + void testXacmlPdpInvalidOption() { final String[] xacmlPdpConfigParameters = {"-d"}; final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); assertThatThrownBy(() -> arguments.parse(xacmlPdpConfigParameters) ).isInstanceOf(PolicyXacmlPdpException.class) - .hasMessageContaining("invalid command line arguments specified"); + .hasMessageContaining("invalid command line arguments specified"); } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java index 5dddec30..5bfc4372 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020,2023 Nordix Foundation + * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ package org.onap.policy.pdpx.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.core.MediaType; @@ -42,18 +42,15 @@ import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.onap.policy.common.endpoints.http.client.HttpClient; -import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.endpoints.http.client.internal.JerseyClient; import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; -import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.models.decisions.concepts.DecisionRequest; @@ -72,23 +69,21 @@ import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class TestAbbreviateDecisionResults { +class TestAbbreviateDecisionResults { private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class); private static int port; private static Main main; private static HttpClient client; - private static CommonTestData testData = new CommonTestData(); + private static final CommonTestData testData = new CommonTestData(); - private static Properties properties = new Properties(); + private static final Properties properties = new Properties(); private static File propertiesFile; private static XacmlApplicationServiceProvider service; - private static RestClientParameters policyApiParameters; - - @ClassRule - public static final TemporaryFolder appsFolder = new TemporaryFolder(); + @TempDir + static Path appsFolder; /** * BeforeClass setup environment. @@ -96,17 +91,15 @@ public class TestAbbreviateDecisionResults { * @throws IOException Cannot create temp apps folder * @throws Exception exception if service does not start */ - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + static void beforeClass() throws Exception { port = NetworkUtil.allocPort(); // // Copy test directory over of the application directories // Path src = Paths.get("src/test/resources/apps"); - File apps = appsFolder.newFolder("apps"); - Files.walk(src).forEach(source -> { - copy(source, apps.toPath().resolve(src.relativize(source))); - }); + File apps = appsFolder.resolve("apps").toFile(); + Files.walk(src).forEach(source -> copy(source, apps.toPath().resolve(src.relativize(source)))); // Start the Monitoring Application startXacmlApplicationService(apps); @@ -116,18 +109,19 @@ public class TestAbbreviateDecisionResults { // Create parameters for XacmlPdPService RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port), - RestServerParameters.class); - policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + RestServerParameters.class); + RestClientParameters policyApiParameters = + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false), - TopicParameterGroup.class); + TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - apps.getAbsolutePath().toString()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + apps.getAbsolutePath()), XacmlApplicationParameters.class); XacmlPdpParameterGroup params = - new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters, + new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters, topicParameterGroup, xacmlApplicationParameters); StandardCoder gson = new StandardCoder(); - File fileParams = appsFolder.newFile("params.json"); + File fileParams = appsFolder.resolve("params.json").toFile(); String jsonParams = gson.encode(params); LOGGER.info("Creating new params: {}", jsonParams); Files.write(fileParams.toPath(), jsonParams.getBytes()); @@ -151,8 +145,8 @@ public class TestAbbreviateDecisionResults { /** * Clean up. */ - @AfterClass - public static void after() throws PolicyXacmlPdpException { + @AfterAll + static void after() { stopXacmlPdpService(main); client.shutdown(); } @@ -162,7 +156,7 @@ public class TestAbbreviateDecisionResults { * should have been removed from the response. */ @Test - public void testAbbreviateDecisionResult() throws HttpClientConfigException { + void testAbbreviateDecisionResult() { LOGGER.info("Running testAbbreviateDecisionResult"); @@ -192,19 +186,18 @@ public class TestAbbreviateDecisionResults { } private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException { - final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() }; - return new Main(XacmlPdpConfigParameters); + final String[] xacmlPdpConfigParameters = {"-c", params.getAbsolutePath()}; + return new Main(xacmlPdpConfigParameters); } - private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException { + private static void stopXacmlPdpService(final Main main) { main.shutdown(); } /** * Performs the POST request to Decision API. - * */ - private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException { + private DecisionResponse getDecision(DecisionRequest request) { Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON); Response response = client.post("", entityRequest, Collections.emptyMap()); @@ -215,10 +208,9 @@ public class TestAbbreviateDecisionResults { /** * Create HttpClient. - * */ private static HttpClient getNoAuthHttpClient() - throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException { + throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException { RestClientParameters clientParams = new RestClientParameters(); clientParams.setClientName("testName"); clientParams.setUseHttps(false); @@ -248,22 +240,22 @@ public class TestAbbreviateDecisionResults { * @param apps - the path to xacml.properties file */ private static void startXacmlApplicationService(File apps) - throws XacmlApplicationException, CoderException, IOException { + throws XacmlApplicationException, IOException { LOGGER.info("****** Starting Xacml Application Service ******"); // // Setup our temporary folder // XacmlPolicyUtils.FileCreator myCreator = (String filename) -> { new File(apps, "monitoring/" + filename).delete(); - return appsFolder.newFile("apps/monitoring/" + filename); + return appsFolder.resolve("apps/monitoring/" + filename).toFile(); }; propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents( - "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator); + "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator); // // Load XacmlApplicationServiceProvider service // ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader - .load(XacmlApplicationServiceProvider.class); + .load(XacmlApplicationServiceProvider.class); // // Look for our class instance and save it // diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java index 93d04ce0..9e2c9893 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019,2023 Nordix Foundation. + * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ package org.onap.policy.pdpx.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -36,16 +36,13 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; @@ -66,27 +63,28 @@ import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class TestDecision { +class TestDecision { private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class); private static int port; private static Main main; private static HttpClient client; - private static CommonTestData testData = new CommonTestData(); + private static final CommonTestData testData = new CommonTestData(); private static final String APPLICATION_XACML_XML = "application/xacml+xml"; private static final String APPLICATION_XACML_JSON = "application/xacml+json"; - @ClassRule - public static final TemporaryFolder appsFolder = new TemporaryFolder(); + @TempDir + static Path appsFolder; /** * BeforeClass setup environment. + * * @throws IOException Cannot create temp apps folder - * @throws Exception exception if service does not start + * @throws Exception exception if service does not start */ - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + static void beforeClass() throws Exception { System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog"); System.setProperty("org.eclipse.jetty.LEVEL", "OFF"); @@ -96,7 +94,7 @@ public class TestDecision { // Copy test directory over of the application directories // Path src = Paths.get("src/test/resources/apps"); - File apps = appsFolder.newFolder("apps"); + File apps = appsFolder.resolve("apps").toFile(); Files.walk(src).forEach(source -> { copy(source, apps.toPath().resolve(src.relativize(source))); }); @@ -106,17 +104,17 @@ public class TestDecision { RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port), RestServerParameters.class); RestClientParameters policyApiParameters = - testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); + testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class); TopicParameterGroup topicParameterGroup = - testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); + testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - apps.getAbsolutePath().toString()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + apps.getAbsolutePath()), XacmlApplicationParameters.class); XacmlPdpParameterGroup params = - new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters, - topicParameterGroup, xacmlApplicationParameters); + new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters, + topicParameterGroup, xacmlApplicationParameters); final Gson gson = new GsonBuilder().create(); - File fileParams = appsFolder.newFile("params.json"); + File fileParams = appsFolder.resolve("params.json").toFile(); String jsonParams = gson.toJson(params); LOGGER.info("Creating new params: {}", jsonParams); Files.write(fileParams.toPath(), jsonParams.getBytes()); @@ -137,14 +135,14 @@ public class TestDecision { client = getNoAuthHttpClient(); } - @AfterClass - public static void after() throws PolicyXacmlPdpException { + @AfterAll + static void after() { stopXacmlPdpService(main); client.shutdown(); } @Test - public void testDecision_UnsupportedAction() throws Exception { + void testDecision_UnsupportedAction() { LOGGER.info("Running test testDecision_UnsupportedAction"); DecisionRequest request = new DecisionRequest(); @@ -164,8 +162,7 @@ public class TestDecision { } @Test - public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException, - ClassNotFoundException { + void testDecision_Guard() { LOGGER.info("Running test testDecision_Guard"); DecisionRequest request = new DecisionRequest(); @@ -184,17 +181,17 @@ public class TestDecision { } @Test - public void testDecision_Native() throws IOException { + void testDecision_Native() throws IOException { LOGGER.info("Running test testDecision_Native"); String xmlRequestAsString = ResourceUtils.getResourceAsString( - "src/test/resources/decisions/decision.native.request.xml"); + "src/test/resources/decisions/decision.native.request.xml"); if (xmlRequestAsString == null) { throw new IOException("failed to read the xml request"); } String jsonRequestAsString = ResourceUtils.getResourceAsString( - "src/test/resources/decisions/decision.native.request.json"); + "src/test/resources/decisions/decision.native.request.json"); if (jsonRequestAsString == null) { throw new IOException("failed to read the json request"); } @@ -209,11 +206,11 @@ public class TestDecision { } private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException { - final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath()}; - return new Main(XacmlPdpConfigParameters); + final String[] xacmlPdpConfigParameters = {"-c", params.getAbsolutePath()}; + return new Main(xacmlPdpConfigParameters); } - private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException { + private static void stopXacmlPdpService(final Main main) { main.shutdown(); } @@ -246,10 +243,10 @@ public class TestDecision { private static HttpClient getNoAuthHttpClient() throws HttpClientConfigException { return HttpClientFactoryInstance.getClientFactory().build(RestClientParameters.builder() - .clientName("testDecisionClient") - .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port) - .basePath("policy/pdpx/v1") - .userName("healthcheck").password("zb!XztG34").managed(true).build()); + .clientName("testDecisionClient") + .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port) + .basePath("policy/pdpx/v1") + .userName("healthcheck").password("zb!XztG34").managed(true).build()); } private static void copy(Path source, Path dest) { diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java index 1b8411e5..e94830e6 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,13 +59,9 @@ public class TestGuardOverrideApplication extends GuardPdpApplication { @Override public boolean canSupportPolicyType(ToscaConceptIdentifier policyTypeId) { - boolean canSuper = super.canSupportPolicyType(policyTypeId); - if (canSuper) { - return canSuper; - } - if (MY_EXTRAGUARD_POLICY_TYPE.equals(policyTypeId.getName())) { + if (super.canSupportPolicyType(policyTypeId)) { return true; } - return false; + return MY_EXTRAGUARD_POLICY_TYPE.equals(policyTypeId.getName()); } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java index f774e022..ae9f6574 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java @@ -32,7 +32,7 @@ import org.onap.policy.pdpx.main.rest.model.StatisticsReport; * Class to perform unit testing of {@link StatisticsReport}. * */ -public class TestStatisticsReport { +class TestStatisticsReport { static StatisticsReport report; diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java index 2cac6dcc..6be2e7a0 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,12 @@ package org.onap.policy.pdpx.main.rest; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.ws.rs.client.Invocation; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.report.HealthCheckReport; import org.onap.policy.pdpx.main.CommonRest; import org.onap.policy.pdpx.main.XacmlState; @@ -35,10 +35,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Class to perform unit test of {@link XacmlPdpRestServer}. - * + * Class to perform unit test of {@link org.onap.policy.pdpx.main.startstop.XacmlPdpRestServer}. */ -public class TestXacmlPdpRestServer extends CommonRest { +class TestXacmlPdpRestServer extends CommonRest { private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpRestServer.class); private static final String NOT_ALIVE = "not alive"; @@ -51,16 +50,16 @@ public class TestXacmlPdpRestServer extends CommonRest { private int nupdates = 0; @Test - public void testHealthCheckSuccess() throws Exception { + void testHealthCheckSuccess() throws Exception { LOGGER.info("***************************** Running testHealthCheckSuccess *****************************"); final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); LOGGER.info("test1HealthCheckSuccess health report {}", report); - validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); + validateHealthCheckReport(true, 200, ALIVE, report); } @Test - public void testHealthCheckFailure() throws Exception { + void testHealthCheckFailure() throws Exception { LOGGER.info("***************************** Running testHealthCheckFailure *****************************"); markActivatorDead(); @@ -68,20 +67,20 @@ public class TestXacmlPdpRestServer extends CommonRest { final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); LOGGER.info("testHealthCheckFailure health report {}", report); - validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report); + validateHealthCheckReport(false, 500, NOT_ALIVE, report); } @Test - public void testHttpsHealthCheckSuccess() throws Exception { + void testHttpsHealthCheckSuccess() throws Exception { LOGGER.info("***************************** Running testHttpsHealthCheckSuccess *****************************"); final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); LOGGER.info("testHttpsHealthCheckSuccess health report {}", report); - validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); + validateHealthCheckReport(true, 200, ALIVE, report); } @Test - public void testStatistics_200() throws Exception { + void testStatistics_200() throws Exception { LOGGER.info("***************************** Running testStatistics_200 *****************************"); Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT); StatisticsReport report = invocationBuilder.get(StatisticsReport.class); @@ -95,7 +94,7 @@ public class TestXacmlPdpRestServer extends CommonRest { } @Test - public void testStatistics_500() throws Exception { + void testStatistics_500() throws Exception { LOGGER.info("***************************** Running testStatistics_500 *****************************"); markActivatorDead(); @@ -107,7 +106,7 @@ public class TestXacmlPdpRestServer extends CommonRest { } @Test - public void testHttpsStatistic() throws Exception { + void testHttpsStatistic() throws Exception { LOGGER.info("***************************** Running testHttpsStatistic *****************************"); final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT); final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); @@ -151,10 +150,10 @@ public class TestXacmlPdpRestServer extends CommonRest { assertEquals(decisionsMap, report.getApplicationMetrics()); } - private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code, - final String message, final HealthCheckReport report) { - assertEquals(name, report.getName()); - assertEquals(url, report.getUrl()); + private void validateHealthCheckReport(final boolean healthy, final int code, + final String message, final HealthCheckReport report) { + assertEquals(TestXacmlPdpRestServer.NAME, report.getName()); + assertEquals(TestXacmlPdpRestServer.SELF, report.getUrl()); assertEquals(healthy, report.isHealthy()); assertEquals(code, report.getCode()); assertEquals(message, report.getMessage()); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java index f72ae4f4..236e6fbc 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,15 +29,15 @@ import static org.mockito.Mockito.when; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class TestXacmlPdpServiceFilter { +@ExtendWith(MockitoExtension.class) +class TestXacmlPdpServiceFilter { // pick an arbitrary service private static final String PERM_SVC = XacmlPdpServiceFilter.PERMANENT_SERVICES.iterator().next(); @@ -56,8 +56,8 @@ public class TestXacmlPdpServiceFilter { /** * Initializes the fields. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { XacmlPdpServiceFilter.disableApi(); filterChain = (req, resp) -> { @@ -69,7 +69,7 @@ public class TestXacmlPdpServiceFilter { } @Test - public void testDoFilter() throws Exception { + void testDoFilter() throws Exception { XacmlPdpServiceFilter.enableApi(); lenient().when(request.getRequestURI()).thenReturn("/other"); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK); @@ -79,7 +79,7 @@ public class TestXacmlPdpServiceFilter { * Tests doFilter() when the API is disabled, but a permanent service is requested. */ @Test - public void testDoFilter_DisabledPermanentServiceReq() throws Exception { + void testDoFilter_DisabledPermanentServiceReq() throws Exception { XacmlPdpServiceFilter.disableApi(); when(request.getRequestURI()).thenReturn(PERM_SVC); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK); @@ -89,7 +89,7 @@ public class TestXacmlPdpServiceFilter { * Tests doFilter() when the API is disabled, but a permanent service is requested, with a leading slash. */ @Test - public void testDoFilter_DisabledPermanentServiceReqLeadingSlash() throws Exception { + void testDoFilter_DisabledPermanentServiceReqLeadingSlash() throws Exception { XacmlPdpServiceFilter.disableApi(); when(request.getRequestURI()).thenReturn("/" + PERM_SVC); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK); @@ -99,7 +99,7 @@ public class TestXacmlPdpServiceFilter { * Tests doFilter() when the API is disabled, but a permanent service is requested, with extra URI prefix. */ @Test - public void testDoFilter_DisabledPermanentServiceReqExtraUri() throws Exception { + void testDoFilter_DisabledPermanentServiceReqExtraUri() throws Exception { XacmlPdpServiceFilter.disableApi(); when(request.getRequestURI()).thenReturn("/some/stuff/" + PERM_SVC); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK); @@ -110,7 +110,7 @@ public class TestXacmlPdpServiceFilter { * the service name. */ @Test - public void testDoFilter_DisabledPermanentServiceReqExtraChars() throws Exception { + void testDoFilter_DisabledPermanentServiceReqExtraChars() throws Exception { XacmlPdpServiceFilter.disableApi(); when(request.getRequestURI()).thenReturn("/ExtraStuff" + PERM_SVC); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_CONFLICT); @@ -120,24 +120,14 @@ public class TestXacmlPdpServiceFilter { * Tests doFilter() when the API is disabled and an API service is requested. */ @Test - public void testDoFilter_DisabledApiReq() throws Exception { + void testDoFilter_DisabledApiReq() throws Exception { XacmlPdpServiceFilter.disableApi(); when(request.getRequestURI()).thenReturn("/other"); assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_CONFLICT); } - /** - * Tests doFilter() when the API is disabled and an API service is requested. - */ - @Test - public void testDoFilter_EnabledApiReq() throws Exception { - XacmlPdpServiceFilter.enableApi(); - lenient().when(request.getRequestURI()).thenReturn("/other"); - assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK); - } - @Test - public void testEnableApi_testDisableApi_testIsApiEnabled() { + void testEnableApi_testDisableApi_testIsApiEnabled() { XacmlPdpServiceFilter.enableApi(); assertThat(XacmlPdpServiceFilter.isApiEnabled()).isTrue(); @@ -148,9 +138,10 @@ public class TestXacmlPdpServiceFilter { /** * Invokes doFilter(). + * * @return the response code set by the filter */ - private int getFilterResponse() throws Exception { + private int getFilterResponse() throws Exception { filter.doFilter(request, response, filterChain); // should only be called once diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java index 856a29a3..45d3dfc5 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +22,11 @@ package org.onap.policy.pdpx.main.rest; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.pdpx.main.CommonRest; import org.onap.policy.pdpx.main.rest.model.StatisticsReport; import org.slf4j.Logger; @@ -33,16 +34,15 @@ import org.slf4j.LoggerFactory; /** * Class to perform unit test of {@link XacmlPdpRestController}. - * */ -public class TestXacmlPdpStatistics extends CommonRest { +class TestXacmlPdpStatistics extends CommonRest { private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpStatistics.class); private int nupdates = 0; @Test - public void testXacmlPdpStatistics_200() throws Exception { + void testXacmlPdpStatistics_200() throws Exception { LOGGER.info("*************************** Running testXacmlPdpStatistics_200 ***************************"); StatisticsReport report = getXacmlPdpStatistics(); validateReport(report, 0, 200, new HashMap<>()); @@ -52,7 +52,7 @@ public class TestXacmlPdpStatistics extends CommonRest { } @Test - public void testXacmlPdpStatistics_500() throws Exception { + void testXacmlPdpStatistics_500() throws Exception { LOGGER.info("***************************** Running testXacmlPdpStatistics_500 *****************************"); markActivatorDead(); final StatisticsReport report = getXacmlPdpStatistics(); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java index b04f44fb..e4a61d53 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2020-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,10 +32,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Map; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardYamlCoder; import org.onap.policy.common.utils.resources.ResourceUtils; @@ -50,28 +50,28 @@ import org.onap.policy.xacml.pdp.application.optimization.OptimizationPdpApplica import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class XacmlPdpApplicationManagerTest { +class XacmlPdpApplicationManagerTest { private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManagerTest.class); private static final StandardYamlCoder yamlCoder = new StandardYamlCoder(); private static Path appsDirectory; private static ToscaServiceTemplate completedJtst; private static final CommonTestData testData = new CommonTestData(); - @ClassRule - public static final TemporaryFolder appsFolder = new TemporaryFolder(); + @TempDir + static Path appsFolder; /** * setupTestEnvironment. * * @throws Exception Exception if anything is missing */ - @BeforeClass - public static void setupTestEnvironment() throws Exception { + @BeforeAll + static void setupTestEnvironment() throws Exception { // // Load an example policy // String policyYaml = ResourceUtils - .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml"); + .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml"); // // Serialize it into a class // @@ -82,13 +82,13 @@ public class XacmlPdpApplicationManagerTest { throw new XacmlApplicationException("Failed to decode policy from resource file", e); } // - // Make sure all the fields are setup properly + // Make sure all the fields are set up properly // JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate(); jtst.fromAuthorative(serviceTemplate); completedJtst = jtst.toAuthorative(); // - // We need at least 1 policies + // We need at least 1 policy // assertThat(completedJtst).isNotNull(); assertThat(completedJtst.getToscaTopologyTemplate().getPolicies()).isNotEmpty(); @@ -96,20 +96,20 @@ public class XacmlPdpApplicationManagerTest { // Copy test directory over of the application directories // Path src = Paths.get("src/test/resources/apps"); - File apps = appsFolder.newFolder("apps"); + File apps = appsFolder.resolve("apps").toFile(); Files.walk(src).forEach(source -> copy(source, apps.toPath().resolve(src.relativize(source)))); appsDirectory = apps.toPath(); } @Test - public void testXacmlPdpApplicationManagerBadPath() throws Exception { + void testXacmlPdpApplicationManagerBadPath() throws Exception { // - // Make up a non existent directory to initialize from + // Make up a non-existent directory to initialize from // - Path nonExistentPath = Paths.get(appsFolder.getRoot().getAbsolutePath(), "nonexistent"); + Path nonExistentPath = Paths.get(appsFolder.toFile().getAbsolutePath(), "nonexistent"); final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - nonExistentPath.toString()), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + nonExistentPath.toString()), XacmlApplicationParameters.class); // // Create our app manager // @@ -132,12 +132,12 @@ public class XacmlPdpApplicationManagerTest { } @Test - public void testXacmlPdpApplicationManagerSimple() { + void testXacmlPdpApplicationManagerSimple() { final String[] exclusions = {"org.onap.policy.xacml.pdp.application.guard.GuardPdpApplication", - "org.onap.policy.xacml.pdp.application.match.MatchPdpApplication" }; + "org.onap.policy.xacml.pdp.application.match.MatchPdpApplication"}; final XacmlApplicationParameters xacmlApplicationParameters = - testData.toObject(testData.getXacmlapplicationParametersMap(false, - appsDirectory.toString(), exclusions), XacmlApplicationParameters.class); + testData.toObject(testData.getXacmlapplicationParametersMap(false, + appsDirectory.toString(), exclusions), XacmlApplicationParameters.class); XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, null); // // Test the basics from the startup diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java index 2a0a5524..0dcd2fa1 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ package org.onap.policy.pdpx.main.rest.serialization; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.att.research.xacml.api.Request; import com.att.research.xacml.api.Response; @@ -46,14 +46,11 @@ public class CommonSerialization { assertFalse(getter.apply(null, null, null, null)); // valid media type and class type - assertTrue("writeable " + subType, getter.apply( - REQUEST_CLASS, null, null, new MediaType(primaryType, subType))); - assertTrue("writeable " + subType, getter.apply( - RESPONSE_CLASS, null, null, new MediaType(primaryType, subType))); + assertTrue(getter.apply(REQUEST_CLASS, null, null, new MediaType(primaryType, subType))); + assertTrue(getter.apply(RESPONSE_CLASS, null, null, new MediaType(primaryType, subType))); // valid media type but invalid class type - assertFalse(getter.apply( - GENERAL_CLASS, null, null, new MediaType(primaryType, subType))); + assertFalse(getter.apply(GENERAL_CLASS, null, null, new MediaType(primaryType, subType))); // null subtype or invalid media type assertFalse(getter.apply(null, null, null, new MediaType(primaryType, null))); diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java index 31d6c60f..20b4336c 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,25 +21,25 @@ package org.onap.policy.pdpx.main.rest.serialization; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.ws.rs.core.Response; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; -public class TestXacmlJsonExceptionMapper { +class TestXacmlJsonExceptionMapper { private XacmlJsonExceptionMapper mapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { mapper = new XacmlJsonExceptionMapper(); } @Test - public void testToResponse() throws CoderException { + void testToResponse() throws CoderException { final IOException writeToEx = new IOException("failed to convert a json response to a string"); final IOException readFromEx = new IOException("failed to decode incoming request string to a json request"); final IOException unexpectedEx = new IOException("unexpected exception"); @@ -49,10 +49,13 @@ public class TestXacmlJsonExceptionMapper { assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), writeToResp.getStatus()); assertEquals("{'errorDetails':'invalid JSON xacml response'}".replace('\'', '"'), - new StandardCoder().encode(writeToResp.getEntity())); + new StandardCoder().encode(writeToResp.getEntity())); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), readFromResp.getStatus()); assertEquals("{'errorDetails':'invalid JSON xacml request'}".replace('\'', '"'), - new StandardCoder().encode(readFromResp.getEntity())); + new StandardCoder().encode(readFromResp.getEntity())); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), unexpectedResp.getStatus()); + writeToResp.close(); + readFromResp.close(); + unexpectedResp.close(); } }
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java index 1dbbff9d..34e64004 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +21,8 @@ package org.onap.policy.pdpx.main.rest.serialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import com.att.research.xacml.api.Request; import com.att.research.xacml.api.RequestAttributes; @@ -34,11 +35,11 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.resources.ResourceUtils; -public class TestXacmlJsonMessageBodyHandler { +class TestXacmlJsonMessageBodyHandler { private static final String PRIMARY_TYPE = "application"; private static final String SUB_TYPE = "xacml+json"; @@ -50,35 +51,35 @@ public class TestXacmlJsonMessageBodyHandler { private XacmlJsonMessageBodyHandler hdlr; - @Before - public void setUp() { + @BeforeEach + void setUp() { hdlr = new XacmlJsonMessageBodyHandler(); } @Test - public void testIsWriteable() { + void testIsWriteable() { CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isWriteable); } @Test - public void testWriteTo() throws IOException, DOMStructureException, JSONStructureException { + void testWriteTo() throws IOException, DOMStructureException, JSONStructureException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Response resp = DOMResponse.load(ResourceUtils.getResourceAsString( - "src/test/resources/decisions/decision.native.response.xml")); + "src/test/resources/decisions/decision.native.response.xml")); hdlr.writeTo(resp, RESPONSE_CLASS, RESPONSE_CLASS, null, null, null, stream); assertEquals(resp, JsonResponseTranslator.load(new ByteArrayInputStream(stream.toByteArray()))); } @Test - public void testIsReadable() { + void testIsReadable() { CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isReadable); } @Test @SuppressWarnings("unchecked") - public void testReadFrom() throws IOException { + void testReadFrom() throws IOException { Request req = hdlr.readFrom(REQUEST_CLASS, REQUEST_CLASS, null, null, null, ResourceUtils.getResourceAsStream( - "src/test/resources/decisions/decision.native.request.json")); + "src/test/resources/decisions/decision.native.request.json")); assertFalse(req.getCombinedDecision()); assertFalse(req.getReturnPolicyIdList()); assertEquals(3, req.getRequestAttributes().size()); @@ -87,16 +88,16 @@ public class TestXacmlJsonMessageBodyHandler { RequestAttributes firstRequestAttributes = iter.next(); assertEquals(1, firstRequestAttributes.getAttributes().size()); assertEquals("Julius Hibbert", firstRequestAttributes.getAttributes().iterator().next() - .getValues().iterator().next().getValue().toString()); + .getValues().iterator().next().getValue().toString()); RequestAttributes secondRequestAttributes = iter.next(); assertEquals(1, secondRequestAttributes.getAttributes().size()); assertEquals("http://medico.com/record/patient/BartSimpson", secondRequestAttributes.getAttributes() - .iterator().next().getValues().iterator().next().getValue().toString()); + .iterator().next().getValues().iterator().next().getValue().toString()); RequestAttributes thirdRequestAttributes = iter.next(); assertEquals(1, thirdRequestAttributes.getAttributes().size()); assertEquals("read", thirdRequestAttributes.getAttributes().iterator().next() - .getValues().iterator().next().getValue().toString()); + .getValues().iterator().next().getValue().toString()); } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java index 3fd76c3b..1a6f7a0e 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,25 +21,25 @@ package org.onap.policy.pdpx.main.rest.serialization; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.ws.rs.core.Response; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; -public class TestXacmlXmlExceptionMapper { +class TestXacmlXmlExceptionMapper { private XacmlXmlExceptionMapper mapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { mapper = new XacmlXmlExceptionMapper(); } @Test - public void testToResponse() throws CoderException { + void testToResponse() throws CoderException { final IOException writeToEx = new IOException("failed to convert a dom response to a string"); final IOException readFromEx = new IOException("failed to decode incoming request string to a dom request"); final IOException unexpectedEx = new IOException("unexpected exception"); @@ -49,10 +49,13 @@ public class TestXacmlXmlExceptionMapper { assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), writeToResp.getStatus()); assertEquals("{'errorDetails':'invalid XML xacml response'}".replace('\'', '"'), - new StandardCoder().encode(writeToResp.getEntity())); + new StandardCoder().encode(writeToResp.getEntity())); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), readFromResp.getStatus()); assertEquals("{'errorDetails':'invalid XML xacml request'}".replace('\'', '"'), - new StandardCoder().encode(readFromResp.getEntity())); + new StandardCoder().encode(readFromResp.getEntity())); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), unexpectedResp.getStatus()); + writeToResp.close(); + readFromResp.close(); + unexpectedResp.close(); } }
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java index f2e4f4f6..f7938e3b 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +21,8 @@ package org.onap.policy.pdpx.main.rest.serialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import com.att.research.xacml.api.Request; import com.att.research.xacml.api.RequestAttributes; @@ -32,11 +33,11 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.resources.ResourceUtils; -public class TestXacmlXmlMessageBodyHandler { +class TestXacmlXmlMessageBodyHandler { private static final String PRIMARY_TYPE = "application"; private static final String SUB_TYPE = "xacml+xml"; @@ -48,35 +49,35 @@ public class TestXacmlXmlMessageBodyHandler { private XacmlXmlMessageBodyHandler hdlr; - @Before - public void setUp() { + @BeforeEach + void setUp() { hdlr = new XacmlXmlMessageBodyHandler(); } @Test - public void testIsWriteable() { + void testIsWriteable() { CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isWriteable); } @Test - public void testWriteTo() throws IOException, DOMStructureException { + void testWriteTo() throws IOException, DOMStructureException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Response resp = DOMResponse.load(ResourceUtils.getResourceAsString( - "src/test/resources/decisions/decision.native.response.xml")); + "src/test/resources/decisions/decision.native.response.xml")); hdlr.writeTo(resp, RESPONSE_CLASS, RESPONSE_CLASS, null, null, null, stream); assertEquals(resp, DOMResponse.load(new ByteArrayInputStream(stream.toByteArray()))); } @Test - public void testIsReadable() { + void testIsReadable() { CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isReadable); } @Test @SuppressWarnings("unchecked") - public void testReadFrom() throws IOException { + void testReadFrom() throws IOException { Request req = hdlr.readFrom(REQUEST_CLASS, REQUEST_CLASS, null, null, null, ResourceUtils.getResourceAsStream( - "src/test/resources/decisions/decision.native.request.xml")); + "src/test/resources/decisions/decision.native.request.xml")); assertFalse(req.getCombinedDecision()); assertFalse(req.getReturnPolicyIdList()); assertEquals(4, req.getRequestAttributes().size()); @@ -85,16 +86,16 @@ public class TestXacmlXmlMessageBodyHandler { RequestAttributes firstRequestAttributes = iter.next(); assertEquals(1, firstRequestAttributes.getAttributes().size()); assertEquals("Julius Hibbert", firstRequestAttributes.getAttributes().iterator().next() - .getValues().iterator().next().getValue().toString()); + .getValues().iterator().next().getValue().toString()); RequestAttributes secondRequestAttributes = iter.next(); assertEquals(1, secondRequestAttributes.getAttributes().size()); assertEquals("http://medico.com/record/patient/BartSimpson", secondRequestAttributes.getAttributes() - .iterator().next().getValues().iterator().next().getValue().toString()); + .iterator().next().getValues().iterator().next().getValue().toString()); RequestAttributes thirdRequestAttributes = iter.next(); assertEquals(1, thirdRequestAttributes.getAttributes().size()); assertEquals("read", thirdRequestAttributes.getAttributes().iterator().next() - .getValues().iterator().next().getValue().toString()); + .getValues().iterator().next().getValue().toString()); } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java index 5e46b669..80e6f707 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,27 +24,27 @@ package org.onap.policy.pdpx.main.startstop; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.pdpx.main.CommonRest; import org.onap.policy.pdpx.main.PolicyXacmlPdpException; /** * Class to perform unit test of Main. - * */ -public class TestMain extends CommonRest { +class TestMain extends CommonRest { private Main main; /** * Sets up properties and configuration. + * * @throws Exception if an error occurs */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { CommonRest.setUpBeforeClass(); @@ -53,7 +53,7 @@ public class TestMain extends CommonRest { } @Override - @Before + @BeforeEach public void setUp() { main = null; } @@ -62,7 +62,7 @@ public class TestMain extends CommonRest { * Shuts "main" down. */ @Override - @After + @AfterEach public void tearDown() { if (main != null) { main.shutdown(); @@ -70,7 +70,7 @@ public class TestMain extends CommonRest { } @Test - public void testMain() throws PolicyXacmlPdpException { + void testMain() { final String[] xacmlPdpConfigParameters = {"-c", CONFIG_FILE}; assertThatCode(() -> { main = new Main(xacmlPdpConfigParameters); @@ -80,30 +80,30 @@ public class TestMain extends CommonRest { } @Test - public void testMain_NoArguments() { + void testMain_NoArguments() { final String[] xacmlPdpConfigParameters = {}; assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class) - .hasMessage("policy xacml pdp configuration file was not specified as an argument"); + .hasMessage("policy xacml pdp configuration file was not specified as an argument"); } @Test - public void testMain_InvalidArguments() { + void testMain_InvalidArguments() { final String[] xacmlPdpConfigParameters = {"parameters/XacmlPdpConfigParameters.json"}; assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class) .hasMessage("too many command line arguments specified : [parameters/XacmlPdpConfigParameters.json]"); } @Test - public void testMain_Help() throws PolicyXacmlPdpException { + void testMain_Help() throws PolicyXacmlPdpException { final String[] xacmlPdpConfigParameters = {"-h"}; - Assert.assertTrue(new Main(xacmlPdpConfigParameters).getArgumentMessage().contains("-h,--help")); + Assertions.assertTrue(new Main(xacmlPdpConfigParameters).getArgumentMessage().contains("-h,--help")); } @Test - public void testMain_InvalidParameters() { + void testMain_InvalidParameters() { final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"}; assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class) - .hasMessageContaining("validation error"); + .hasMessageContaining("validation error"); } } diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java index 61ba8b85..bdcbd99c 100644 --- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java +++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019,2023 Nordix Foundation. + * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ package org.onap.policy.pdpx.main.startstop; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.pdpx.main.CommonRest; -import org.onap.policy.pdpx.main.PolicyXacmlPdpException; import org.onap.policy.pdpx.main.parameters.CommonTestData; import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup; import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterHandler; @@ -40,7 +39,6 @@ import org.springframework.test.util.ReflectionTestUtils; /** * Class to perform unit test of XacmlPdpActivator. - * */ public class TestXacmlPdpActivator extends CommonRest { private static final String PROBE_FIELD_NAME = "probeHeartbeatTopicSec"; @@ -52,7 +50,7 @@ public class TestXacmlPdpActivator extends CommonRest { /** * Loads properties. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { CommonRest.setUpBeforeClass(); @@ -68,14 +66,14 @@ public class TestXacmlPdpActivator extends CommonRest { * Creates the activator. */ @Override - @Before + @BeforeEach public void setUp() { ReflectionTestUtils.setField(parGroup, PROBE_FIELD_NAME, 4); activator = new XacmlPdpActivator(parGroup); } @Test - public void testXacmlPdpActivator() throws Exception { + void testXacmlPdpActivator() { assertFalse(activator.isAlive()); assertFalse(activator.isApiEnabled()); activator.start(); @@ -95,7 +93,7 @@ public class TestXacmlPdpActivator extends CommonRest { } @Test - public void testXacmlPdpActivator_NoProbe() throws Exception { + void testXacmlPdpActivator_NoProbe() { ReflectionTestUtils.setField(parGroup, PROBE_FIELD_NAME, 0); activator = new XacmlPdpActivator(parGroup); activator.start(); @@ -103,13 +101,13 @@ public class TestXacmlPdpActivator extends CommonRest { } @Test - public void testGetCurrent_testSetCurrent() { + void testGetCurrent_testSetCurrent() { XacmlPdpActivator.setCurrent(activator); assertSame(activator, XacmlPdpActivator.getCurrent()); } @Test - public void testTerminate() throws Exception { + void testTerminate() { activator.start(); activator.stop(); assertFalse(activator.isAlive()); @@ -117,10 +115,9 @@ public class TestXacmlPdpActivator extends CommonRest { /** * Teardown tests. - * @throws PolicyXacmlPdpException on termination errors */ - @After - public void teardown() throws PolicyXacmlPdpException { + @AfterEach + public void teardown() { if (activator != null && activator.isAlive()) { activator.stop(); } diff --git a/main/src/test/resources/META-INF/persistence.xml b/main/src/test/resources/META-INF/persistence.xml index d7f9d921..6ab21988 100644 --- a/main/src/test/resources/META-INF/persistence.xml +++ b/main/src/test/resources/META-INF/persistence.xml @@ -4,7 +4,7 @@ ONAP ================================================================================ Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - Modifications Copyright (C) 2023 Nordix Foundation. + Modifications Copyright (C) 2023-2024 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,18 +20,17 @@ ============LICENSE_END========================================================= --> -<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> +<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd"> <persistence-unit name="PipEngineTest" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - + <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>org.onap.policy.guard.OperationsHistory</class> - <properties> <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/> <property name="jakarta.persistence.schema-generation.create-source" value="metadata"/> - <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/> - <property name="hibernate.show_sql" value="false" /> + <property name="hibernate.show_sql" value="false"/> </properties> </persistence-unit> |