diff options
Diffstat (limited to 'main/src/test')
71 files changed, 1453 insertions, 1504 deletions
diff --git a/main/src/test/java/org/onap/policy/pap/contract/PapContractTest.java b/main/src/test/java/org/onap/policy/pap/contract/PapContractTest.java index 7b9698bb..0b663beb 100644 --- a/main/src/test/java/org/onap/policy/pap/contract/PapContractTest.java +++ b/main/src/test/java/org/onap/policy/pap/contract/PapContractTest.java @@ -19,28 +19,28 @@ package org.onap.policy.pap.contract; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.test.context.ActiveProfiles; -@ActiveProfiles({ "test", "stub" }) -public class PapContractTest extends CommonPapRestServer { +@ActiveProfiles({"test", "stub"}) +class PapContractTest extends CommonPapRestServer { @Test - public void testStubsHealthcheck() throws Exception { + void testStubsHealthcheck() throws Exception { checkStubJsonGet("healthcheck"); checkStubJsonGet("pdps/healthcheck"); checkStubJsonGet("components/healthcheck"); } @Test - public void testStubsPolicies() throws Exception { + void testStubsPolicies() throws Exception { checkStubJsonGet("policies/audit"); checkStubJsonGet("policies/audit/group"); checkStubJsonGet("policies/audit/group/name/version"); @@ -55,7 +55,7 @@ public class PapContractTest extends CommonPapRestServer { } @Test - public void testStubsPdps() throws Exception { + void testStubsPdps() throws Exception { checkStubJsonGet("pdps"); checkStubJsonPost("pdps/groups/batch"); @@ -79,8 +79,8 @@ public class PapContractTest extends CommonPapRestServer { var response = super.sendRequest(url); PdpGroups groups = new PdpGroups(); assertEquals(Response.Status.OK.getStatusCode(), response - .post(Entity.entity(groups, MediaType.APPLICATION_JSON)) - .getStatus()); + .post(Entity.entity(groups, MediaType.APPLICATION_JSON)) + .getStatus()); } private void checkStubJsonPut(String url) throws Exception { diff --git a/main/src/test/java/org/onap/policy/pap/main/PapConstantsTest.java b/main/src/test/java/org/onap/policy/pap/main/PapConstantsTest.java index 6d5d303a..747bc75b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/PapConstantsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/PapConstantsTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020, 2023 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,12 +23,12 @@ package org.onap.policy.pap.main; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PapConstantsTest { +class PapConstantsTest { @Test - public void test() { + void test() { assertThat(PapConstants.PAP_NAME).startsWith("pap").isNotEqualTo("pap"); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java b/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java index 608e7ad8..c85531c7 100644 --- a/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java +++ b/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java @@ -1,6 +1,6 @@ /*-- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2023 Nordix Foundation. * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,7 +21,7 @@ package org.onap.policy.pap.main; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; /** @@ -29,10 +29,10 @@ import org.onap.policy.common.utils.test.ExceptionsTester; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class TestExceptions { +class TestExceptions { @Test - public void test() { + void test() { new ExceptionsTester().test(PolicyPapException.class); new ExceptionsTester().test(PolicyPapRuntimeException.class); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java index 7fe1360f..81e0d5bc 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java @@ -33,8 +33,8 @@ import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.function.Consumer; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; @@ -89,7 +89,7 @@ public class CommonRequestBase { protected RequestParams reqParams; protected PdpModifyRequestMapParams mapParams; - @BeforeClass + @BeforeAll public static void setupBeforeAll() { Registry.registerOrReplace(PapConstants.REG_METER_REGISTRY, new SimpleMeterRegistry()); } @@ -99,7 +99,7 @@ public class CommonRequestBase { * * @throws Exception if an error occurs */ - @Before + @BeforeEach @SuppressWarnings("unchecked") public void setUp() throws Exception { publisher = mock(Publisher.class); diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/MultiPdpStatusListenerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/MultiPdpStatusListenerTest.java index 4f276a90..beb0697e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/MultiPdpStatusListenerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/MultiPdpStatusListenerTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 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,21 +21,21 @@ package org.onap.policy.pap.main.comm; -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 java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.models.pdp.concepts.PdpResponseDetails; import org.onap.policy.models.pdp.concepts.PdpStatus; -public class MultiPdpStatusListenerTest { +class MultiPdpStatusListenerTest { private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; private static final String TOPIC = "my-topic"; private static final String ID1 = "request-1"; @@ -46,16 +46,16 @@ public class MultiPdpStatusListenerTest { private PdpStatus status; @Test - public void testMultiPdpStatusListenerString() throws Exception { + void testMultiPdpStatusListenerString() throws Exception { listener = new MyListener(ID1); - assertEquals(Arrays.asList(ID1).toString(), listener.getUnseenIds().toString()); + assertEquals(List.of(ID1).toString(), listener.getUnseenIds().toString()); // an ID is in the queue - not done yet assertFalse(doWait(0)); } @Test - public void testMultiPdpStatusListenerCollectionOfString() throws Exception { + void testMultiPdpStatusListenerCollectionOfString() throws Exception { List<String> lst = ID_LIST; listener = new MyListener(lst); @@ -73,7 +73,7 @@ public class MultiPdpStatusListenerTest { } @Test - public void testGetUnseenIds() { + void testGetUnseenIds() { List<String> lst = ID_LIST; listener = new MyListener(lst); @@ -83,7 +83,7 @@ public class MultiPdpStatusListenerTest { status = new PdpStatus(); status.setResponse(makeResponse(ID2)); listener.onTopicEvent(INFRA, TOPIC, status); - assertEquals(Arrays.asList(ID1).toString(), listener.getUnseenIds().toString()); + assertEquals(List.of(ID1).toString(), listener.getUnseenIds().toString()); // receive message from the other PDP status = new PdpStatus(); @@ -93,7 +93,7 @@ public class MultiPdpStatusListenerTest { } @Test - public void testAwait() throws Exception { + void testAwait() throws Exception { // try with an empty list - should already be complete listener = new MyListener(new LinkedList<>()); assertTrue(doWait(0)); @@ -120,7 +120,7 @@ public class MultiPdpStatusListenerTest { } @Test - public void testOnTopicEvent() throws Exception { + void testOnTopicEvent() throws Exception { listener = new MyListener(ID_LIST); // not done yet diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java index 20e34f62..5f2df5be 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ @@ -23,18 +23,15 @@ package org.onap.policy.pap.main.comm; import static org.assertj.core.api.Assertions.assertThat; -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 java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpSubGroup; @@ -64,13 +61,11 @@ public class PdpHeartbeatListenerTest extends End2EndBase { private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; private static final String TOPIC = "my-topic"; - private Instant timeStamp; - @Autowired private PdpHeartbeatListener pdpHeartbeatListener; @Test - public void testPdpHeartbeatListener() throws CoderException, PfModelException { + public void testPdpHeartbeatListener() { addGroups("PdpGroups.json"); PapParameterGroup parameterGroup = new PapParameterGroup(); parameterGroup.setPdpParameters(new PdpParameters()); @@ -82,11 +77,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status1.setPdpGroup(DEFAULT_GROUP); status1.setPdpType(APEX_TYPE); status1.setHealthy(PdpHealthStatus.HEALTHY); - final List<ToscaConceptIdentifier> idents1 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents1 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status1.setPolicies(idents1); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status1); - verifyPdpGroup(DEFAULT_GROUP, 1); + verifyPdpGroup(1); // Testing pdp heartbeat success case final PdpStatus status2 = new PdpStatus(); @@ -96,11 +90,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status2.setPdpType(APEX_TYPE); status2.setHealthy(PdpHealthStatus.HEALTHY); status2.setPdpSubgroup(APEX_TYPE); - final List<ToscaConceptIdentifier> idents2 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents2 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status2.setPolicies(idents2); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status2); - verifyPdpGroup(DEFAULT_GROUP, 1); + verifyPdpGroup(1); // Testing pdp heartbeat failure case with pdp missing final PdpStatus status3 = new PdpStatus(); @@ -110,11 +103,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status3.setPdpType(APEX_TYPE); status3.setHealthy(PdpHealthStatus.HEALTHY); status3.setPdpSubgroup(APEX_TYPE); - final List<ToscaConceptIdentifier> idents3 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents3 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status3.setPolicies(idents3); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status3); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing pdp registration failure case final PdpStatus status4 = new PdpStatus(); @@ -123,11 +115,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status4.setPdpGroup("wrongGroup"); status4.setPdpType(APEX_TYPE); status4.setHealthy(PdpHealthStatus.HEALTHY); - final List<ToscaConceptIdentifier> idents4 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents4 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status4.setPolicies(idents4); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status4); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing pdp heartbeat failure case with pdp state mismatch final PdpStatus status5 = new PdpStatus(); @@ -137,11 +128,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status5.setPdpType(APEX_TYPE); status5.setHealthy(PdpHealthStatus.HEALTHY); status5.setPdpSubgroup(APEX_TYPE); - final List<ToscaConceptIdentifier> idents5 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents5 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status5.setPolicies(idents5); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status5); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing pdp heartbeat failure case with pdp policies mismatch final PdpStatus status6 = new PdpStatus(); @@ -156,7 +146,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { new ToscaConceptIdentifier("onap.restart.tca", POLICY_VERSION)); status6.setPolicies(idents6); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status6); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing pdp heartbeat failure case with pdp no policies final PdpStatus status7 = new PdpStatus(); @@ -167,7 +157,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status7.setHealthy(PdpHealthStatus.HEALTHY); status7.setPdpSubgroup(APEX_TYPE); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status7); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing old message for pdp_1 - should have no effect final PdpStatus status7b = new PdpStatus(); @@ -178,11 +168,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status7b.setPdpType(APEX_TYPE); status7b.setPdpSubgroup(APEX_TYPE); status7b.setHealthy(PdpHealthStatus.HEALTHY); - final List<ToscaConceptIdentifier> idents7b = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents7b = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status7b.setPolicies(idents7b); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status7b); - verifyPdpGroup(DEFAULT_GROUP, 2); + verifyPdpGroup(2); // Testing pdp termination case for pdp_1 final PdpStatus status8 = new PdpStatus(); @@ -192,11 +181,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status8.setPdpType(APEX_TYPE); status8.setPdpSubgroup(APEX_TYPE); status8.setHealthy(PdpHealthStatus.HEALTHY); - final List<ToscaConceptIdentifier> idents8 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents8 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status8.setPolicies(idents8); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status8); - verifyPdpGroup(DEFAULT_GROUP, 1); + verifyPdpGroup(1); // Testing pdp termination case for pdp_2 final PdpStatus status9 = new PdpStatus(); @@ -206,11 +194,10 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status9.setPdpType(APEX_TYPE); status9.setPdpSubgroup(APEX_TYPE); status9.setHealthy(PdpHealthStatus.HEALTHY); - final List<ToscaConceptIdentifier> idents9 = - Arrays.asList(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); + final List<ToscaConceptIdentifier> idents9 = List.of(new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION)); status9.setPolicies(idents9); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status9); - verifyPdpGroup(DEFAULT_GROUP, 0); + verifyPdpGroup(0); // Test policy lists updated in createUpdate ToscaPolicy polA = new ToscaPolicy(); @@ -233,8 +220,8 @@ public class PdpHeartbeatListenerTest extends End2EndBase { assertThat(update10.getPoliciesToBeDeployed()).isInstanceOf(List.class); } - private void verifyPdpGroup(final String name, final int count) throws PfModelException { - final List<PdpGroup> fetchedGroups = fetchGroups(name); + private void verifyPdpGroup(final int count) { + final List<PdpGroup> fetchedGroups = fetchGroups(PdpHeartbeatListenerTest.DEFAULT_GROUP); for (final PdpSubGroup subGroup : fetchedGroups.get(0).getPdpSubgroups()) { if (subGroup.getPdpType().equals(APEX_TYPE)) { assertEquals(count, subGroup.getPdpInstances().size()); diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java index 40284496..6fc9d8f0 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020-2021,2023 Nordix Foundation. + * Modifications Copyright (C) 2020-2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -25,11 +25,11 @@ package org.onap.policy.pap.main.comm; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -39,22 +39,25 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import jakarta.ws.rs.core.Response.Status; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; -import javax.ws.rs.core.Response.Status; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -76,7 +79,7 @@ import org.onap.policy.pap.main.service.PolicyStatusService; import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) -public class PdpModifyRequestMapTest extends CommonRequestBase { +class PdpModifyRequestMapTest extends CommonRequestBase { private static final String MY_REASON = "my reason"; private static final int EXPIRED_SECONDS = 100; @@ -119,15 +122,18 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { private PdpStateChange change; private PdpStatus response; + AutoCloseable autoCloseable; + /** * Sets up. * * @throws Exception if an error occurs */ - @Before + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); + autoCloseable = MockitoAnnotations.openMocks(this); response = new PdpStatus(); @@ -146,14 +152,19 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { map = new MyMap(mapParams); } + @AfterEach + void tearDown() throws Exception { + autoCloseable.close(); + } + @Test - public void testPdpModifyRequestMap() { + void testPdpModifyRequestMap() { assertSame(mapParams, ReflectionTestUtils.getField(map, "params")); assertSame(lock, ReflectionTestUtils.getField(map, "modifyLock")); } @Test - public void testIsEmpty() { + void testIsEmpty() { assertTrue(map.isEmpty()); map.addRequest(change); @@ -167,7 +178,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStopPublishing() { + void testStopPublishing() { // try with non-existent PDP map.stopPublishing(PDP1); @@ -182,13 +193,13 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testAddRequestPdpUpdatePdpStateChange_BothNull() { + void testAddRequestPdpUpdatePdpStateChange_BothNull() { // nulls should be ok Assertions.assertThatCode(() -> map.addRequest(null, null)).doesNotThrowAnyException(); } @Test - public void testAddRequestPdpUpdatePdpStateChange_NullUpdate() { + void testAddRequestPdpUpdatePdpStateChange_NullUpdate() { map.addRequest(null, change); Request req = getSingletons(1).get(0); @@ -197,7 +208,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testAddRequestPdpUpdatePdpStateChange_NullStateChange() { + void testAddRequestPdpUpdatePdpStateChange_NullStateChange() { map.addRequest(update, null); Request req = getSingletons(1).get(0); @@ -210,7 +221,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * message. */ @Test - public void testAddRequestPdpUpdatePdpStateChange_BothProvided_Active() { + void testAddRequestPdpUpdatePdpStateChange_BothProvided_Active() { change.setState(PdpState.ACTIVE); map.addRequest(update, change); @@ -235,7 +246,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * message. */ @Test - public void testAddRequestPdpUpdatePdpStateChange_BothProvided_Passive() { + void testAddRequestPdpUpdatePdpStateChange_BothProvided_Passive() { change.setState(PdpState.PASSIVE); map.addRequest(update, change); @@ -256,7 +267,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testAddRequestPdpUpdatePdpStateChange() { + void testAddRequestPdpUpdatePdpStateChange() { // null should be ok map.addRequest(null, null); @@ -269,11 +280,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { // broadcast should throw an exception change.setName(null); assertThatIllegalArgumentException().isThrownBy(() -> map.addRequest(change)) - .withMessageStartingWith("unexpected broadcast message: PdpStateChange"); + .withMessageStartingWith("unexpected broadcast message: PdpStateChange"); } @Test - public void testAddRequestPdpUpdate() { + void testAddRequestPdpUpdate() { // null should be ok map.addRequest((PdpUpdate) null); @@ -286,11 +297,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { // broadcast should throw an exception update.setName(null); assertThatIllegalArgumentException().isThrownBy(() -> map.addRequest(update)) - .withMessageStartingWith("unexpected broadcast message: PdpUpdate"); + .withMessageStartingWith("unexpected broadcast message: PdpUpdate"); } @Test - public void testAddRequestPdpStateChange() { + void testAddRequestPdpStateChange() { // null should be ok map.addRequest((PdpStateChange) null); @@ -303,11 +314,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { // broadcast should throw an exception change.setName(null); assertThatIllegalArgumentException().isThrownBy(() -> map.addRequest(change)) - .withMessageStartingWith("unexpected broadcast message: PdpStateChange"); + .withMessageStartingWith("unexpected broadcast message: PdpStateChange"); } @Test - public void testAddSingleton() { + void testAddSingleton() { map.addRequest(change); assertEquals(1, map.nalloc); @@ -333,7 +344,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStartNextRequest_NoMore() { + void testStartNextRequest_NoMore() { map.addRequest(change); // indicate success @@ -350,7 +361,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStartNextRequest_HaveMore() { + void testStartNextRequest_HaveMore() { map.addRequest(update); map.addRequest(change); @@ -375,7 +386,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRemoveExpiredPdps() throws Exception { + void testRemoveExpiredPdps() { PdpGroup group1 = makeGroup(MY_GROUP); group1.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1))); @@ -410,7 +421,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRemoveExpiredPdps_NothingExpired() throws Exception { + void testRemoveExpiredPdps_NothingExpired() { PdpGroup group1 = makeGroup(MY_GROUP); group1.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1))); @@ -424,21 +435,21 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRemoveExpiredPdps_DaoEx() throws Exception { + void testRemoveExpiredPdps_DaoEx() { when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @Test - public void testRemoveExpiredPdps_DaoRtEx() throws Exception { + void testRemoveExpiredPdps_DaoRtEx() { when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @Test - public void testRemoveFromSubgroup() throws Exception { + void testRemoveFromSubgroup() { PdpGroup group = makeGroup(MY_GROUP); group.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1, PDP2, PDP3))); @@ -473,7 +484,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testMakePdpRequests() { + void testMakePdpRequests() { // this should invoke the real method without throwing an exception PdpModifyRequestMap reqMap = new PdpModifyRequestMap(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); @@ -489,11 +500,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testSingletonListenerFailure() throws Exception { + void testSingletonListenerFailure() throws Exception { map.addRequest(change); // invoke the method - invokeFailureHandler(1); + invokeFailureHandler(); verify(undeployer, never()).undeploy(any(), any(), any()); verify(requests, never()).stopPublishing(); @@ -507,14 +518,14 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * Tests Listener.failure() when something has to be undeployed. */ @Test - public void testSingletonListenerFailureUndeploy() throws Exception { + void testSingletonListenerFailureUndeploy() throws Exception { ToscaConceptIdentifier ident = new ToscaConceptIdentifier("undeployed", "2.3.4"); ToscaPolicy policy = mock(ToscaPolicy.class); when(policy.getIdentifier()).thenReturn(ident); // add some policies to the update - update.setPoliciesToBeDeployed(Arrays.asList(policy)); + update.setPoliciesToBeDeployed(List.of(policy)); map.addRequest(update); @@ -527,7 +538,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { doAnswer(ans -> { PdpUpdate update2 = new PdpUpdate(update); update2.setPoliciesToBeDeployed(Collections.emptyList()); - update2.setPoliciesToBeUndeployed(Arrays.asList(policy.getIdentifier())); + update2.setPoliciesToBeUndeployed(List.of(policy.getIdentifier())); assertTrue(req.reconfigure(update2)); throw makeException(); }).when(undeployer).undeploy(any(), any(), any()); @@ -538,10 +549,10 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { req.checkResponse(response); // invoke the method - invokeFailureHandler(1); + invokeFailureHandler(); verify(undeployer).undeploy(eq(MY_GROUP), eq(MY_SUBGROUP), undeployCaptor.capture()); - assertEquals(Arrays.asList(ident).toString(), undeployCaptor.getValue().toString()); + assertEquals(List.of(ident).toString(), undeployCaptor.getValue().toString()); // no effect on the map map.addRequest(update); @@ -553,14 +564,14 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * remains unchanged. */ @Test - public void testSingletonListenerFailureUndeployMessageUnchanged() throws Exception { + void testSingletonListenerFailureUndeployMessageUnchanged() throws Exception { ToscaConceptIdentifier ident = new ToscaConceptIdentifier("msg-unchanged", "8.7.6"); ToscaPolicy policy = mock(ToscaPolicy.class); when(policy.getIdentifier()).thenReturn(ident); // add some policies to the update - update.setPoliciesToBeDeployed(Arrays.asList(policy)); + update.setPoliciesToBeDeployed(List.of(policy)); map.addRequest(update); @@ -571,10 +582,10 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { req.checkResponse(response); // invoke the method - invokeFailureHandler(1); + invokeFailureHandler(); verify(undeployer).undeploy(eq(MY_GROUP), eq(MY_SUBGROUP), undeployCaptor.capture()); - assertEquals(Arrays.asList(ident).toString(), undeployCaptor.getValue().toString()); + assertEquals(List.of(ident).toString(), undeployCaptor.getValue().toString()); // requests should have been removed from the map so this should allocate another map.addRequest(update); @@ -582,11 +593,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testSingletonListenerSuccess() throws Exception { + void testSingletonListenerSuccess() { map.addRequest(change); // invoke the method - invokeSuccessHandler(1); + invokeSuccessHandler(); verify(requests, never()).stopPublishing(); @@ -596,11 +607,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRequestCompleted_LastRequest() throws Exception { + void testRequestCompleted_LastRequest() { map.addRequest(change); // invoke the method - invokeSuccessHandler(1); + invokeSuccessHandler(); verify(requests, never()).stopPublishing(); @@ -610,7 +621,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRequestCompleted_NameMismatch() throws Exception { + void testRequestCompleted_NameMismatch() { // use a different name when(requests.getPdpName()).thenReturn(DIFFERENT); @@ -618,10 +629,10 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { // put the PDP in a group PdpGroup group = makeGroup(MY_GROUP); - group.setPdpSubgroups(Arrays.asList(makeSubGroup(MY_SUBGROUP, PDP1, DIFFERENT))); + group.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1, DIFFERENT))); // invoke the method - with a different name (i.e., PDP1 instead of DIFFERENT) - invokeSuccessHandler(1); + invokeSuccessHandler(); verify(requests, never()).stopPublishing(); @@ -634,13 +645,13 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRequestCompleted_AlreadyStopped() throws Exception { + void testRequestCompleted_AlreadyStopped() { map.addRequest(change); map.stopPublishing(PDP1); // invoke the method - invokeSuccessHandler(1); + invokeSuccessHandler(); // should have called this a second time verify(requests, times(2)).stopPublishing(); @@ -651,13 +662,13 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testRequestCompleted_NotFirstInQueue() throws Exception { + void testRequestCompleted_NotFirstInQueue() { map.addRequest(change); when(requests.isFirstInQueue(any())).thenReturn(false); // invoke the method - invokeSuccessHandler(1); + invokeSuccessHandler(); // should not have called this verify(requests, never()).stopPublishing(); @@ -668,11 +679,11 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testSingletonListenerRetryCountExhausted() throws Exception { + void testSingletonListenerRetryCountExhausted() { final var request = map.addRequest(change); // invoke the method - invokeLastRetryHandler(1, request); + invokeLastRetryHandler(request); verify(requests).stopPublishing(); } @@ -680,30 +691,25 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { /** * Invokes the first request's listener.success() method. - * - * @param count expected number of requests */ - private void invokeSuccessHandler(int count) { - getListener(getSingletons(count).get(0)).success(PDP1, response); + private void invokeSuccessHandler() { + getListener(getSingletons(1).get(0)).success(PDP1, response); } /** * Invokes the first request's listener.failure() method. - * - * @param count expected number of requests */ - private void invokeFailureHandler(int count) { - getListener(getSingletons(count).get(0)).failure(PDP1, MY_REASON); + private void invokeFailureHandler() { + getListener(getSingletons(1).get(0)).failure(PDP1, MY_REASON); } /** * Invokes the first request's listener.retryCountExhausted() method. * - * @param count expected number of requests * @param request request whose count was exhausted */ - private void invokeLastRetryHandler(int count, Request request) { - getListener(getSingletons(count).get(0)).retryCountExhausted(request); + private void invokeLastRetryHandler(Request request) { + getListener(getSingletons(1).get(0)).retryCountExhausted(request); } /** @@ -742,7 +748,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { subgroup.setPdpType(pdpType); subgroup.setCurrentInstanceCount(pdpNames.length); - subgroup.setPdpInstances(Arrays.asList(pdpNames).stream().map(this::makePdp).collect(Collectors.toList())); + subgroup.setPdpInstances(Arrays.stream(pdpNames).map(this::makePdp).collect(Collectors.toList())); return subgroup; } @@ -759,9 +765,8 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * Gets the input to the method. * * @return the input that was passed to the dao.updatePdpGroups() method - * @throws Exception if an error occurred */ - private List<PdpGroup> getGroupUpdates() throws Exception { + private List<PdpGroup> getGroupUpdates() { verify(pdpGroupService).updatePdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); @@ -775,7 +780,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { */ private List<PdpGroup> copyList(List<PdpGroup> source) { List<PdpGroup> newlst = new ArrayList<>(source); - Collections.sort(newlst, (left, right) -> left.getName().compareTo(right.getName())); + newlst.sort(Comparator.comparing(PdpGroup::getName)); return newlst; } @@ -787,7 +792,8 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { public MyMap(PdpModifyRequestMapParams params) { super(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); - super.initialize(params);; + super.initialize(params); + ; } @Override diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpRequestsTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpRequestsTest.java index 8c257f0b..0c787678 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpRequestsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpRequestsTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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 +22,17 @@ package org.onap.policy.pap.main.comm; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -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 static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.pap.main.comm.msgdata.StateChangeReq; import org.onap.policy.pap.main.comm.msgdata.UpdateReq; @@ -44,7 +45,7 @@ public class PdpRequestsTest extends CommonRequestBase { /** * Sets up. */ - @Before + @BeforeEach public void setUp() { update = makeUpdateReq(PDP1, MY_GROUP, MY_SUBGROUP); change = makeStateChangeReq(PDP1, MY_STATE); @@ -109,7 +110,7 @@ public class PdpRequestsTest extends CommonRequestBase { public void testAddSingleton_Broadcast() { UpdateReq req = makeUpdateReq(null, MY_GROUP, MY_SUBGROUP); assertThatIllegalArgumentException().isThrownBy(() -> data.addSingleton(req)) - .withMessage("unexpected broadcast for pdp_1"); + .withMessage("unexpected broadcast for pdp_1"); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandlerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandlerTest.java index f3ba51ab..5a889125 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandlerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandlerTest.java @@ -23,23 +23,32 @@ package org.onap.policy.pap.main.comm; import static org.assertj.core.api.Assertions.assertThat; +import java.io.Serial; import java.sql.SQLIntegrityConstraintViolationException; import org.hibernate.HibernateException; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.utils.services.Registry; import org.onap.policy.pap.main.PolicyPapApplication; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; @SpringBootTest( classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "db.initialize=false" - }) - -public class PdpStatusMessageHandlerTest { + properties = {"db.initialize=false"}) +@ActiveProfiles("test") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class PdpStatusMessageHandlerTest { + + @BeforeAll + public static void setupClass() { + Registry.newRegistry(); + } @Test - public void testIsDuplicateKeyException() { + void testIsDuplicateKeyException() { // @formatter:off @@ -85,7 +94,7 @@ public class PdpStatusMessageHandlerTest { new SQLIntegrityConstraintViolationException()), HibernateException.class)) .isTrue(); - // multiple cause both inside and outside of the eclipselink exception + // multiple cause both inside and outside the eclipselink exception assertThat(PdpStatusMessageHandler.isDuplicateKeyException( new Exception( new Exception( @@ -98,6 +107,7 @@ public class PdpStatusMessageHandlerTest { } public static class MyHibernateException extends HibernateException { + @Serial private static final long serialVersionUID = 1L; public MyHibernateException() { diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java index c33790aa..ed93a06c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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,19 +23,19 @@ package org.onap.policy.pap.main.comm; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +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 java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.event.comm.TopicListener; @@ -82,9 +82,8 @@ public class PublisherTest extends Threaded { /** * Configures the topic and attaches a listener. - * */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { final PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); TopicEndpointManager.getManager().shutdown(); @@ -93,7 +92,7 @@ public class PublisherTest extends Threaded { TopicEndpointManager.getManager().start(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { TopicEndpointManager.getManager().shutdown(); } @@ -103,7 +102,7 @@ public class PublisherTest extends Threaded { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -118,7 +117,7 @@ public class PublisherTest extends Threaded { * * @throws Exception if an error occurs */ - @After + @AfterEach public void tearDown() throws Exception { TopicEndpointManager.getManager().getNoopTopicSink(PDP_PAP_TOPIC).unregister(listener); @@ -238,9 +237,8 @@ public class PublisherTest extends Threaded { /** * Waits for a message to be published to the topic. * - * @param waitMs time to wait, in milli-seconds - * @return the next message in the queue, or {@code null} if there are no messages - * or if the timeout was reached + * @param waitMs time to wait, in milliseconds + * @return the next message in the queue, or {@code null} if there are no messages/timeout was reached * @throws InterruptedException if this thread was interrupted while waiting */ public String await(long waitMs) throws InterruptedException { diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/QueueTokenTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/QueueTokenTest.java index 3ff91edf..ada00101 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/QueueTokenTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/QueueTokenTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,21 +21,22 @@ package org.onap.policy.pap.main.comm; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class QueueTokenTest { +class QueueTokenTest { private static final String STRING1 = "a string"; private static final String STRING2 = "another string"; private QueueToken<String> token; @Test - public void test() throws Exception { + void test() throws Exception { token = new QueueToken<>(STRING1); assertEquals(STRING1, token.get()); @@ -42,13 +44,13 @@ public class QueueTokenTest { assertEquals(STRING2, token.get()); assertEquals(STRING2, token.replaceItem(null)); - assertEquals(null, token.get()); + assertNull(token.get()); - assertEquals(null, token.replaceItem(null)); - assertEquals(null, token.get()); + assertNull(token.replaceItem(null)); + assertNull(token.get()); - assertEquals(null, token.replaceItem(STRING1)); - assertEquals(null, token.get()); + assertNull(token.replaceItem(STRING1)); + assertNull(token.get()); /* * Now do some mult-threaded tests, hopefully causing some contention. @@ -80,7 +82,7 @@ public class QueueTokenTest { for (int x = 0; x < threads.length; ++x) { String msg = "me-" + x; - assertTrue(msg, values.contains(msg)); + assertTrue(values.contains(msg), msg); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/Threaded.java b/main/src/test/java/org/onap/policy/pap/main/comm/Threaded.java index d6a0d1f1..c2f0e66d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/Threaded.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/Threaded.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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.pap.main.comm; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; /** * Super class for tests that run a background thread. @@ -44,7 +45,7 @@ public abstract class Threaded { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { thread = null; } @@ -55,7 +56,7 @@ public abstract class Threaded { * * @throws Exception if an error occurs */ - @After + @AfterEach public void tearDown() throws Exception { stopThread(); waitStop(); diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java index d0f960fc..254e4678 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,9 +31,9 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.pap.main.comm.TimerManager.Timer; public class TimerManagerTest extends Threaded { @@ -57,14 +58,14 @@ public class TimerManagerTest extends Threaded { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); mgr = new MyManager(MGR_NAME, MGR_TIMEOUT_MS); } - @After + @AfterEach public void tearDown() throws Exception { super.tearDown(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/RequestImplTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/RequestImplTest.java index dd635627..c49ebd9c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/RequestImplTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/RequestImplTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020, 2023 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,13 +24,13 @@ package org.onap.policy.pap.main.comm.msgdata; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; @@ -38,8 +38,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpResponseDetails; import org.onap.policy.models.pdp.concepts.PdpStateChange; @@ -59,7 +59,7 @@ public class RequestImplTest extends CommonRequestBase { * Sets up. * @throws Exception if an error occurs */ - @Before + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -120,8 +120,8 @@ public class RequestImplTest extends CommonRequestBase { // should only be one token in the queue QueueToken<PdpMessage> token = queue.poll(); - assertNotNull(token); - assertSame(msg2, token.get()); + org.junit.jupiter.api.Assertions.assertNotNull(token); + org.junit.jupiter.api.Assertions.assertSame(msg2, token.get()); verify(dispatcher).register(eq(msg.getRequestId()), any()); verify(timers).register(eq(msg.getRequestId()), any()); @@ -269,7 +269,7 @@ public class RequestImplTest extends CommonRequestBase { @Test public void testResetRetryCount_testBumpRetryCount() { req = new MyRequest(new RequestParams().setMaxRetryCount(2).setModifyLock(lock).setPdpPublisher(publisher) - .setResponseDispatcher(dispatcher).setTimers(timers), MY_REQ_NAME, msg); + .setResponseDispatcher(dispatcher).setTimers(timers), MY_REQ_NAME, msg); req.setListener(listener); assertEquals(0, req.getRetryCount()); @@ -455,7 +455,7 @@ public class RequestImplTest extends CommonRequestBase { assertTrue(req.getUndeployPolicies().isEmpty()); } - private class MyRequest extends RequestImpl { + private static class MyRequest extends RequestImpl { public MyRequest(RequestParams params, String name, PdpMessage message) { super(params, name, message); diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/StateChangeReqTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/StateChangeReqTest.java index e16cd899..e0185890 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/StateChangeReqTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/StateChangeReqTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,14 +21,14 @@ package org.onap.policy.pap.main.comm.msgdata; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -45,7 +46,7 @@ public class StateChangeReqTest extends CommonRequestBase { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -83,7 +84,7 @@ public class StateChangeReqTest extends CommonRequestBase { public void testCheckResponse_NullMsgName() { msg.setName(null); - assertEquals(null, data.checkResponse(response)); + assertNull(data.checkResponse(response)); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java index 53e78e52..7d62c7ef 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021,2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 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,11 +23,11 @@ package org.onap.policy.pap.main.comm.msgdata; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -40,10 +40,8 @@ import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -51,8 +49,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.CommonRequestBase; -@RunWith(MockitoJUnitRunner.class) -public class UpdateReqTest extends CommonRequestBase { +class UpdateReqTest extends CommonRequestBase { private UpdateReq data; private PdpUpdate update; @@ -64,7 +61,7 @@ public class UpdateReqTest extends CommonRequestBase { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -76,21 +73,21 @@ public class UpdateReqTest extends CommonRequestBase { response.setPdpGroup(update.getPdpGroup()); response.setPdpSubgroup(update.getPdpSubgroup()); response.setPolicies( - update.getPoliciesToBeDeployed().stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList())); + update.getPoliciesToBeDeployed().stream().map(ToscaPolicy::getIdentifier) + .collect(Collectors.toList())); data = new UpdateReq(reqParams, MY_REQ_NAME, update); data.setNotifier(notifier); } @Test - public void testGetMessage() { + void testGetMessage() { assertEquals(MY_REQ_NAME, data.getName()); assertSame(update, data.getMessage()); } @Test - public void testCheckResponse() { + void testCheckResponse() { assertNull(data.checkResponse(response)); assertTrue(data.getUndeployPolicies().isEmpty()); verifyResponse(); @@ -103,7 +100,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testCheckResponse_NullName() { + void testCheckResponse_NullName() { response.setName(null); assertEquals("null PDP name", data.checkResponse(response)); @@ -112,16 +109,16 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testCheckResponse_NullMsgName() { + void testCheckResponse_NullMsgName() { update.setName(null); - assertEquals(null, data.checkResponse(response)); + assertNull(data.checkResponse(response)); assertTrue(data.getUndeployPolicies().isEmpty()); verifyResponse(); } @Test - public void testUpdateReqCheckResponse_MismatchedGroup() { + void testUpdateReqCheckResponse_MismatchedGroup() { response.setPdpGroup(DIFFERENT); assertEquals("group does not match", data.checkResponse(response)); @@ -130,7 +127,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testUpdateReqCheckResponse_MismatchedSubGroup() { + void testUpdateReqCheckResponse_MismatchedSubGroup() { response.setPdpSubgroup(DIFFERENT); assertEquals("subgroup does not match", data.checkResponse(response)); @@ -139,20 +136,20 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testCheckResponse_NullSubGroup() { + void testCheckResponse_NullSubGroup() { update.setPdpSubgroup(null); response.setPdpSubgroup(null); // different policy list - should have no impact response.setPolicies(Collections.emptyList()); - assertEquals(null, data.checkResponse(response)); + assertNull(data.checkResponse(response)); assertTrue(data.getUndeployPolicies().isEmpty()); verifyNoResponse(); } @Test - public void testUpdateReqCheckResponse_MismatchedPolicies() { + void testUpdateReqCheckResponse_MismatchedPolicies() { ArrayList<ToscaPolicy> policies = new ArrayList<>(update.getPoliciesToBeDeployed()); policies.set(0, makePolicy(DIFFERENT, "10.0.0")); @@ -163,20 +160,20 @@ public class UpdateReqTest extends CommonRequestBase { // the first policy from the original update is all that should be undeployed assertEquals(Collections.singleton(update.getPoliciesToBeDeployed().get(0).getIdentifier()).toString(), - data.getUndeployPolicies().toString()); + data.getUndeployPolicies().toString()); } @Test - public void testUpdateReqCheckResponse_MismatchedPolicies_Null_NotNull() { + void testUpdateReqCheckResponse_MismatchedPolicies_Null_NotNull() { update.setPoliciesToBeDeployed(null); - assertEquals(null, data.checkResponse(response)); + assertNull(data.checkResponse(response)); assertTrue(data.getUndeployPolicies().isEmpty()); verifyResponse(); } @Test - public void testUpdateReqCheckResponse_MismatchedPolicies_NotNull_Null() { + void testUpdateReqCheckResponse_MismatchedPolicies_NotNull_Null() { response.setPolicies(null); assertEquals("policies do not match", data.checkResponse(response)); @@ -184,12 +181,11 @@ public class UpdateReqTest extends CommonRequestBase { // all policies in the update should be undeployed assertEquals(update.getPoliciesToBeDeployed().stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()) - .toString(), new TreeSet<>(data.getUndeployPolicies()).toString()); + .toList().toString(), new TreeSet<>(data.getUndeployPolicies()).toString()); } @Test - public void testReconfigure() { + void testReconfigure() { // different message type should fail and leave message unchanged assertFalse(data.reconfigure(new PdpStateChange())); assertSame(update, data.getMessage()); @@ -216,7 +212,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testReconfigureIsFullSameAsDeployList() { + void testReconfigureIsFullSameAsDeployList() { PdpUpdate msg2 = new PdpUpdate(update); ArrayList<ToscaPolicy> policies = new ArrayList<>(update.getPoliciesToBeDeployed()); @@ -226,7 +222,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testListsNewVsResult() { + void testListsNewVsResult() { PdpUpdate msg2 = new PdpUpdate(update); ArrayList<ToscaPolicy> policies = new ArrayList<>(update.getPoliciesToBeDeployed()); @@ -246,8 +242,8 @@ public class UpdateReqTest extends CommonRequestBase { policies.clear(); policies = new ArrayList<>(update.getPoliciesToBeDeployed()); List<ToscaConceptIdentifier> polsToUndep = policies.parallelStream() - .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .map(ToscaPolicy::getIdentifier) + .collect(Collectors.toList()); msg2.setPoliciesToBeUndeployed(polsToUndep); assertTrue(data.reconfigure(msg2)); @@ -261,7 +257,7 @@ public class UpdateReqTest extends CommonRequestBase { // some items in both undeploy and newMessage.undeploy List<ToscaConceptIdentifier> pols = policies.stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .collect(Collectors.toList()); msg2.setPoliciesToBeUndeployed(pols); pols.add(makePolicy("policy-zz-1", "1.1.0").getIdentifier()); data.getMessage().setPoliciesToBeUndeployed(pols); @@ -271,8 +267,8 @@ public class UpdateReqTest extends CommonRequestBase { // some items in both undeploy and newMessage.deploy policies = new ArrayList<>(update.getPoliciesToBeDeployed()); List<ToscaConceptIdentifier> polsToUndep2 = policies.parallelStream() - .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .map(ToscaPolicy::getIdentifier) + .collect(Collectors.toList()); data.getMessage().setPoliciesToBeUndeployed(polsToUndep2); List<ToscaPolicy> polsToDep2 = new LinkedList<>(); @@ -283,14 +279,14 @@ public class UpdateReqTest extends CommonRequestBase { assertTrue(data.reconfigure(msg2)); List<ToscaConceptIdentifier> dataPols2 = data.getMessage().getPoliciesToBeDeployed().stream() - .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .map(ToscaPolicy::getIdentifier) + .collect(Collectors.toList()); assertThat(data.getMessage().getPoliciesToBeUndeployed()) - .doesNotContainAnyElementsOf(dataPols2); + .doesNotContainAnyElementsOf(dataPols2); // some items only in undeploy pols = policies.stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .collect(Collectors.toList()); msg2.setPoliciesToBeUndeployed(pols); data.getMessage().setPoliciesToBeUndeployed(new LinkedList<>()); assertTrue(data.reconfigure(msg2)); @@ -298,7 +294,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent() { + void testIsSameContent() { data = new UpdateReq(reqParams, MY_REQ_NAME, update); data.setNotifier(notifier); @@ -317,7 +313,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_BothGroupNamesNull() { + void testIsSameContent_BothGroupNamesNull() { PdpUpdate msg2 = new PdpUpdate(update); msg2.setPdpGroup(null); update.setPdpGroup(null); @@ -325,7 +321,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_BothSubGroupNamesNull() { + void testIsSameContent_BothSubGroupNamesNull() { PdpUpdate msg2 = new PdpUpdate(update); msg2.setPdpSubgroup(null); update.setPdpSubgroup(null); @@ -333,7 +329,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_DiffGroup() { + void testIsSameContent_DiffGroup() { PdpUpdate msg2 = new PdpUpdate(update); msg2.setPdpGroup(null); assertFalse(data.isSameContent(msg2)); @@ -346,7 +342,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_DiffSubGroup() { + void testIsSameContent_DiffSubGroup() { PdpUpdate msg2 = new PdpUpdate(update); msg2.setPdpSubgroup(null); assertFalse(data.isSameContent(msg2)); @@ -359,7 +355,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_DiffPolicies() { + void testIsSameContent_DiffPolicies() { PdpUpdate msg2 = new PdpUpdate(update); ArrayList<ToscaPolicy> policies = new ArrayList<>(update.getPoliciesToBeDeployed()); @@ -370,7 +366,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_DiffPolicies_NotNull_Null() { + void testIsSameContent_DiffPolicies_NotNull_Null() { PdpUpdate msg2 = new PdpUpdate(update); msg2.setPoliciesToBeDeployed(null); @@ -378,7 +374,7 @@ public class UpdateReqTest extends CommonRequestBase { } @Test - public void testIsSameContent_DiffPolicies_Null_NotNull() { + void testIsSameContent_DiffPolicies_Null_NotNull() { final PdpUpdate msg2 = new PdpUpdate(update); update.setPoliciesToBeDeployed(null); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java index 306ec8cd..188bece0 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,24 +28,22 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import lombok.NonNull; import org.apache.commons.lang3.builder.CompareToBuilder; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -55,7 +54,6 @@ import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.notification.StatusAction.Action; import org.onap.policy.pap.main.service.PolicyStatusService; -@RunWith(MockitoJUnitRunner.class) public class DeploymentStatusTest { private static final String VERSION = "1.2.3"; @@ -85,10 +83,12 @@ public class DeploymentStatusTest { private DeploymentStatus tracker; + AutoCloseable autoCloseable; + /** * Set up the meter registry for tests. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { Registry.registerOrReplace(PapConstants.REG_METER_REGISTRY, new SimpleMeterRegistry()); } @@ -96,7 +96,7 @@ public class DeploymentStatusTest { /** * Tear down the meter registry after tests. */ - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.unregister(PapConstants.REG_METER_REGISTRY); } @@ -104,8 +104,9 @@ public class DeploymentStatusTest { /** * Sets up. */ - @Before + @BeforeEach public void setUp() { + autoCloseable = MockitoAnnotations.openMocks(this); tracker = new DeploymentStatus(policyStatusService); // @formatter:off @@ -121,8 +122,13 @@ public class DeploymentStatusTest { } + @AfterEach + void tearDown() throws Exception { + autoCloseable.close(); + } + @Test - public void testAddNotifications() { + void testAddNotifications() { PdpPolicyStatus create = builder.pdpId("created").state(State.FAILURE).build(); PdpPolicyStatus update = builder.pdpId("updated").state(State.SUCCESS).build(); PdpPolicyStatus delete = builder.pdpId("deleted").state(State.SUCCESS).build(); @@ -160,7 +166,7 @@ public class DeploymentStatusTest { } @Test - public void testLoadByGroup() throws PfModelException { + void testLoadByGroup() { PdpPolicyStatus status1 = builder.build(); PdpPolicyStatus status2 = builder.policy(POLICY_B).build(); PdpPolicyStatus status3 = builder.policy(POLICY_A).pdpId(PDP_B).build(); @@ -183,7 +189,7 @@ public class DeploymentStatusTest { } @Test - public void testFlushPdpNotification() { + void testFlushPdpNotification() { PdpPolicyStatus create = builder.pdpId("created").state(State.FAILURE).build(); tracker.getRecordMap().putAll(makeMap(Action.CREATED, create)); @@ -196,7 +202,7 @@ public class DeploymentStatusTest { } @Test - public void testFlush() throws PfModelException { + void testFlush() { PdpPolicyStatus create1 = builder.pdpId("createA").build(); PdpPolicyStatus create2 = builder.pdpId("createB").build(); PdpPolicyStatus update1 = builder.pdpId("updateA").build(); @@ -240,7 +246,7 @@ public class DeploymentStatusTest { } @Test - public void testDeleteUndeployments() { + void testDeleteUndeployments() { builder.deploy(true); PdpPolicyStatus delete = builder.policy(POLICY_A).build(); PdpPolicyStatus deployedComplete = builder.policy(POLICY_B).build(); @@ -283,7 +289,7 @@ public class DeploymentStatusTest { } @Test - public void testDeleteDeploymentString() { + void testDeleteDeploymentString() { PdpPolicyStatus statusaa = builder.pdpId(PDP_A).policy(POLICY_A).build(); PdpPolicyStatus statusab = builder.pdpId(PDP_A).policy(POLICY_B).build(); PdpPolicyStatus statusba = builder.pdpId(PDP_B).policy(POLICY_A).build(); @@ -311,7 +317,7 @@ public class DeploymentStatusTest { } @Test - public void testDeleteDeploymentToscaConceptIdentifierBoolean() { + void testDeleteDeploymentToscaConceptIdentifierBoolean() { PdpPolicyStatus deploy1A = builder.policy(POLICY_A).build(); PdpPolicyStatus deploy2A = builder.policy(POLICY_A).pdpId(PDP_B).build(); PdpPolicyStatus deployB = builder.policy(POLICY_B).pdpId(PDP_A).build(); @@ -356,7 +362,7 @@ public class DeploymentStatusTest { } @Test - public void testDeleteDeploymentBiPredicateOfStatusKeyStatusAction() { + void testDeleteDeploymentBiPredicateOfStatusKeyStatusAction() { PdpPolicyStatus create1 = builder.pdpId(PDP_A).build(); PdpPolicyStatus delete = builder.pdpId(PDP_B).build(); PdpPolicyStatus update = builder.pdpId(PDP_C).build(); @@ -386,7 +392,7 @@ public class DeploymentStatusTest { } @Test - public void testDeploy() { + void testDeploy() { tracker.deploy(PDP_A, POLICY_A, POLICY_TYPE, GROUP_A, PDP_TYPE, true); assertThat(tracker.getRecordMap()).hasSize(1); @@ -450,7 +456,7 @@ public class DeploymentStatusTest { } @Test - public void testCompleteDeploy() { + void testCompleteDeploy() { tracker.deploy(PDP_A, POLICY_A, POLICY_TYPE, GROUP_A, PDP_TYPE, true); assertThat(tracker.getRecordMap()).hasSize(1); @@ -503,7 +509,7 @@ public class DeploymentStatusTest { } private void checkCompleteDeploy(boolean deploy, Set<ToscaConceptIdentifier> expected, - Set<ToscaConceptIdentifier> actual, Action action, State state) { + Set<ToscaConceptIdentifier> actual, Action action, State state) { StatusAction status = tracker.getRecordMap().values().iterator().next(); status.getStatus().setDeploy(deploy); @@ -518,7 +524,7 @@ public class DeploymentStatusTest { private List<PdpPolicyStatus> sort(List<PdpPolicyStatus> list) { - Collections.sort(list, (rec1, rec2) -> { + list.sort((rec1, rec2) -> { // @formatter:off return new CompareToBuilder() diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentTrackerTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentTrackerTest.java index 22eb8786..3c351e50 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentTrackerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentTrackerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,11 +25,11 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; +import java.util.Comparator; import java.util.Iterator; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -36,7 +37,7 @@ import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.PdpPolicyStatusBuilde import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -public class DeploymentTrackerTest { +class DeploymentTrackerTest { private static final String VERSION = "1.2.3"; private static final String MY_GROUP = "MyGroup"; private static final String MY_PDP_TYPE = "MyPdpType"; @@ -52,15 +53,15 @@ public class DeploymentTrackerTest { /** * Sets up test objects. */ - @Before + @BeforeEach public void setUp() { tracker = new DeploymentTracker(); builder = PdpPolicyStatus.builder().deploy(true).state(State.SUCCESS).pdpGroup(MY_GROUP).pdpType(MY_PDP_TYPE) - .policy(POLICY_A).policyType(POLICY_TYPE).pdpId(PDP_A); + .policy(POLICY_A).policyType(POLICY_TYPE).pdpId(PDP_A); } @Test - public void testGetDeploymentStatus() { + void testGetDeploymentStatus() { assertThat(tracker.getDeploymentStatus()).isEmpty(); tracker.add(builder.build()); @@ -71,7 +72,7 @@ public class DeploymentTrackerTest { } @Test - public void testGetUndeploymentStatus() { + void testGetUndeploymentStatus() { builder.deploy(false); assertThat(tracker.getUndeploymentStatus()).isEmpty(); @@ -84,7 +85,7 @@ public class DeploymentTrackerTest { } @Test - public void testAddNotifications() { + void testAddNotifications() { DeploymentTracker newTracker = new DeploymentTracker(); newTracker.add(builder.build()); @@ -101,7 +102,7 @@ public class DeploymentTrackerTest { } @Test - public void testMerge() { + void testMerge() { DeploymentTracker newTracker = new DeploymentTracker(); // appears in both @@ -122,7 +123,7 @@ public class DeploymentTrackerTest { } @Test - public void testNeedNotification() { + void testNeedNotification() { final PolicyStatus oldStat = new PolicyStatus(); final PolicyStatus newStat = new PolicyStatus(); @@ -168,7 +169,7 @@ public class DeploymentTrackerTest { } @Test - public void testAddMissing() { + void testAddMissing() { DeploymentTracker newTracker = new DeploymentTracker(); // appears in both, not waiting @@ -197,7 +198,7 @@ public class DeploymentTrackerTest { } @Test - public void testAddStatusAction() { + void testAddStatusAction() { tracker.add(new StatusAction(StatusAction.Action.DELETED, builder.build())); assertThat(tracker.getDeploymentStatus()).isEmpty(); @@ -212,7 +213,7 @@ public class DeploymentTrackerTest { } @Test - public void testAddPdpPolicyStatus() { + void testAddPdpPolicyStatus() { tracker.add(builder.build()); Collection<PolicyStatus> result = tracker.getDeploymentStatus(); assertThat(result).hasSize(1); @@ -250,7 +251,7 @@ public class DeploymentTrackerTest { assertThat(result).hasSize(2); List<PolicyStatus> list = new ArrayList<>(result); - Collections.sort(list, (rec1, rec2) -> rec1.getPolicy().compareTo(rec2.getPolicy())); + list.sort(Comparator.comparing(PolicyStatus::getPolicy)); Iterator<PolicyStatus> iter = list.iterator(); status = iter.next(); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java index 48e3f57e..69c74205 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -32,15 +32,17 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import jakarta.ws.rs.core.Response.Status; import java.util.Collections; import java.util.Set; -import javax.ws.rs.core.Response.Status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; @@ -55,7 +57,7 @@ import org.onap.policy.pap.main.comm.QueueToken; import org.onap.policy.pap.main.service.PolicyStatusService; @RunWith(MockitoJUnitRunner.class) -public class PolicyNotifierTest { +class PolicyNotifierTest { private static final String GROUP_A = "groupA"; private static final String PDP1 = "pdp-1"; private static final ToscaConceptIdentifier policy1 = new ToscaConceptIdentifier("policy1", "1.2.3"); @@ -70,28 +72,19 @@ public class PolicyNotifierTest { @Mock private DeploymentStatus tracker; - @Mock - private PolicyStatus status1; - - @Mock - private PolicyStatus status2; - - @Mock - private PolicyStatus status3; - - @Mock - private PolicyStatus status4; - @Captor ArgumentCaptor<QueueToken<PolicyNotification>> notifyCaptor; private MyNotifier notifier; + AutoCloseable closeable; + /** * Creates various objects, including {@link #notifier}. */ - @Before + @BeforeEach public void setUp() { + closeable = MockitoAnnotations.openMocks(this); try { when(policyStatusService.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); Registry.registerOrReplace(PapConstants.REG_METER_REGISTRY, new SimpleMeterRegistry()); @@ -102,8 +95,13 @@ public class PolicyNotifierTest { } } + @AfterEach + void tearDown() throws Exception { + closeable.close(); + } + @Test - public void testProcessResponseString() throws PfModelException { + void testProcessResponseString() { Set<ToscaConceptIdentifier> expected = Set.of(policy1); Set<ToscaConceptIdentifier> actual = Set.of(policy2); @@ -124,7 +122,7 @@ public class PolicyNotifierTest { } @Test - public void testProcessResponseString_Ex() throws PfModelException { + void testProcessResponseString_Ex() { doThrow(new PfModelRuntimeException(Status.BAD_REQUEST, "expected exception")).when(tracker) .loadByGroup(anyString()); @@ -135,7 +133,7 @@ public class PolicyNotifierTest { * Tests publish(), when the notification is empty. */ @Test - public void testPublishEmpty() { + void testPublishEmpty() { notifier.publish(new PolicyNotification()); verify(publisher, never()).enqueue(any()); } @@ -144,7 +142,7 @@ public class PolicyNotifierTest { * Tests publish(), when the notification is NOT empty. */ @Test - public void testPublishNotEmpty() { + void testPublishNotEmpty() { PolicyNotification notif = new PolicyNotification(); notif.getAdded().add(new PolicyStatus()); @@ -154,7 +152,7 @@ public class PolicyNotifierTest { } @Test - public void testMakeDeploymentTracker() throws PfModelException { + void testMakeDeploymentTracker() { // make real object, which will invoke the real makeXxx() methods PolicyNotifier policyNotifier = new PolicyNotifier(policyStatusService); policyNotifier.setPublisher(publisher); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/StatusActionTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/StatusActionTest.java index 3303a9b2..17a6141e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/StatusActionTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/StatusActionTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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.pap.main.notification; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Only test the methods that are not generated by lombok. */ -public class StatusActionTest { +class StatusActionTest { @Test - public void testSetChanged() { + void testSetChanged() { StatusAction status = new StatusAction(StatusAction.Action.UNCHANGED, null); // new records should always remain new - action should not change diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/StatusKeyTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/StatusKeyTest.java index 558c6bc2..cdad7ea1 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/StatusKeyTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/StatusKeyTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,17 +23,17 @@ package org.onap.policy.pap.main.notification; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; /** * Only test the methods that are not generated by lombok. */ -public class StatusKeyTest { +class StatusKeyTest { @Test - public void testStatusKeyPdpPolicyStatus() { + void testStatusKeyPdpPolicyStatus() { ToscaConceptIdentifier myPolicy = new ToscaConceptIdentifier(); StatusKey key = new StatusKey(PdpPolicyStatus.builder().pdpId("myPdp").policy(myPolicy).build()); diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java index d52e21f4..5e0e8f2c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2023 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * Modification Copyright 2022. Nordix Foundation. @@ -24,11 +24,11 @@ package org.onap.policy.pap.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.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 org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java index c41915d2..affc3b36 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2023 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,11 +25,11 @@ package org.onap.policy.pap.main.parameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.mock; -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.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; @@ -49,7 +50,7 @@ public class TestPdpModifyRequestMapParams { /** * Sets up the objects and creates an empty {@link #builder}. */ - @Before + @BeforeEach @SuppressWarnings("unchecked") public void setUp() { pub = mock(Publisher.class); diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpParameters.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpParameters.java index 19192dad..791f1f34 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpParameters.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,13 +22,13 @@ package org.onap.policy.pap.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.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 org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpRequestParameters.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpRequestParameters.java index 810bc448..2c07925c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpRequestParameters.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpRequestParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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 +22,12 @@ package org.onap.policy.pap.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 org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpStateChangeParameters.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpStateChangeParameters.java index 45cbe372..dba174c7 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpStateChangeParameters.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpStateChangeParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,10 +21,10 @@ package org.onap.policy.pap.main.parameters; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpUpdateParameters.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpUpdateParameters.java index 814894c6..56a967e3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpUpdateParameters.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpUpdateParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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,10 +21,10 @@ package org.onap.policy.pap.main.parameters; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestRequestParams.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestRequestParams.java index 7c5a3954..5d48f0d5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestRequestParams.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestRequestParams.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 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 +22,12 @@ package org.onap.policy.pap.main.parameters; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -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.Mockito.mock; -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.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; @@ -45,7 +46,7 @@ public class TestRequestParams { /** * Sets up the objects and creates an empty {@link #params}. */ - @Before + @BeforeEach @SuppressWarnings("unchecked") public void setUp() { pub = mock(Publisher.class); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index ca81ab7d..fe22cd89 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019,2023 Nordix Foundation. + * Copyright (C) 2019, 2023 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -22,28 +22,29 @@ package org.onap.policy.pap.main.rest; -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 jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.net.ssl.SSLContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; +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.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; @@ -61,7 +62,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; /** @@ -69,7 +69,6 @@ import org.springframework.test.util.ReflectionTestUtils; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@RunWith(SpringRunner.class) @SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"db.initialize=false"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -98,7 +97,7 @@ public abstract class CommonPapRestServer { * * @throws Exception if an error occurs */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { keystore = new SelfSignedKeyStore(); CommonTestData.newDb(); @@ -122,7 +121,7 @@ public abstract class CommonPapRestServer { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { httpsPrefix = "https://localhost:" + port + "/"; papActivator = Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class); @@ -132,11 +131,16 @@ public abstract class CommonPapRestServer { /** * Restores the activator's "alive" state. */ - @After + @AfterEach public void tearDown() { markActivator(activatorWasAlive); } + @AfterAll + public static void cleanRegistry() { + Registry.newRegistry(); + } + /** * Verifies that an endpoint appears within the swagger response. * @@ -145,7 +149,7 @@ public abstract class CommonPapRestServer { */ protected void testSwagger(final String endpoint) throws Exception { final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix - + ENDPOINT_PREFIX + "v3/api-docs", true, MediaType.APPLICATION_JSON); + + ENDPOINT_PREFIX + "v3/api-docs", true, MediaType.APPLICATION_JSON); final String resp = invocationBuilder.get(String.class); assertTrue(resp.contains(endpoint)); } @@ -175,7 +179,8 @@ public abstract class CommonPapRestServer { private void markActivator(boolean wasAlive) { Object manager = ReflectionTestUtils.getField(papActivator, "serviceManager"); - AtomicBoolean running = (AtomicBoolean) ReflectionTestUtils.getField(manager, "running"); + AtomicBoolean running = (AtomicBoolean) ReflectionTestUtils + .getField(Objects.requireNonNull(manager), "running"); running.set(wasAlive); } @@ -183,13 +188,13 @@ public abstract class CommonPapRestServer { * Verifies that unauthorized requests fail. * * @param endpoint the target end point - * @param sender function that sends the requests to the target + * @param sender function that sends the requests to the target * @throws Exception if an error occurs */ protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender) - throws Exception { + throws Exception { assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), - sender.apply(sendNoAuthRequest(endpoint)).getStatus()); + sender.apply(sendNoAuthRequest(endpoint)).getStatus()); } /** @@ -206,7 +211,7 @@ public abstract class CommonPapRestServer { /** * Sends a request to an endpoint. * - * @param endpoint the target endpoint + * @param endpoint the target endpoint * @param mediaType the media type for the request * @return a request builder * @throws Exception if an error occurs @@ -230,21 +235,21 @@ public abstract class CommonPapRestServer { * Sends a request to a fully qualified endpoint. * * @param fullyQualifiedEndpoint the fully qualified target endpoint - * @param includeAuth if authorization header should be included + * @param includeAuth if authorization header should be included * @return a request builder * @throws Exception if an error occurs */ protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth, - String mediaType) throws Exception { + String mediaType) throws Exception { final SSLContext sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom()); final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); + ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); final Client client = clientBuilder.build(); client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); client.register((mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON) ? GsonMessageBodyHandler.class - : YamlMessageBodyHandler.class)); + : YamlMessageBodyHandler.class)); if (includeAuth) { final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34"); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java index d1d29f0c..8faf2d25 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,11 +26,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import jakarta.ws.rs.core.SecurityContext; import java.util.UUID; -import javax.ws.rs.core.SecurityContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.ResponseEntity; @@ -44,13 +44,13 @@ public class PapRestControllerV1Test { private AutoCloseable closeable; private BodyBuilder bldr; - @Before + @BeforeEach public void setUp() { bldr = ResponseEntity.ok(); closeable = MockitoAnnotations.openMocks(this); } - @After + @AfterEach public void after() throws Exception { closeable.close(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java index 60de563e..e5a83305 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2022 Nordix Foundation. + * Modifications Copyright (C) 2021-2023 Nordix Foundation. * Modifications Copyright (C) 2022-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,7 +23,7 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -37,7 +37,8 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -95,15 +96,17 @@ public class ProviderSuper { protected ToscaPolicy policy1; protected MeterRegistry meterRegistry; + AutoCloseable closeable; + /** * Configures DAO, captors, and various mocks. */ - @Before + @BeforeEach public void setUp() throws Exception { Registry.newRegistry(); - MockitoAnnotations.openMocks(this); + closeable = MockitoAnnotations.openMocks(this); reqmap = mock(PdpModifyRequestMap.class); @@ -125,6 +128,11 @@ public class ProviderSuper { } + @AfterEach + public void tearDown() throws Exception { + closeable.close(); + } + /** * Initialize services to the provider for tests. * @@ -280,7 +288,7 @@ public class ProviderSuper { * Loads an object from a JSON file. * * @param fileName name of the file from which to load - * @param clazz the class of the object to be loaded + * @param clazz the class of the object to be loaded * @return the object that was loaded from the file */ protected <T> T loadFile(String fileName, Class<T> clazz) { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestActuatorEndpoints.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestActuatorEndpoints.java index 3fdb1f42..d1efa895 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestActuatorEndpoints.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestActuatorEndpoints.java @@ -20,17 +20,16 @@ package org.onap.policy.pap.main.rest; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.pap.main.PolicyPapApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @@ -38,13 +37,13 @@ import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"db.initialize=false"}) @ActiveProfiles("test") @AutoConfigureMockMvc @ContextConfiguration @@ -57,7 +56,10 @@ public class TestActuatorEndpoints { @Autowired private MockMvc mock; - @BeforeClass + private final RequestPostProcessor mockSecurity = SecurityMockMvcRequestPostProcessors + .httpBasic("policyAdmin", "zb!XztG34"); + + @BeforeAll public static void setupClass() { Registry.newRegistry(); } @@ -68,17 +70,8 @@ public class TestActuatorEndpoints { } @Test - public void testMetricsEndpoint() throws Exception { - mock.perform(get("/plain-metrics").with(SecurityMockMvcRequestPostProcessors.httpBasic( - "policyAdmin", "zb!XztG34"))) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(jsonPath("$").isNotEmpty()); - } - - @Test - public void testPrometheusEndpoint() throws Exception { - mock.perform(get("/metrics").with(SecurityMockMvcRequestPostProcessors.httpBasic("policyAdmin", "zb!XztG34"))) + void testPrometheusEndpoint() throws Exception { + mock.perform(get("/metrics").with(mockSecurity)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$").isNotEmpty()); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestGroupData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestGroupData.java index 5eb5611f..47c4c28e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestGroupData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestGroupData.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +26,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpGroup; public class TestGroupData { @@ -39,7 +40,7 @@ public class TestGroupData { /** * Sets up. */ - @Before + @BeforeEach public void setUp() { oldGroup = new PdpGroup(); oldGroup.setName(NAME); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java index e5823bc3..c1058a78 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ @@ -23,12 +23,12 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.SyncInvoker; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.SyncInvoker; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.report.HealthCheckReport; import org.onap.policy.models.base.PfModelRuntimeException; import org.springframework.boot.test.mock.mockito.MockBean; @@ -39,8 +39,8 @@ import org.springframework.test.context.ActiveProfiles; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@ActiveProfiles({ "test", "default" }) -public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { +@ActiveProfiles({"test", "default"}) +class TestHealthCheckRestControllerV1 extends CommonPapRestServer { private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; @@ -48,12 +48,12 @@ public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { private PolicyStatusProvider policyStatusProvider; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(HEALTHCHECK_ENDPOINT); } @Test - public void testHealthCheckSuccess() throws Exception { + void testHealthCheckSuccess() throws Exception { final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); validateHealthCheckReport(true, 200, ALIVE, report); @@ -63,7 +63,7 @@ public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { } @Test - public void testHealthCheckActivatorFailure() throws Exception { + void testHealthCheckActivatorFailure() throws Exception { markActivatorDead(); @@ -75,7 +75,7 @@ public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { } @Test - public void testHealthCheckDbConnectionFailure() throws Exception { + void testHealthCheckDbConnectionFailure() throws Exception { when(policyStatusProvider.getPolicyStatus()).thenThrow(PfModelRuntimeException.class); final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); var response = invocationBuilder.get(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateControllerV1.java index c5442fad..7303fd92 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateControllerV1.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 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,12 +23,12 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.util.List; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpGroupUpdateResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index 7666dc2a..afbe5492 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -1,561 +1,562 @@ -/*
- * ============LICENSE_START=======================================================
- * ONAP PAP
- * ================================================================================
- * Copyright (C) 2019-2021 Nordix Foundation.
- * Modifications Copyright (C) 2021 AT&T Intellectual Property.
- * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.pap.main.rest;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.TreeMap;
-import javax.ws.rs.core.Response.Status;
-import org.assertj.core.api.Assertions;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.common.utils.services.Registry;
-import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.pdp.concepts.PdpGroup;
-import org.onap.policy.models.pdp.concepts.PdpGroups;
-import org.onap.policy.models.pdp.concepts.PdpStateChange;
-import org.onap.policy.models.pdp.concepts.PdpSubGroup;
-import org.onap.policy.models.pdp.concepts.PdpUpdate;
-import org.onap.policy.models.pdp.enums.PdpState;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.pap.main.PapConstants;
-
-public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper {
- private static final String EXPECTED_EXCEPTION = "expected exception";
-
- private static final String PDP2 = "pdpB";
- private static final String PDP4 = "pdpD";
-
- private PdpGroupCreateOrUpdateProvider prov;
-
-
- - @AfterClass
- public static void tearDownAfterClass() {
- Registry.newRegistry();
- }
-
- /**
- * Configures mocks and objects.
- *
- * @throws Exception if an error occurs
- */
- @Before
- @Override
- public void setUp() throws Exception {
super.setUp();
- prov = new PdpGroupCreateOrUpdateProvider();
- super.initialize(prov);
- when(toscaService.getPolicyTypeList("typeA", "100.2.3"))
- .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json")));
}
-
- @Test
- public void testCreateOrUpdateGroups() throws Exception {
- prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json"));
-
- // no groups, so no action should have been taken
- assertNoGroupAction();
- }
-
- @Test
- public void testCreateOrUpdateGroups_InvalidRequest() throws Exception {
- assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class)
- .hasMessageContaining("is null");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testCreateOrUpdate_Invalid() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("pdpGroupState");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testAddGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup group = groups.getGroups().get(0);
- group.setPdpGroupState(PdpState.PASSIVE);
-
- prov.createOrUpdateGroups(groups);
-
- // should not have updated the state
- assertEquals(PdpState.PASSIVE, group.getPdpGroupState());
-
- assertSame(group, getGroupCreates().get(0));
- }
-
- @Test
- public void testAddGroup_Invalid() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("pdpGroupState");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testAddGroup_InvalidSubGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
-
- groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99");
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("unknown policy type");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testValidateGroupOnly_NullState() {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(null);
- Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
- }
-
- @Test
- public void testValidateGroupOnly_Active() {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE);
- Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
- }
-
- @Test
- public void testValidateGroupOnly_Passive() {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE);
- Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
- }
-
- @Test
- public void testValidateGroupOnly_Invalid() {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("pdpGroupState");
- }
-
- @Test
- public void testUpdateGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
-
- // DB group = new group
- PdpGroup group = new PdpGroup(groups.getGroups().get(0));
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- assertNoGroupAction();
- }
-
- @Test
- public void testUpdateGroup_PropertiesChanged() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
-
- PdpGroup group = new PdpGroup(groups.getGroups().get(0));
- group.setProperties(new TreeMap<>());
-
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("properties");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testUpdateGroup_NewDescription() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- group.setDescription("old description");
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- assertGroupUpdateOnly(group);
-
- assertEquals("my description", group.getDescription());
- assertEquals(newgrp.toString(), group.toString());
- }
-
- @Test
- public void testUpdateGroup_NewState() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- group.setPdpGroupState(PdpState.TEST);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- assertGroupUpdateOnly(group);
-
- assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
- assertEquals(newgrp.toString(), group.toString());
- }
-
- @Test
- public void testUpdateGroup_NewSubGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
- PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- PdpGroup newgrp = groups.getGroups().get(0);
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testUpdateGroup_UpdatedSubGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- // something different in this subgroup
- group.getPdpSubgroups().get(0).setDesiredInstanceCount(10);
-
- prov.createOrUpdateGroups(groups);
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception {
- PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0));
- when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup));
-
- PdpGroups groups = loadPdpGroups("createGroups.json");
-
- prov.createOrUpdateGroups(groups);
-
- // verify that DB group was updated
- List<PdpGroup> updates = getGroupUpdates();
- assertEquals(1, updates.size());
- dbgroup = updates.get(0);
-
- PdpGroup newgrp = groups.getGroups().get(0);
-
- Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
- Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies());
-
- assertEquals(newgrp.toString(), dbgroup.toString());
-
- // no deployment notifications
- checkEmptyNotification();
-
- // this requires a PDP UPDATE message
- List<PdpUpdate> pdpUpdates = getUpdateRequests(2);
- assertEquals(2, pdpUpdates.size());
-
- PdpUpdate pdpUpdate = pdpUpdates.get(0);
- assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource());
- assertEquals(PDP2, pdpUpdate.getName());
- assertNull(pdpUpdate.getPdpGroup());
-
- pdpUpdate = pdpUpdates.get(1);
- assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource());
- assertEquals(PDP4, pdpUpdate.getName());
- assertNull(pdpUpdate.getPdpGroup());
-
- // it also requires a PDP STATE-CHANGE message
- List<PdpStateChange> changes = getStateChangeRequests(2);
- assertEquals(2, changes.size());
-
- PdpStateChange change = changes.get(0);
- assertEquals(PapConstants.PAP_NAME, change.getSource());
- assertEquals(PDP2, change.getName());
- assertEquals(PdpState.PASSIVE, change.getState());
-
- change = changes.get(1);
- assertEquals(PapConstants.PAP_NAME, change.getSource());
- assertEquals(PDP4, change.getName());
- assertEquals(PdpState.PASSIVE, change.getState());
- }
-
- @Test
- public void testUpdateField_Unchanged() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- assertNoGroupAction();
- }
-
- @Test
- public void testUpdateField_WasNull() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- group.setDescription(null);
-
- prov.createOrUpdateGroups(groups);
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testUpdateField_NowNull() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- newgrp.setDescription(null);
-
- prov.createOrUpdateGroups(groups);
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testUpdateField_Changed() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- newgrp.setDescription(group.getDescription() + "-changed");
-
- prov.createOrUpdateGroups(groups);
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testAddSubGroup() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
- PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- PdpGroup newgrp = groups.getGroups().get(0);
-
- PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1);
- newsub.setCurrentInstanceCount(0);
- newsub.setPdpInstances(new ArrayList<>(0));
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- /**
- * Tests addSubgroup() when the new subgroup has a wild-card policy type.
- *
- * @throws Exception if an error occurs
- */
- @Test
- public void testAddSubGroupWildCardPolicyType() throws Exception {
- when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json"));
- when(toscaService.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList());
-
- PdpGroups groups = loadPdpGroups("createGroupsWildCard.json");
- PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- PdpGroup newgrp = groups.getGroups().get(0);
-
- PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1);
- newsub.setCurrentInstanceCount(0);
- newsub.setPdpInstances(new ArrayList<>(0));
-
- assertEquals(newgrp.toString(), group.toString());
- }
-
- @Test
- public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
- PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList());
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type");
- }
-
- @Test
- public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
- PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION);
- when(toscaService.getPolicyTypeList(any(), any())).thenThrow(exc);
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc);
- }
-
- @Test
- public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup dbgroup = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup));
-
- when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
- .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json"));
-
- PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json");
-
- prov.createOrUpdateGroups(reqgroups);
-
- Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
- Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies());
-
- assertEquals(newgrp.toString(), dbgroup.toString());
- }
-
- @Test
- public void testUpdateSubGroup_Invalid() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- // change properties
- newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>());
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("properties");
-
- assertNoGroupAction();
- }
-
- @Test
- public void testUpdateSubGroup_SupportedPolicies() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes()
- .add(new ToscaConceptIdentifier("typeX.*", "9.8.7"));
-
- // the group is updated with a new supported policy type in subgroup
- assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size());
- prov.createOrUpdateGroups(groups);
- // PdpGroup update doesn't allow supported policy type modifications
- // during pdp group update, the ones in db is maintained
- assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size());
- assertEquals(newgrp.toString(), group.toString());
- }
-
- @Test
- public void testUpdateSubGroup_DesiredCount() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20);
-
- prov.createOrUpdateGroups(groups);
-
- assertEquals(newgrp.toString(), group.toString());
- assertGroupUpdateOnly(group);
- }
-
- @Test
- public void testUpdateSubGroup_Unchanged() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- prov.createOrUpdateGroups(groups);
-
- Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
- Collections.sort(group.getPdpSubgroups().get(0).getPolicies());
-
- assertEquals(newgrp.toString(), group.toString());
-
- // no notifications
- checkEmptyNotification();
-
- // no group updates
- assertNoGroupAction();
- }
-
- @Test
- public void testValidateSubGroup_PropertiesMismatch() throws Exception {
- PdpGroups groups = loadPdpGroups("createGroups.json");
- PdpGroup newgrp = groups.getGroups().get(0);
- PdpGroup group = new PdpGroup(newgrp);
- when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
-
- newgrp.setProperties(new TreeMap<>());
-
- assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("properties");
-
- assertNoGroupAction();
- }
-
- private void assertNoGroupAction() throws Exception {
- verify(pdpGroupService, never()).createPdpGroups(any());
- verify(pdpGroupService, never()).updatePdpGroups(any());
- verify(reqmap, never()).addRequest(any(), any());
- }
-
- private void assertGroupUpdateOnly(PdpGroup group) throws Exception {
- verify(pdpGroupService, never()).createPdpGroups(any());
- verify(reqmap, never()).addRequest(any(), any());
-
- List<PdpGroup> updates = getGroupUpdates();
- assertEquals(Arrays.asList(group), updates);
- }
-}
+/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019-2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.core.Response.Status; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.TreeMap; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroups; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.pap.main.PapConstants; + +public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { + private static final String EXPECTED_EXCEPTION = "expected exception"; + + private static final String PDP2 = "pdpB"; + private static final String PDP4 = "pdpD"; + + private PdpGroupCreateOrUpdateProvider prov; + + + @AfterAll + public static void tearDownAfterClass() { + Registry.newRegistry(); + } + + /** + * Configures mocks and objects. + * + * @throws Exception if an error occurs + */ + @BeforeEach + @Override + public void setUp() throws Exception { + super.setUp(); + prov = new PdpGroupCreateOrUpdateProvider(); + super.initialize(prov); + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); + } + + @Test + public void testCreateOrUpdateGroups() throws Exception { + prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); + + // no groups, so no action should have been taken + assertNoGroupAction(); + } + + @Test + public void testCreateOrUpdateGroups_InvalidRequest() throws Exception { + assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) + .hasMessageContaining("is null"); + + assertNoGroupAction(); + } + + @Test + public void testCreateOrUpdate_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + + assertNoGroupAction(); + } + + @Test + public void testAddGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup group = groups.getGroups().get(0); + group.setPdpGroupState(PdpState.PASSIVE); + + prov.createOrUpdateGroups(groups); + + // should not have updated the state + assertEquals(PdpState.PASSIVE, group.getPdpGroupState()); + + assertSame(group, getGroupCreates().get(0)); + } + + @Test + public void testAddGroup_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + + assertNoGroupAction(); + } + + @Test + public void testAddGroup_InvalidSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("unknown policy type"); + + assertNoGroupAction(); + } + + @Test + public void testValidateGroupOnly_NullState() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(null); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Active() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Passive() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Invalid() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + } + + @Test + public void testUpdateGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + // DB group = new group + PdpGroup group = new PdpGroup(groups.getGroups().get(0)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertNoGroupAction(); + } + + @Test + public void testUpdateGroup_PropertiesChanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + PdpGroup group = new PdpGroup(groups.getGroups().get(0)); + group.setProperties(new TreeMap<>()); + + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + @Test + public void testUpdateGroup_NewDescription() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + group.setDescription("old description"); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertGroupUpdateOnly(group); + + assertEquals("my description", group.getDescription()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateGroup_NewState() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + group.setPdpGroupState(PdpState.TEST); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertGroupUpdateOnly(group); + + assertEquals(PdpState.ACTIVE, group.getPdpGroupState()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateGroup_NewSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateGroup_UpdatedSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + // something different in this subgroup + group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception { + PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + + PdpGroups groups = loadPdpGroups("createGroups.json"); + + prov.createOrUpdateGroups(groups); + + // verify that DB group was updated + List<PdpGroup> updates = getGroupUpdates(); + assertEquals(1, updates.size()); + dbgroup = updates.get(0); + + PdpGroup newgrp = groups.getGroups().get(0); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), dbgroup.toString()); + + // no deployment notifications + checkEmptyNotification(); + + // this requires a PDP UPDATE message + List<PdpUpdate> pdpUpdates = getUpdateRequests(2); + assertEquals(2, pdpUpdates.size()); + + PdpUpdate pdpUpdate = pdpUpdates.get(0); + assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); + assertEquals(PDP2, pdpUpdate.getName()); + assertNull(pdpUpdate.getPdpGroup()); + + pdpUpdate = pdpUpdates.get(1); + assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); + assertEquals(PDP4, pdpUpdate.getName()); + assertNull(pdpUpdate.getPdpGroup()); + + // it also requires a PDP STATE-CHANGE message + List<PdpStateChange> changes = getStateChangeRequests(2); + assertEquals(2, changes.size()); + + PdpStateChange change = changes.get(0); + assertEquals(PapConstants.PAP_NAME, change.getSource()); + assertEquals(PDP2, change.getName()); + assertEquals(PdpState.PASSIVE, change.getState()); + + change = changes.get(1); + assertEquals(PapConstants.PAP_NAME, change.getSource()); + assertEquals(PDP4, change.getName()); + assertEquals(PdpState.PASSIVE, change.getState()); + } + + @Test + public void testUpdateField_Unchanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertNoGroupAction(); + } + + @Test + public void testUpdateField_WasNull() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + group.setDescription(null); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateField_NowNull() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setDescription(null); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateField_Changed() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setDescription(group.getDescription() + "-changed"); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testAddSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + + PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); + newsub.setCurrentInstanceCount(0); + newsub.setPdpInstances(new ArrayList<>(0)); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + /** + * Tests addSubgroup() when the new subgroup has a wild-card policy type. + * + * @throws Exception if an error occurs + */ + @Test + public void testAddSubGroupWildCardPolicyType() throws Exception { + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); + when(toscaService.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList()); + + PdpGroups groups = loadPdpGroups("createGroupsWildCard.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + + PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); + newsub.setCurrentInstanceCount(0); + newsub.setPdpInstances(new ArrayList<>(0)); + + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type"); + } + + @Test + public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); + when(toscaService.getPolicyTypeList(any(), any())).thenThrow(exc); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc); + } + + @Test + public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup dbgroup = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json")); + + PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json"); + + prov.createOrUpdateGroups(reqgroups); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), dbgroup.toString()); + } + + @Test + public void testUpdateSubGroup_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + // change properties + newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + @Test + public void testUpdateSubGroup_SupportedPolicies() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes() + .add(new ToscaConceptIdentifier("typeX.*", "9.8.7")); + + // the group is updated with a new supported policy type in subgroup + assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); + prov.createOrUpdateGroups(groups); + // PdpGroup update doesn't allow supported policy type modifications + // during pdp group update, the ones in db is maintained + assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateSubGroup_DesiredCount() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateSubGroup_Unchanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), group.toString()); + + // no notifications + checkEmptyNotification(); + + // no group updates + assertNoGroupAction(); + } + + @Test + public void testValidateSubGroup_PropertiesMismatch() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setProperties(new TreeMap<>()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + private void assertNoGroupAction() throws Exception { + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); + verify(reqmap, never()).addRequest(any(), any()); + } + + private void assertGroupUpdateOnly(PdpGroup group) throws Exception { + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(reqmap, never()).addRequest(any(), any()); + + List<PdpGroup> updates = getGroupUpdates(); + assertEquals(Arrays.asList(group), updates); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java index 21640bf9..07efd55b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,10 +23,10 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.SyncInvoker; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.SyncInvoker; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.springframework.test.context.ActiveProfiles; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index 0b6c57e7..be69c4cd 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020-2022 Nordix Foundation. + * Modifications Copyright (C) 2020-2023 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -35,12 +35,12 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import jakarta.ws.rs.core.Response.Status; import java.util.List; import java.util.Set; -import javax.ws.rs.core.Response.Status; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -71,7 +71,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { private ToscaConceptIdentifier ident; private Updater updater; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -81,7 +81,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { * * @throws Exception if an error occurs */ - @Before + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -104,15 +104,15 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(session.getGroup(GROUP1_NAME)).thenReturn(group); assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class) - .hasMessage("group is still ACTIVE"); + .hasMessage("group is still ACTIVE"); } @Test public void testDeleteGroup_NotFound() { assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class) - .hasMessage("group not found") - .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode()) - .isEqualTo(Status.NOT_FOUND); + .hasMessage("group not found") + .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode()) + .isEqualTo(Status.NOT_FOUND); } @Test @@ -183,7 +183,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(session.isUnchanged()).thenReturn(true); assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class) - .hasMessage("policy does not appear in any PDP group: policyA null"); + .hasMessage("policy does not appear in any PDP group: policyA null"); } @Test @@ -205,7 +205,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { // process method catches RuntimeException and re-throws as PfModelException assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class) - .hasRootCauseMessage(EXPECTED_EXCEPTION); + .hasRootCauseMessage(EXPECTED_EXCEPTION); } @Test @@ -279,7 +279,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { @Override protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy) - throws PfModelException { + throws PfModelException { // do nothing } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java index 61d204c9..7ff8ad0a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019-2022 Nordix Foundation. + * Copyright (C) 2019-2023 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,13 +24,13 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.util.Arrays; import java.util.List; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.DeploymentGroup; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index b828509b..e9f23c23 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -31,15 +31,15 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import jakarta.ws.rs.core.Response.Status; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import javax.ws.rs.core.Response.Status; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -72,7 +72,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { private PdpGroupDeployProvider prov; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -83,7 +83,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -92,7 +92,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); when(toscaService.getPolicyTypeList("typeA", "100.2.3")) - .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); + .thenReturn(List.of(loadPolicyType("daoPolicyType.json"))); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckControllerV1.java index f935f923..e0854538 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 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,13 +20,13 @@ package org.onap.policy.pap.main.rest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.SyncInvoker; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.SyncInvoker; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.Pdps; import org.springframework.test.context.ActiveProfiles; @@ -36,17 +36,17 @@ import org.springframework.test.context.ActiveProfiles; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @ActiveProfiles({ "test", "default" }) -public class TestPdpGroupHealthCheckControllerV1 extends CommonPapRestServer { +class TestPdpGroupHealthCheckControllerV1 extends CommonPapRestServer { private static final String ENDPOINT = "pdps/healthcheck"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(ENDPOINT); } @Test - public void testPdpGroupHealthCheck() throws Exception { + void testPdpGroupHealthCheck() throws Exception { final String uri = ENDPOINT; final Invocation.Builder invocationBuilder = sendRequest(uri); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index 0040beae..51429bae 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2023 Nordix Foundation. * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -23,15 +23,18 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.File; import java.util.List; import org.apache.commons.lang3.tuple.Pair; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; @@ -52,27 +55,34 @@ import org.springframework.http.HttpStatus; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @RunWith(MockitoJUnitRunner.class) -public class TestPdpGroupHealthCheckProvider { +class TestPdpGroupHealthCheckProvider { @Mock private PdpGroupService pdpGroupService; private List<PdpGroup> groups; - private Coder coder = new StandardCoder(); + private final Coder coder = new StandardCoder(); + + AutoCloseable autoCloseable; /** * Configures DAO and mocks. */ - @Before + @BeforeEach public void setUp() throws Exception { - + autoCloseable = MockitoAnnotations.openMocks(this); Registry.newRegistry(); - groups = loadFile("pdpGroup.json").getGroups(); + groups = loadFile().getGroups(); when(pdpGroupService.getPdpGroups()).thenReturn(groups); } + @AfterEach + public void tearDown() throws Exception { + autoCloseable.close(); + } + @Test - public void testFetchPdpGroupHealthStatus() throws Exception { + void testFetchPdpGroupHealthStatus() throws Exception { final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(pdpGroupService); final Pair<HttpStatus, Pdps> pair = provider.fetchPdpGroupHealthStatus(); assertEquals(HttpStatus.OK, pair.getLeft()); @@ -81,15 +91,21 @@ public class TestPdpGroupHealthCheckProvider { private void verifyPdps(final List<Pdp> pdpList, final List<PdpGroup> groups) { assertEquals(6, pdpList.size()); - for (final PdpGroup group : groups) { - for (final PdpSubGroup subGroup : group.getPdpSubgroups()) { - pdpList.containsAll(subGroup.getPdpInstances()); + boolean containsAll = false; + + do { + for (final PdpGroup group : groups) { + for (final PdpSubGroup subGroup : group.getPdpSubgroups()) { + containsAll = pdpList.containsAll(subGroup.getPdpInstances()); + } } - } + } while (!containsAll); + + assertTrue(containsAll); } - private PdpGroups loadFile(final String fileName) { - final File propFile = new File(ResourceUtils.getFilePath4Resource("rest/" + fileName)); + private PdpGroups loadFile() { + final File propFile = new File(ResourceUtils.getFilePath4Resource("rest/" + "pdpGroup.json")); try { return coder.decode(propFile, PdpGroups.class); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupQueryControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupQueryControllerV1.java index 30cd5944..11f3c5d6 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupQueryControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupQueryControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 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,10 +23,10 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.SyncInvoker; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.SyncInvoker; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.springframework.test.context.ActiveProfiles; @@ -35,7 +35,7 @@ import org.springframework.test.context.ActiveProfiles; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@ActiveProfiles({ "test", "default" }) +@ActiveProfiles({"test", "default"}) public class TestPdpGroupQueryControllerV1 extends CommonPapRestServer { private static final String GROUP_ENDPOINT = "pdps"; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java index a92731ab..db0da86d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 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,10 +23,10 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpGroupStateChangeResponse; import org.springframework.test.context.ActiveProfiles; @@ -35,7 +35,7 @@ import org.springframework.test.context.ActiveProfiles; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@ActiveProfiles({ "test", "default" }) +@ActiveProfiles({"test", "default"}) public class TestPdpGroupStateChangeControllerV1 extends CommonPapRestServer { private static final String GROUP_ENDPOINT = "pdps/groups"; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java index 3764e211..b8f9c988 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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 +21,15 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.springframework.test.context.ActiveProfiles; /** * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. */ -@ActiveProfiles({ "test", "default" }) +@ActiveProfiles({"test", "default"}) public class TestPolicyAuditControllerV1 extends CommonPapRestServer { private static final String POLICY_AUDIT_ENDPOINT = "policies/audit"; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java index 4f844fbc..c9a5beab 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. + * Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,13 +23,13 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; @@ -50,19 +50,19 @@ public class TestPolicyAuditManager extends ProviderSuper { * Setup the test variables. */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); auditManager = new PolicyAuditManager(policyAuditService); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @Test - public void testDeployments() { + void testDeployments() { auditManager.addDeploymentAudit(MY_POLICY, GROUP_A, PDP_TYPE, USER); auditManager.addUndeploymentAudit(MY_POLICY, GROUP_B, PDP_TYPE, USER); @@ -76,15 +76,16 @@ public class TestPolicyAuditManager extends ProviderSuper { } @Test - public void testSaveRecordsToDb_EmptyList() { - assertThat(auditManager.getAuditRecords()).isEmpty();; + void testSaveRecordsToDb_EmptyList() { + assertThat(auditManager.getAuditRecords()).isEmpty(); + ; auditManager.saveRecordsToDb(); assertThatCode(() -> auditManager.saveRecordsToDb()).doesNotThrowAnyException(); } @Test - public void testSaveRecordsToDb_Exception() { + void testSaveRecordsToDb_Exception() { auditManager.addDeploymentAudit(MY_POLICY, GROUP_A, PDP_TYPE, USER); assertThat(auditManager.getAuditRecords()).hasSize(1); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java index ff91ebe9..5637da28 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2020, 2022 Nordix Foundation. + * Copyright (C) 2019-2020, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Inc. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ @@ -22,16 +22,16 @@ package org.onap.policy.pap.main.rest; -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 jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.springframework.beans.factory.annotation.Autowired; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java index 3db1ed83..0999c51f 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2020, 2022 Nordix Foundation. + * Copyright (C) 2020, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Corp. * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -22,23 +22,24 @@ package org.onap.policy.pap.main.rest; -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 static org.mockito.Mockito.when; +import jakarta.ws.rs.core.Response; import java.io.File; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import java.util.Map; -import javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.Pair; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; @@ -62,7 +63,7 @@ import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) -public class TestPolicyComponentsHealthCheckProvider { +class TestPolicyComponentsHealthCheckProvider { private static final String CLIENT_1 = "client1"; private static final String PDP_GROUP_DATA_FILE = "rest/pdpGroup.json"; @@ -102,13 +103,16 @@ public class TestPolicyComponentsHealthCheckProvider { private PolicyComponentsHealthCheckProvider provider; + AutoCloseable autoCloseable; + /** * Configures mocks and objects. * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { + autoCloseable = MockitoAnnotations.openMocks(this); groups = loadPdpGroupsFromFile().getGroups(); when(pdpGroupService.getPdpGroups()).thenReturn(groups); @@ -155,26 +159,27 @@ public class TestPolicyComponentsHealthCheckProvider { /** * Tear down. */ - @After - public void tearDown() { + @AfterEach + public void tearDown() throws Exception { if (savedPapParameterGroup != null) { ParameterService.register(savedPapParameterGroup, true); } else { ParameterService.deregister(PAP_GROUP_PARAMS_NAME); } provider.cleanup(); + autoCloseable.close(); } @Test - public void testFetchPolicyComponentsHealthStatus_allHealthy() { + void testFetchPolicyComponentsHealthStatus_allHealthy() { Pair<HttpStatus, Map<String, Object>> ret = provider.fetchPolicyComponentsHealthStatus(); assertEquals(HttpStatus.OK, ret.getLeft()); assertTrue((Boolean) ret.getRight().get(HEALTHY)); } @Test - public void testFetchPolicyComponentsHealthStatus_unhealthyClient() { + void testFetchPolicyComponentsHealthStatus_unhealthyClient() { when(response1.getStatus()).thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); when(response1.readEntity(HealthCheckReport.class)) .thenReturn(createReport(HttpURLConnection.HTTP_INTERNAL_ERROR, false)); @@ -207,7 +212,7 @@ public class TestPolicyComponentsHealthCheckProvider { @SuppressWarnings("unchecked") @Test - public void testFetchPolicyComponentsHealthStatus_unhealthyPdps() { + void testFetchPolicyComponentsHealthStatus_unhealthyPdps() { // Get a PDP and set it unhealthy groups.get(0).getPdpSubgroups().get(0).getPdpInstances().get(0).setHealthy(PdpHealthStatus.NOT_HEALTHY); Map<String, Object> result = callFetchPolicyComponentsHealthStatus(); @@ -217,7 +222,7 @@ public class TestPolicyComponentsHealthCheckProvider { } @Test - public void testFetchPolicyComponentsHealthStatus_PdpDown() { + void testFetchPolicyComponentsHealthStatus_PdpDown() { // Set currentInstanceCount as 0 to simulate PDP down groups.get(0).getPdpSubgroups().get(0).setCurrentInstanceCount(0); Map<String, Object> result = callFetchPolicyComponentsHealthStatus(); @@ -225,7 +230,7 @@ public class TestPolicyComponentsHealthCheckProvider { } @Test - public void testFetchPolicyComponentsHealthStatus_unhealthyPap() { + void testFetchPolicyComponentsHealthStatus_unhealthyPap() { when(papActivator.isAlive()).thenReturn(false); Map<String, Object> result = callFetchPolicyComponentsHealthStatus(); assertFalse((Boolean) result.get(HEALTHY)); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusControllerV1.java index 41cfd39d..114539dd 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusControllerV1.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2021-2022 Nordix Foundation. + * Copyright (C) 2019, 2021-2023 Nordix Foundation. * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ @@ -23,12 +23,12 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.SyncInvoker; -import javax.ws.rs.core.Response; -import org.junit.Test; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.SyncInvoker; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; import org.springframework.test.context.ActiveProfiles; /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index 1f2c08ed..c3ed77de 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 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,21 +23,20 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; -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 static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; +import java.util.Comparator; import java.util.Iterator; import java.util.List; import lombok.NonNull; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.PdpPolicyStatusBuilder; @@ -59,7 +58,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { private PolicyStatusProvider prov; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -70,7 +69,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -79,12 +78,12 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetStatus_testAccumulate() throws PfModelException { + public void testGetStatus_testAccumulate() { buildPolicyStatusToReturn1(); List<PolicyStatus> result = new ArrayList<>(prov.getStatus()); - Collections.sort(result, (rec1, rec2) -> rec1.getPolicy().compareTo(rec2.getPolicy())); + result.sort(Comparator.comparing(PolicyStatus::getPolicy)); assertThat(result).hasSize(3); @@ -113,7 +112,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetStatusToscaConceptIdentifierOptVersion() throws PfModelException { + public void testGetStatusToscaConceptIdentifierOptVersion() { ToscaConceptIdentifierOptVersion optIdent = buildPolicyStatusToReturn2(); @@ -131,12 +130,12 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatus() throws PfModelException { + public void testGetPolicyStatus() { buildPolicyStatusToReturn1(); List<PdpPolicyStatus> result = new ArrayList<>(prov.getPolicyStatus()); - Collections.sort(result, (rec1, rec2) -> rec1.getPolicy().compareTo(rec2.getPolicy())); + result.sort(Comparator.comparing(PdpPolicyStatus::getPolicy)); assertThat(result).hasSize(5); Iterator<PdpPolicyStatus> iter = result.iterator(); @@ -170,7 +169,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusByGroupAndPolicyIdVersion() throws PfModelException { + public void testGetPolicyStatusByGroupAndPolicyIdVersion() { ToscaConceptIdentifierOptVersion optIdent = buildPolicyStatusToReturn2(); @@ -199,7 +198,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusByRegexNoMatch() throws PfModelException { + public void testGetPolicyStatusByRegexNoMatch() { buildPolicyStatusToReturn1(); final String pattern = "Hello"; @@ -208,7 +207,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusOneMatch() throws PfModelException { + public void testGetPolicyStatusOneMatch() { buildPolicyStatusToReturn1(); final String pattern = "My(We|Po)[li]{0,3}c.A"; @@ -220,7 +219,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusAllMatch() throws PfModelException { + public void testGetPolicyStatusAllMatch() { buildPolicyStatusToReturn1(); final String pattern = "My(We|Po)[li]{0,3}c.{2}0*"; @@ -229,7 +228,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { assertThat(actual).hasSize(3); } - private void buildPolicyStatusToReturn1() throws PfModelException { + private void buildPolicyStatusToReturn1() { PdpPolicyStatusBuilder builder = PdpPolicyStatus.builder().pdpGroup(MY_GROUP).pdpType(MY_PDP_TYPE) .policyType(POLICY_TYPE).state(State.WAITING); @@ -250,7 +249,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { // @formatter:on } - private ToscaConceptIdentifierOptVersion buildPolicyStatusToReturn2() throws PfModelException { + private ToscaConceptIdentifierOptVersion buildPolicyStatusToReturn2() { PdpPolicyStatusBuilder builder = PdpPolicyStatus.builder().pdpGroup(MY_GROUP).pdpType(MY_PDP_TYPE).policy(POLICY_A).policyType(POLICY_TYPE); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java index 9ae64452..f172222d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 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,7 +21,8 @@ package org.onap.policy.pap.main.rest; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -32,9 +33,9 @@ import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -66,7 +67,7 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { private MyProvider prov; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -77,7 +78,7 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -96,15 +97,15 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { Pdp pdp1 = new Pdp(); pdp1.setInstanceId(PDP1); - subgroup.setPdpInstances(Arrays.asList(pdp1)); + subgroup.setPdpInstances(List.of(pdp1)); // this subgroup should never be touched PdpSubGroup subgroup0 = new PdpSubGroup(); subgroup0.setPdpType(MY_SUBGROUP0); - subgroup0.setPolicies(Collections.unmodifiableList(Arrays.asList(ident1, ident2, ident3, ident4))); - subgroup.setPdpInstances(Arrays.asList(pdp1)); + subgroup0.setPolicies(List.of(ident1, ident2, ident3, ident4)); + subgroup.setPdpInstances(List.of(pdp1)); - group.setPdpSubgroups(Arrays.asList(subgroup0, subgroup)); + group.setPdpSubgroups(List.of(subgroup0, subgroup)); when(session.getGroup(MY_GROUP)).thenReturn(group); when(session.getPolicy(any())).thenReturn(policy1); @@ -114,15 +115,15 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { @Test public void testUndeployPolicies() throws PfModelException { - subgroup.setPolicies(new LinkedList<>(Arrays.asList(ident1, ident2, ident3, ident4))); + subgroup.setPolicies(new LinkedList<>(List.of(ident1, ident2, ident3, ident4))); - prov.undeploy(MY_GROUP, MY_SUBGROUP, Arrays.asList(ident1, ident2)); + prov.undeploy(MY_GROUP, MY_SUBGROUP, List.of(ident1, ident2)); // group should have been updated verify(session).update(group); // subgroup should only have remaining policies - assertEquals(Arrays.asList(ident3, ident4).toString(), subgroup.getPolicies().toString()); + assertEquals(List.of(ident3, ident4).toString(), subgroup.getPolicies().toString()); // should have generated PDP-UPDATE for the PDP verify(session).addUpdate(any()); @@ -133,10 +134,10 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { */ @Test public void testUndeployPoliciesUnchanged() throws PfModelException { - List<ToscaConceptIdentifier> origlist = Arrays.asList(ident3, ident4); + List<ToscaConceptIdentifier> origlist = List.of(ident3, ident4); subgroup.setPolicies(new LinkedList<>(origlist)); - prov.undeploy(MY_GROUP, MY_SUBGROUP, Arrays.asList(ident1, ident2)); + prov.undeploy(MY_GROUP, MY_SUBGROUP, List.of(ident1, ident2)); // group NOT should have been updated verify(session, never()).update(group); @@ -154,11 +155,11 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { @Test public void testUndeployPoliciesGroupNotFound() throws PfModelException { // force exception to be thrown if the list is changed - subgroup.setPolicies(Collections.unmodifiableList(Arrays.asList(ident1, ident2, ident3, ident4))); + subgroup.setPolicies(Collections.unmodifiableList(List.of(ident1, ident2, ident3, ident4))); when(session.getGroup(any())).thenReturn(null); - prov.undeploy(MY_GROUP, MY_SUBGROUP, Arrays.asList(ident1, ident2)); + prov.undeploy(MY_GROUP, MY_SUBGROUP, List.of(ident1, ident2)); // group should have been updated verify(session, never()).update(group); @@ -173,11 +174,11 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { @Test public void testUndeployPoliciesSubGroupNotFound() throws PfModelException { // force exception to be thrown if the list is changed - subgroup.setPolicies(Collections.unmodifiableList(Arrays.asList(ident1, ident2, ident3, ident4))); + subgroup.setPolicies(Collections.unmodifiableList(List.of(ident1, ident2, ident3, ident4))); subgroup.setPdpType(MY_SUBGROUP + "X"); - prov.undeploy(MY_GROUP, MY_SUBGROUP, Arrays.asList(ident1, ident2)); + prov.undeploy(MY_GROUP, MY_SUBGROUP, List.of(ident1, ident2)); // group should have been updated verify(session, never()).update(group); @@ -186,9 +187,9 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { verify(session, never()).addUpdate(any()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testMakeUpdater() { - prov.makeUpdater(null, null, null); + assertThrows(UnsupportedOperationException.class, () -> prov.makeUpdater(null, null, null)); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index d969c565..058357f2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021,2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,23 +23,22 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.util.Arrays; +import jakarta.ws.rs.core.Response.Status; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; -import javax.ws.rs.core.Response.Status; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -71,7 +70,7 @@ public class TestProviderBase extends ProviderSuper { private MyProvider prov; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -82,7 +81,7 @@ public class TestProviderBase extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); prov = new MyProvider(); @@ -319,8 +318,8 @@ public class TestProviderBase extends ProviderSuper { private static class MyProvider extends ProviderBase { /** - * Used to determine whether or not to make an update when - * {@link #makeUpdater(ToscaPolicy)} is called. The updater function removes an + * Used to determine whether to make an update when + * makeUpdater() is called. The updater function removes an * item from this queue each time it is invoked. */ private final Queue<Boolean> shouldUpdate = new LinkedList<>(); @@ -339,7 +338,7 @@ public class TestProviderBase extends ProviderSuper { } public void add(Boolean... update) { - shouldUpdate.addAll(Arrays.asList(update)); + shouldUpdate.addAll(List.of(update)); } @Override diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java index ec79c03a..47e9d42a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,11 +26,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; @@ -39,17 +39,16 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import jakarta.ws.rs.core.Response.Status; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; -import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyNotification; @@ -90,7 +89,7 @@ public class TestSessionData extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -106,7 +105,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicyType() throws Exception { ToscaPolicyType policy1 = makePolicyType(POLICY_TYPE, POLICY_TYPE_VERSION); - when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1)); + when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(List.of(policy1)); assertSame(policy1, session.getPolicyType(type)); @@ -132,7 +131,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_NullVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion(null); assertSame(policy1, session.getPolicy(ident)); @@ -140,7 +139,7 @@ public class TestSessionData extends ProviderSuper { ToscaTypedEntityFilter<ToscaPolicy> filter = getPolicyFilter(); assertEquals(POLICY_NAME, filter.getName()); assertEquals(ToscaTypedEntityFilter.LATEST_VERSION, filter.getVersion()); - assertEquals(null, filter.getVersionPrefix()); + assertNull(filter.getVersionPrefix()); // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); @@ -150,7 +149,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_MajorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion("1"); assertSame(policy1, session.getPolicy(ident)); @@ -168,7 +167,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_MajorMinorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion(POLICY_VERSION); assertSame(policy1, session.getPolicy(ident)); @@ -176,7 +175,7 @@ public class TestSessionData extends ProviderSuper { ToscaTypedEntityFilter<ToscaPolicy> filter = getPolicyFilter(); assertEquals(POLICY_NAME, filter.getName()); assertEquals(POLICY_VERSION, filter.getVersion()); - assertEquals(null, filter.getVersionPrefix()); + assertNull(filter.getVersionPrefix()); // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); @@ -262,10 +261,10 @@ public class TestSessionData extends ProviderSuper { assertSame(change3, pair.getRight()); // verify individual lists - List<PdpUpdate> updates = Arrays.asList(update, update2); + List<PdpUpdate> updates = List.of(update, update2); assertEquals(sort(updates, this::compare), sort(session.getPdpUpdates(), this::compare)); - List<PdpStateChange> changes = Arrays.asList(change, change3); + List<PdpStateChange> changes = List.of(change, change3); assertEquals(sort(changes, this::compare), sort(session.getPdpStateChanges(), this::compare)); } @@ -290,14 +289,14 @@ public class TestSessionData extends ProviderSuper { session.addUpdate(update3); List<PdpUpdate> lst = sort(getUpdateRequests(), this::compare); - assertEquals(Arrays.asList(update1, update2, update3).toString(), lst.toString()); + assertEquals(List.of(update1, update2, update3).toString(), lst.toString()); // overwrite one update2 = makeUpdate(PDP2); session.addUpdate(update2); lst = sort(getUpdateRequests(), this::compare); - assertEquals(Arrays.asList(update1, update2, update3).toString(), lst.toString()); + assertEquals(List.of(update1, update2, update3).toString(), lst.toString()); } @Test @@ -313,14 +312,14 @@ public class TestSessionData extends ProviderSuper { session.addStateChange(change3); List<PdpStateChange> lst = sort(getStateChangeRequests(), this::compare); - assertEquals(Arrays.asList(change1, change2, change3).toString(), lst.toString()); + assertEquals(List.of(change1, change2, change3).toString(), lst.toString()); // overwrite one change2 = makeStateChange(PDP2); session.addStateChange(change2); lst = sort(getStateChangeRequests(), this::compare); - assertEquals(Arrays.asList(change1, change2, change3).toString(), lst.toString()); + assertEquals(List.of(change1, change2, change3).toString(), lst.toString()); } private ToscaPolicyType makePolicyType(String name, String version) { @@ -365,13 +364,13 @@ public class TestSessionData extends ProviderSuper { assertTrue(session.isUnchanged()); // force the groups into the cache - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); session.getActivePdpGroupsByPolicyType(type); /* * try group 1 */ - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); PdpGroup newgrp = new PdpGroup(group1); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -384,7 +383,7 @@ public class TestSessionData extends ProviderSuper { /* * try group 2 */ - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group2)); newgrp = new PdpGroup(group2); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -397,7 +396,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdate_NotInCache() throws Exception { - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); assertThatIllegalStateException().isThrownBy(() -> session.update(new PdpGroup(group1))) .withMessage("group not cached: groupA"); @@ -405,7 +404,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetGroup() throws Exception { - when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(List.of(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); verify(pdpGroupService).getPdpGroups(any(String.class)); @@ -431,14 +430,14 @@ public class TestSessionData extends ProviderSuper { verify(pdpGroupService, times(2)).getPdpGroups(GROUP_NAME); // find it this time - when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(List.of(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); verify(pdpGroupService, times(3)).getPdpGroups(GROUP_NAME); } @Test public void testGetActivePdpGroupsByPolicyType() throws Exception { - List<PdpGroup> groups = Arrays.asList(group1, group2); + List<PdpGroup> groups = List.of(group1, group2); when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // repeat @@ -452,7 +451,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testAddGroup() throws Exception { - List<PdpGroup> groups = Arrays.asList(group1, group2); + List<PdpGroup> groups = List.of(group1, group2); when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // query by each type @@ -472,7 +471,7 @@ public class TestSessionData extends ProviderSuper { public void testUpdateDb() throws Exception { // force the groups into the cache PdpGroup group3 = loadGroup("group3.json"); - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2, group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2, group3)); session.getActivePdpGroupsByPolicyType(type); // create groups 4 & 5 @@ -483,7 +482,7 @@ public class TestSessionData extends ProviderSuper { session.create(group5); // update group 1 - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); PdpGroup newgrp1 = new PdpGroup(group1); session.update(newgrp1); @@ -492,12 +491,12 @@ public class TestSessionData extends ProviderSuper { session.update(newgrp1); // update group 3 - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group3)); PdpGroup newgrp3 = new PdpGroup(group3); session.update(newgrp3); // update group 5 - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group5)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group5)); PdpGroup newgrp5 = new PdpGroup(group5); session.update(newgrp5); @@ -522,7 +521,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdateDb_Empty() throws Exception { // force data into the cache - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); session.getActivePdpGroupsByPolicyType(type); PolicyNotification notif = new PolicyNotification(); @@ -566,10 +565,10 @@ public class TestSessionData extends ProviderSuper { policy.setType(POLICY_TYPE); policy.setTypeVersion(POLICY_TYPE_VERSION); - when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy)); ToscaConceptIdentifier policyId = new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION); - List<String> pdps = Arrays.asList(PDP1, PDP2); + List<String> pdps = List.of(PDP1, PDP2); ToscaPolicy testPolicy = session.getPolicy(new ToscaConceptIdentifierOptVersion(policyId)); @@ -626,7 +625,7 @@ public class TestSessionData extends ProviderSuper { private <T> List<T> sort(Collection<T> collection, Comparator<T> comparator) { List<T> lst = new ArrayList<>(collection); - Collections.sort(lst, comparator); + lst.sort(comparator); return lst; } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index 2b339f82..1aa40a28 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020, 2022 Nordix Foundation. + * Modifications Copyright (C) 2019-2020, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,7 +30,7 @@ import java.io.IOException; import java.util.List; import java.util.Optional; import lombok.Getter; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; @@ -56,7 +56,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.yaml.snakeyaml.Yaml; -@ActiveProfiles({ "test-e2e", "default" }) +@ActiveProfiles({"test-e2e", "default"}) public abstract class End2EndBase extends CommonPapRestServer { private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class); @@ -99,7 +99,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * Tears down. */ @Override - @After + @AfterEach public void tearDown() { if (context != null) { try { @@ -194,7 +194,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * Loads an object from a YAML file. * * @param fileName name of the file from which to load - * @param clazz the class of the object to be loaded + * @param clazz the class of the object to be loaded * @return the object that was loaded from the file */ protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) { @@ -223,7 +223,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * Loads an object from a JSON file. * * @param fileName name of the file from which to load - * @param clazz the class of the object to be loaded + * @param clazz the class of the object to be loaded * @return the object that was loaded from the file */ protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndContext.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndContext.java index c910a7b4..c0c98adc 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndContext.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndContext.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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,9 +21,9 @@ package org.onap.policy.pap.main.rest.e2e; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.LinkedList; diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/HealthCheckTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/HealthCheckTest.java index 296a6609..99ac30b0 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/HealthCheckTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/HealthCheckTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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.pap.main.rest.e2e; -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 jakarta.ws.rs.client.Invocation; import java.net.HttpURLConnection; -import javax.ws.rs.client.Invocation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.report.HealthCheckReport; public class HealthCheckTest extends End2EndBase { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java index 650dd41a..cf37d55a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP PAP * ================================================================================ - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,18 +21,18 @@ package org.onap.policy.pap.main.rest.e2e; -import static org.junit.Assert.assertEquals; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.util.Optional; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpGroupUpdateResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; @@ -52,7 +52,7 @@ public class PdpGroupCreateOrUpdateTest extends End2EndBase { * Sets up. */ @Override - @Before + @BeforeEach public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); super.setUp(); @@ -64,7 +64,7 @@ public class PdpGroupCreateOrUpdateTest extends End2EndBase { * Deletes the deployed group. */ @Override - @After + @AfterEach public void tearDown() { // delete the group that was inserted try { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java index 5e2ca38f..e3305ba5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2022 Nordix Foundation. + * Modifications Copyright (C) 2021-2023 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,18 +23,18 @@ package org.onap.policy.pap.main.rest.e2e; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +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 jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; import java.util.Collections; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; -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.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; import org.onap.policy.common.utils.coder.StandardCoder; @@ -54,7 +54,7 @@ public class PdpGroupDeleteTest extends End2EndBase { * Sets up. */ @Override - @Before + @BeforeEach public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); addToscaPolicies("monitoring.policy.yaml"); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java index f28ccd14..3eb4e2bb 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2022 Nordix Foundation. + * Modifications Copyright (C) 2021-2023 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,20 +23,20 @@ package org.onap.policy.pap.main.rest.e2e; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +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 jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -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.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; import org.onap.policy.common.utils.coder.StandardCoder; @@ -60,7 +60,7 @@ public class PdpGroupDeployTest extends End2EndBase { * Sets up. */ @Override - @Before + @BeforeEach public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); addToscaPolicies("monitoring.policy.yaml"); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java index d6472ce1..02c7063b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,19 +22,19 @@ package org.onap.policy.pap.main.rest.e2e; -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 jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; @@ -52,7 +52,7 @@ public class PdpGroupQueryTest extends End2EndBase { * @throws Exception the exception */ @Override - @Before + @BeforeEach public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java index 2fa7cfb4..463228fa 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,16 +22,16 @@ package org.onap.policy.pap.main.rest.e2e; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; import java.util.Collections; import java.util.List; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PdpGroupStateChangeResponse; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.enums.PdpState; @@ -50,7 +50,7 @@ public class PdpGroupStateChangeTest extends End2EndBase { * Sets up. */ @Override - @Before + @BeforeEach public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); addToscaPolicies("monitoring.policy.yaml"); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java index b0a135d2..6b5ddc5e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021-2022 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2023 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,15 +21,15 @@ package org.onap.policy.pap.main.rest.e2e; import static org.assertj.core.api.Assertions.assertThat; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.time.Instant; import java.util.ArrayList; import java.util.List; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; @@ -60,7 +61,7 @@ public class PolicyAuditTest extends End2EndBase { private PolicyAuditRepository policyAuditRepository; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); setupEnv(); @@ -70,7 +71,7 @@ public class PolicyAuditTest extends End2EndBase { * Teardown after tests. */ @Override - @After + @AfterEach public void tearDown() { policyAuditRepository.deleteAll(); super.tearDown(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java index 09c8a2ac..7fd0eee9 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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 +22,15 @@ package org.onap.policy.pap.main.rest.e2e; -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 jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.List; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State; @@ -43,7 +43,7 @@ public class PolicyStatusTest extends End2EndBase { private static final String POLICY_DEPLOYMENT_STATUS_ENDPOINT = "policies/status"; @Override - @Before + @BeforeEach public void setUp() throws Exception { addPdpPolicyStatus("policyStatus.json"); super.setUp(); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java index 4edb05dc..2846e506 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collections; import java.util.List; -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.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.pdp.concepts.Pdp; @@ -40,10 +40,12 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @ActiveProfiles("test") -public class PdpGroupServiceTest extends CommonPapRestServer { +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) +class PdpGroupServiceTest extends CommonPapRestServer { private static final String FIELD_IS_NULL = "%s is marked non-null but is null"; @@ -62,7 +64,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { private PdpGroups groupsToCreate; - private StandardCoder coder = new StandardCoder(); + private final StandardCoder coder = new StandardCoder(); /** * Setup before tests. @@ -70,7 +72,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { * @throws Exception the exception */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); PdpGroups defaultGroup = coder.decode(ResourceUtils.getResourceAsString("e2e/PdpGroups.json"), PdpGroups.class); @@ -79,7 +81,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { } @Test - public void testPdpGroupsCrudSuccess() { + void testPdpGroupsCrudSuccess() { List<PdpGroup> pdpGroups = pdpGroupService.getPdpGroups(); assertThat(pdpGroups).hasSize(1); @@ -118,7 +120,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { } @Test - public void testPdpGroupsCrudFailure() { + void testPdpGroupsCrudFailure() { PdpState pdpState = null; assertThatThrownBy(() -> pdpGroupService.getPdpGroups(pdpState)) .hasMessage(String.format(FIELD_IS_NULL, "pdpState")); @@ -140,23 +142,17 @@ public class PdpGroupServiceTest extends CommonPapRestServer { } @Test - public void testUpdatePdp() { + void testUpdatePdp() { + assertThatThrownBy(() -> pdpGroupService.updatePdp(null, null, new Pdp())) + .hasMessage(String.format(FIELD_IS_NULL, "pdpGroupName")); - assertThatThrownBy(() -> { - pdpGroupService.updatePdp(null, null, new Pdp()); - }).hasMessage(String.format(FIELD_IS_NULL, "pdpGroupName")); + assertThatThrownBy(() -> pdpGroupService.updatePdp(NAME, null, new Pdp())) + .hasMessage(String.format(FIELD_IS_NULL, "pdpSubGroup")); - assertThatThrownBy(() -> { - pdpGroupService.updatePdp(NAME, null, new Pdp()); - }).hasMessage(String.format(FIELD_IS_NULL, "pdpSubGroup")); + assertThatThrownBy(() -> pdpGroupService.updatePdp(NAME, TYPE, null)) + .hasMessage(String.format(FIELD_IS_NULL, "pdp")); - assertThatThrownBy(() -> { - pdpGroupService.updatePdp(NAME, TYPE, null); - }).hasMessage(String.format(FIELD_IS_NULL, "pdp")); - - assertThatThrownBy(() -> { - pdpGroupService.updatePdp(NAME, TYPE, new Pdp()); - }).hasMessage(LOCALNAME_IS_NULL); + assertThatThrownBy(() -> pdpGroupService.updatePdp(NAME, TYPE, new Pdp())).hasMessage(LOCALNAME_IS_NULL); pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); @@ -174,18 +170,15 @@ public class PdpGroupServiceTest extends CommonPapRestServer { } @Test - public void testUpdateSubGroup() { - assertThatThrownBy(() -> { - pdpGroupService.updatePdpSubGroup(null, null); - }).hasMessage(String.format(FIELD_IS_NULL, "pdpGroupName")); - - assertThatThrownBy(() -> { - pdpGroupService.updatePdpSubGroup(NAME, null); - }).hasMessage(String.format(FIELD_IS_NULL, "pdpSubGroup")); - - assertThatThrownBy(() -> { - pdpGroupService.updatePdpSubGroup(NAME, new PdpSubGroup()); - }).hasMessage(LOCALNAME_IS_NULL); + void testUpdateSubGroup() { + assertThatThrownBy(() -> pdpGroupService.updatePdpSubGroup(null, null)) + .hasMessage(String.format(FIELD_IS_NULL, "pdpGroupName")); + + assertThatThrownBy(() -> pdpGroupService.updatePdpSubGroup(NAME, null)) + .hasMessage(String.format(FIELD_IS_NULL, "pdpSubGroup")); + + assertThatThrownBy(() -> pdpGroupService.updatePdpSubGroup(NAME, new PdpSubGroup())) + .hasMessage(LOCALNAME_IS_NULL); pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java index 8c351e24..79037af3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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,13 +23,13 @@ package org.onap.policy.pap.main.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; @@ -59,7 +59,7 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { * Teardown after tests. */ @Override - @After + @AfterEach public void tearDown() { policyAuditRepository.deleteAll(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java index 6166580e..06eb887b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022-2023 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,8 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; @@ -55,7 +55,7 @@ public class PolicyStatusServiceTest extends CommonPapRestServer { * @throws Exception the exception */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); ToscaConceptIdentifier policyType = new ToscaConceptIdentifier("MyPolicyType", "1.2.4"); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/ToscaNodeTemplateServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/ToscaNodeTemplateServiceTest.java index d5c19fe3..7aefdc4c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/ToscaNodeTemplateServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/ToscaNodeTemplateServiceTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP PAP * ================================================================================ - * Copyright (C) 2022, Nordix Foundation. All rights reserved. + * Copyright (C) 2022-2023 Nordix Foundation. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.util.Optional; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -44,7 +46,7 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; import org.onap.policy.pap.main.repository.ToscaNodeTemplateRepository; @RunWith(MockitoJUnitRunner.class) -public class ToscaNodeTemplateServiceTest { +class ToscaNodeTemplateServiceTest { private static final String NODE_TEMPLATE_NAME = "tca_metadata"; private static final String NODE_TEMPLATE_VERSION = "1.0.0"; @@ -57,24 +59,31 @@ public class ToscaNodeTemplateServiceTest { private ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); - private StandardCoder coder = new StandardYamlCoder(); + private final StandardCoder coder = new StandardYamlCoder(); + + AutoCloseable autoCloseable; /** * Set up for tests. - * */ - @Before + @BeforeEach public void setup() throws CoderException { + autoCloseable = MockitoAnnotations.openMocks(this); coder.decode(ResourceUtils.getResourceAsString("e2e/policyMetadataSet.yaml"), - ToscaServiceTemplate.class).getToscaTopologyTemplate().getNodeTemplates() + ToscaServiceTemplate.class).getToscaTopologyTemplate().getNodeTemplates() .forEach((key, value) -> nodeTemplate = value); Mockito.when(nodeTemplateRepository.findById(new PfConceptKey(NODE_TEMPLATE_NAME, NODE_TEMPLATE_VERSION))) .thenReturn(Optional.of(new JpaToscaNodeTemplate(nodeTemplate))); } + @AfterEach + public void tearDown() throws Exception { + autoCloseable.close(); + } + @Test - public void testGetToscaNodeTemplate() { + void testGetToscaNodeTemplate() { assertDoesNotThrow(() -> nodeTemplateService.getToscaNodeTemplate(NODE_TEMPLATE_NAME, NODE_TEMPLATE_VERSION)); assertThat(nodeTemplateService.getToscaNodeTemplate(NODE_TEMPLATE_NAME, NODE_TEMPLATE_VERSION).getMetadata()) diff --git a/main/src/test/java/org/onap/policy/pap/main/service/ToscaServiceTemplateServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/ToscaServiceTemplateServiceTest.java index b64ad287..20bd2257 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/ToscaServiceTemplateServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/ToscaServiceTemplateServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022 Nordix Foundation. + * Modifications Copyright (C) 2022-2023 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,16 +24,18 @@ package org.onap.policy.pap.main.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import jakarta.ws.rs.core.Response; import java.util.List; import java.util.Map; import java.util.Optional; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -49,7 +51,7 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository; @RunWith(MockitoJUnitRunner.class) -public class ToscaServiceTemplateServiceTest { +class ToscaServiceTemplateServiceTest { private static final String VERSION_1 = "1.0.0"; @@ -72,22 +74,22 @@ public class ToscaServiceTemplateServiceTest { @Mock private ToscaNodeTemplateService nodeTemplateService; - private ToscaServiceTemplate serviceTemplate; - private ToscaNodeTemplate nodeTemplate; - private StandardCoder coder = new StandardYamlCoder(); + private final StandardCoder coder = new StandardYamlCoder(); + + AutoCloseable autoCloseable; /** * Set up for tests. * * @throws CoderException the exception */ - @Before + @BeforeEach public void setup() throws CoderException { - + autoCloseable = MockitoAnnotations.openMocks(this); coder.decode(ResourceUtils.getResourceAsString("e2e/policyMetadataSet.yaml"), - ToscaServiceTemplate.class).getToscaTopologyTemplate().getNodeTemplates() + ToscaServiceTemplate.class).getToscaTopologyTemplate().getNodeTemplates() .forEach((key, value) -> nodeTemplate = value); ToscaServiceTemplate toscaPolicyType = @@ -100,7 +102,7 @@ public class ToscaServiceTemplateServiceTest { toscaPolicy.getToscaTopologyTemplate().getPolicies().forEach(e -> e.entrySet().iterator().next().getValue() .getMetadata().putAll(Map.of("metadataSetName", NODE_TEMPLATE_NAME, "metadataSetVersion", NODE_TEMPLATE_VERSION))); - serviceTemplate = new ToscaServiceTemplate(toscaPolicyType); + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(toscaPolicyType); serviceTemplate.setToscaTopologyTemplate(toscaPolicy.getToscaTopologyTemplate()); Mockito .when(toscaRepository.findById( @@ -112,9 +114,13 @@ public class ToscaServiceTemplateServiceTest { .thenReturn(nodeTemplate); } + @AfterEach + public void tearDown() throws Exception { + autoCloseable.close(); + } @Test - public void testGetPolicyList() throws PfModelException { + void testGetPolicyList() throws PfModelException { assertThatThrownBy(() -> toscaService.getPolicyList(NAME, VERSION)) .isInstanceOf(PfModelRuntimeException.class).hasRootCauseMessage(INVALID_VERSION_ERR_MSG); @@ -124,7 +130,7 @@ public class ToscaServiceTemplateServiceTest { } @Test - public void testPolicyForMetadataSet() throws PfModelException { + void testPolicyForMetadataSet() throws PfModelException { List<ToscaPolicy> policies = toscaService.getPolicyList("onap.restart.tca", VERSION_1); assertThat(policies.get(0).getMetadata()).containsEntry("metadataSet", nodeTemplate.getMetadata()); @@ -140,7 +146,7 @@ public class ToscaServiceTemplateServiceTest { } @Test - public void testGetPolicyTypeList() throws PfModelException { + void testGetPolicyTypeList() throws PfModelException { assertThatThrownBy(() -> toscaService.getPolicyTypeList(NAME, VERSION)) .isInstanceOf(PfModelRuntimeException.class).hasRootCauseMessage(INVALID_VERSION_ERR_MSG); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 04ef2b66..a49f3c58 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022 Nordix Foundation. + * Copyright (C) 2019, 2022-2023 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ @@ -23,21 +23,21 @@ package org.onap.policy.pap.main.startstop; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -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 io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.utils.network.NetworkUtil; @@ -63,8 +63,9 @@ public class TestPapActivator { /** * Allocates a new DB name, server port, and creates a config file. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { + Registry.newRegistry(); CommonTestData.newDb(); } @@ -73,7 +74,7 @@ public class TestPapActivator { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { Registry.newRegistry(); TopicEndpointManager.getManager().shutdown(); @@ -102,20 +103,20 @@ public class TestPapActivator { * * @throws Exception if an error occurs */ - @After + @AfterEach public void teardown() throws Exception { if (activator != null && activator.isAlive()) { activator.stop(); } } - @AfterClass + @AfterAll public static void afterClass() { Registry.newRegistry(); } @Test - public void testPapActivator() { + void testPapActivator() { assertFalse(activator.isAlive()); activator.start(); assertTrue(activator.isAlive()); @@ -133,7 +134,7 @@ public class TestPapActivator { } @Test - public void testTerminate() { + void testTerminate() { activator.start(); activator.stop(); assertFalse(activator.isAlive()); diff --git a/main/src/test/resources/application-test-e2e.yaml b/main/src/test/resources/application-test-e2e.yaml index 435eb569..a4afd3ed 100644 --- a/main/src/test/resources/application-test-e2e.yaml +++ b/main/src/test/resources/application-test-e2e.yaml @@ -1,29 +1,16 @@ spring: - security: - user: - name: policyadmin - password: zb!XztG34 - http: - converters: - preferred-json-mapper: gson datasource: url: jdbc:h2:mem:testdb driverClassName: org.h2.Driver jpa: -# show-sql: true properties: hibernate: dialect: org.hibernate.dialect.H2Dialect -# format_sql: true hibernate: ddl-auto: create-drop naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl implicit-strategy: org.onap.policy.common.spring.utils.CustomImplicitNamingStrategy -server: - port: 6969 - servlet: - context-path: /policy/pap/v1 pap: name: "PapGroupE2E" @@ -82,11 +69,3 @@ pap: port: 3905 useHttps: true basePath: topics - -management: - endpoints: - web: - base-path: / - exposure: - include: health, metrics, prometheus - path-mapping.prometheus: metrics diff --git a/main/src/test/resources/application-test.yaml b/main/src/test/resources/application-test.yaml index 96ba60df..d5c125c2 100644 --- a/main/src/test/resources/application-test.yaml +++ b/main/src/test/resources/application-test.yaml @@ -1,97 +1,13 @@ spring: - security: - user: - name: policyadmin - password: zb!XztG34 - http: - converters: - preferred-json-mapper: gson datasource: url: jdbc:h2:mem:testdb driverClassName: org.h2.Driver jpa: -# show-sql: true properties: hibernate: dialect: org.hibernate.dialect.H2Dialect -# format_sql: true hibernate: ddl-auto: create-drop naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl implicit-strategy: org.onap.policy.common.spring.utils.CustomImplicitNamingStrategy - -server: - port: 6969 - servlet: - context-path: /policy/pap/v1 -pap: - name: "PapGroup" - aaf: false - topic: - pdp-pap.name: POLICY-PDP-PAP - notification.name: POLICY-NOTIFICATION - heartbeat.name: POLICY-HEARTBEAT - pdpParameters: - updateParameters: - maxRetryCount: 1 - maxWaitMs: 3000 - stateChangeParameters: - maxRetryCount: 1 - maxWaitMs: 3000 - heartBeatMs: 6000 - maxMessageAgeMs: 20000 - topicParameterGroup: - topicSources: - - topic: ${pap.topic.pdp-pap.name} - servers: - - message-router - topicCommInfrastructure: noop - - topic: ${pap.topic.heartbeat.name} - effectiveTopic: ${pap.topic.pdp-pap.name} - consumerGroup: policy-pap - servers: - - message-router - topicCommInfrastructure: noop - topicSinks: - - topic: ${pap.topic.pdp-pap.name} - servers: - - message-router - topicCommInfrastructure: noop - - topic: ${pap.topic.notification.name} - servers: - - message-router - topicCommInfrastructure: noop - healthCheckRestClientParameters: - - clientName: api - hostname: policy-api - port: 6969 - userName: policyadmin - password: zb!XztG34 - useHttps: true - basePath: policy/api/v1/healthcheck - - clientName: distribution - hostname: policy-distribution - port: 6969 - userName: healthcheck - password: zb!XztG34 - useHttps: true - basePath: healthcheck - - clientName: dmaap - hostname: message-router - port: 3905 - useHttps: true - basePath: topics - -management: - metrics: - export: - prometheus: - enabled: true - endpoints: - web: - base-path: / - exposure: - include: health, metrics, prometheus - path-mapping.metrics: plain-metrics - path-mapping.prometheus: metrics |