diff options
author | adheli.tavares <adheli.tavares@est.tech> | 2023-08-17 22:09:58 +0100 |
---|---|---|
committer | adheli.tavares <adheli.tavares@est.tech> | 2023-09-22 15:58:23 +0100 |
commit | 42c18ef1c6506e63151b55a96d90362da9fbda63 (patch) | |
tree | 895c7598c35b8daad7ac5e2681bc0feed5a47027 /main/src/test | |
parent | eb4cf2ad5d004cbfda90a752d10fbc6e91ef8fb4 (diff) |
Java 17 / Spring 6 / Spring Boot 3 Upgrade
Issue-ID: POLICY-4671
Change-Id: I664e5f62b1ad23619888af98589c04875b07f4d3
Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
Diffstat (limited to 'main/src/test')
71 files changed, 1762 insertions, 1828 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..e3bf63bc 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 @@ -181,17 +181,13 @@ public class MultiPdpStatusListenerTest { private boolean doWait(long millisec) throws InterruptedException { AtomicBoolean done = new AtomicBoolean(false); - Thread thread = new Thread() { - @Override - public void run() { - try { - done.set(listener.await(millisec, TimeUnit.MILLISECONDS)); - - } catch (InterruptedException expected) { - return; - } + Thread thread = new Thread(() -> { + try { + done.set(listener.await(millisec, TimeUnit.MILLISECONDS)); + } catch (InterruptedException expected) { + expected.printStackTrace(); } - }; + }); thread.start(); thread.join(5000); 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..0f221f04 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; @@ -54,7 +51,7 @@ import org.springframework.beans.factory.annotation.Autowired; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class PdpHeartbeatListenerTest extends End2EndBase { +class PdpHeartbeatListenerTest extends End2EndBase { private static final String POLICY_VERSION = "1.0.0"; private static final String POLICY_NAME = "onap.policies.controlloop.operational.common.apex.SampleDomain"; @@ -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 { + 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..7290be7a 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,23 +39,24 @@ 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.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +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.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.Pdp; @@ -75,8 +76,7 @@ import org.onap.policy.pap.main.service.PdpGroupService; 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 +119,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 +149,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 +175,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStopPublishing() { + void testStopPublishing() { // try with non-existent PDP map.stopPublishing(PDP1); @@ -182,13 +190,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 +205,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 +218,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 +243,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 +264,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testAddRequestPdpUpdatePdpStateChange() { + void testAddRequestPdpUpdatePdpStateChange() { // null should be ok map.addRequest(null, null); @@ -269,11 +277,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 +294,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 +311,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 +341,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStartNextRequest_NoMore() { + void testStartNextRequest_NoMore() { map.addRequest(change); // indicate success @@ -350,7 +358,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { } @Test - public void testStartNextRequest_HaveMore() { + void testStartNextRequest_HaveMore() { map.addRequest(update); map.addRequest(change); @@ -375,7 +383,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 +418,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 +432,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 +481,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 +497,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 +515,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 +535,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 +546,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 +561,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 +579,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 +590,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 +604,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 +618,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 +626,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 +642,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 +659,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 +676,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 +688,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 +745,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 +762,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 +777,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 +789,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..865ad7a8 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,21 +22,21 @@ 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; -public class PdpRequestsTest extends CommonRequestBase { +class PdpRequestsTest extends CommonRequestBase { private PdpRequests data; private UpdateReq update; @@ -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); @@ -53,13 +54,13 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testPdpRequests_testGetLastGroupName() { + void testPdpRequests_testGetLastGroupName() { assertEquals(PDP1, data.getPdpName()); assertSame(notifier, data.getNotifier()); } @Test - public void testAddSingleton() { + void testAddSingleton() { data.addSingleton(update); verify(update).setNotifier(notifier); @@ -67,7 +68,7 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testAddSingleton_SameAsExisting() { + void testAddSingleton_SameAsExisting() { data.addSingleton(update); // add duplicate update @@ -82,7 +83,7 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testAddSingleton_AnotherRequest() { + void testAddSingleton_AnotherRequest() { data.addSingleton(update); // add another request @@ -106,14 +107,14 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testAddSingleton_Broadcast() { + 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 - public void testStopPublishing() { + void testStopPublishing() { // nothing in the queue - nothing should happen data.stopPublishing(); @@ -133,7 +134,7 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testStartNextRequest_NothingToStart() { + void testStartNextRequest_NothingToStart() { assertFalse(data.startNextRequest(update)); // should not have published it @@ -144,7 +145,7 @@ public class PdpRequestsTest extends CommonRequestBase { * Tests addSingleton() when only one request is in the queue. */ @Test - public void testStartNextRequest_OneRequest() { + void testStartNextRequest_OneRequest() { data.addSingleton(update); assertFalse(data.startNextRequest(update)); @@ -159,7 +160,7 @@ public class PdpRequestsTest extends CommonRequestBase { * Tests addSingleton() when more than one request is in the queue. */ @Test - public void testStartNextRequest_MultipleRequests() { + void testStartNextRequest_MultipleRequests() { data.addSingleton(update); data.addSingleton(change); @@ -181,7 +182,7 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testIsFirstInQueue() { + void testIsFirstInQueue() { // test with empty queue assertFalse(data.isFirstInQueue(update)); @@ -194,7 +195,7 @@ public class PdpRequestsTest extends CommonRequestBase { } @Test - public void testGetPdpName() { + void testGetPdpName() { assertEquals(PDP1, data.getPdpName()); } } 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..6ef828bf 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); @@ -133,7 +132,7 @@ public class PublisherTest extends Threaded { } @Test - public void testPublisher_testStop() throws Exception { + void testPublisher_testStop() throws Exception { startThread(pub); pub.stop(); @@ -144,12 +143,12 @@ public class PublisherTest extends Threaded { } @Test - public void testPublisher_Ex() { + void testPublisher_Ex() { assertThatThrownBy(() -> new Publisher<>("unknwon-topic")).isInstanceOf(PolicyPapException.class); } @Test - public void testEnqueue() throws Exception { + void testEnqueue() throws Exception { // enqueue before running pub.enqueue(new QueueToken<>(MSG1)); @@ -165,7 +164,7 @@ public class PublisherTest extends Threaded { } @Test - public void testRun_StopBeforeProcess() throws Exception { + void testRun_StopBeforeProcess() throws Exception { // enqueue before running QueueToken<PdpMessage> token = new QueueToken<>(MSG1); pub.enqueue(token); @@ -183,7 +182,7 @@ public class PublisherTest extends Threaded { } @Test - public void testRun() throws Exception { + void testRun() throws Exception { startThread(pub); // should skip token with null message @@ -206,7 +205,7 @@ public class PublisherTest extends Threaded { } @Test - public void testGetNext() throws Exception { + void testGetNext() throws Exception { startThread(pub); // wait for a message to be processed @@ -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..6d4ac025 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. @@ -20,22 +21,22 @@ package org.onap.policy.pap.main.comm; -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.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; 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 { +class TimerManagerTest extends Threaded { private static final String EXPECTED_EXCEPTION = "expected exception"; private static final String MGR_NAME = "my-manager"; private static final String NAME1 = "timer-A"; @@ -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(); } @@ -78,7 +79,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testTimerManager_testStop() throws Exception { + void testTimerManager_testStop() throws Exception { startThread(mgr); mgr.stop(); @@ -89,7 +90,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testRegister() throws Exception { + void testRegister() throws Exception { mgr.register(NAME2, mgr::addToQueue); mgr.registerNewTime(NAME1, mgr::addToQueue); @@ -105,7 +106,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testRun_Ex() throws Exception { + void testRun_Ex() throws Exception { startThread(mgr); mgr.register(NAME1, mgr::addToQueue); @@ -118,7 +119,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testProcessTimers() throws Exception { + void testProcessTimers() throws Exception { startThread(mgr); mgr.register(NAME1, mgr::addToQueue); mgr.awaitSleep(); @@ -138,7 +139,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testGetNextTimer() throws Exception { + void testGetNextTimer() throws Exception { startThread(mgr); mgr.register(NAME1, mgr::addToQueue); mgr.awaitSleep(); @@ -149,7 +150,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testProcessTimer_StopWhileWaiting() throws Exception { + void testProcessTimer_StopWhileWaiting() throws Exception { startThread(mgr); mgr.register(NAME1, mgr::addToQueue); mgr.awaitSleep(); @@ -169,7 +170,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testProcessTimer_CancelWhileWaiting() throws Exception { + void testProcessTimer_CancelWhileWaiting() throws Exception { startThread(mgr); Timer timer = mgr.register(NAME1, mgr::addToQueue); mgr.awaitSleep(); @@ -190,7 +191,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testProcessTimer_TimerEx() throws Exception { + void testProcessTimer_TimerEx() throws Exception { mgr.register(NAME1, name -> { throw new RuntimeException(EXPECTED_EXCEPTION); @@ -211,7 +212,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testTimerAwait() throws Exception { + void testTimerAwait() throws Exception { startThread(mgr); // same times - should only sleep once @@ -236,7 +237,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testTimerCancel_WhileWaiting() throws Exception { + void testTimerCancel_WhileWaiting() throws Exception { startThread(mgr); Timer timer = mgr.register(NAME1, mgr::addToQueue); @@ -255,7 +256,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testTimerCancel_ViaReplace() throws Exception { + void testTimerCancel_ViaReplace() throws Exception { startThread(mgr); mgr.register(NAME1, name -> mgr.addToQueue("hello")); @@ -272,14 +273,14 @@ public class TimerManagerTest extends Threaded { } @Test - public void testTimerToString() { + void testTimerToString() { Timer timer = mgr.register(NAME1, mgr::addToQueue); assertNotNull(timer.toString()); assertTrue(timer.toString().contains(NAME1)); } @Test - public void testCurrentTimeMillis() { + void testCurrentTimeMillis() { long tbeg = System.currentTimeMillis(); long tcur = new TimerManager(MGR_NAME, MGR_TIMEOUT_MS).currentTimeMillis(); long tend = System.currentTimeMillis(); @@ -289,7 +290,7 @@ public class TimerManagerTest extends Threaded { } @Test - public void testSleep() throws Exception { + void testSleep() throws Exception { long tbeg = System.currentTimeMillis(); new TimerManager(MGR_NAME, MGR_TIMEOUT_MS).sleep(10); long tend = System.currentTimeMillis(); 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..f4be1409 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; @@ -49,7 +49,7 @@ import org.onap.policy.pap.main.comm.CommonRequestBase; import org.onap.policy.pap.main.comm.QueueToken; import org.onap.policy.pap.main.parameters.RequestParams; -public class RequestImplTest extends CommonRequestBase { +class RequestImplTest extends CommonRequestBase { private MyRequest req; private PdpStatus response; @@ -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..7cf731d4 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,21 +21,21 @@ 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; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.pap.main.comm.CommonRequestBase; -public class StateChangeReqTest extends CommonRequestBase { +class StateChangeReqTest extends CommonRequestBase { private StateChangeReq data; private PdpStatus response; @@ -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..7303537b 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,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.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.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; @@ -40,42 +41,42 @@ import org.onap.policy.common.utils.coder.StandardCoder; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class TestPapParameterGroup { +class TestPapParameterGroup { private static final Coder coder = new StandardCoder(); CommonTestData commonTestData = new CommonTestData(); @Test - public void testPapParameterGroup_Named() { + void testPapParameterGroup_Named() { final PapParameterGroup papParameters = new PapParameterGroup("my-name"); assertEquals("my-name", papParameters.getName()); } @Test - public void testPapParameterGroup() { + void testPapParameterGroup() { final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(1); validateParameters(papParameters); } @Test - public void testPapParameterGroup_Postgres() throws CoderException { + void testPapParameterGroup_Postgres() throws CoderException { String json = commonTestData.getPapPostgresParameterGroupAsString(1); final PapParameterGroup papPostgresParameters = coder.decode(json, PapParameterGroup.class); validateParameters(papPostgresParameters); } @Test - public void testPapParameterGroup_NullName() throws Exception { + void testPapParameterGroup_NullName() throws Exception { String json = commonTestData.getPapParameterGroupAsString(1).replace("\"PapGroup\"", "null"); final PapParameterGroup papParameters = coder.decode(json, PapParameterGroup.class); final ValidationResult validationResult = papParameters.validate(); assertFalse(validationResult.isValid()); - assertEquals(null, papParameters.getName()); + assertNull(papParameters.getName()); assertThat(validationResult.getResult()).contains("is null"); } @Test - public void testPapParameterGroup_EmptyName() throws Exception { + void testPapParameterGroup_EmptyName() throws Exception { String json = commonTestData.getPapParameterGroupAsString(1).replace(CommonTestData.PAP_GROUP_NAME, ""); final PapParameterGroup papParameters = coder.decode(json, PapParameterGroup.class); final ValidationResult validationResult = papParameters.validate(); @@ -85,7 +86,7 @@ public class TestPapParameterGroup { } @Test - public void testPapParameterGroup_SetName() { + void testPapParameterGroup_SetName() { final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(1); papParameters.setName("PapNewGroup"); final ValidationResult validationResult = papParameters.validate(); 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..ae46e66b 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; @@ -36,7 +37,7 @@ import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.TimerManager; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams.PdpModifyRequestMapParamsBuilder; -public class TestPdpModifyRequestMapParams { +class TestPdpModifyRequestMapParams { private static final long MAX_PDP_AGE_MS = 100; private PdpModifyRequestMapParamsBuilder builder; private Publisher<PdpMessage> pub; @@ -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); @@ -65,7 +66,7 @@ public class TestPdpModifyRequestMapParams { } @Test - public void testGettersSetters() { + void testGettersSetters() { PdpModifyRequestMapParams params = builder.build(); assertThat(params.getMaxPdpAgeMs()).isEqualTo(MAX_PDP_AGE_MS); assertSame(pub, params.getPdpPublisher()); @@ -77,12 +78,12 @@ public class TestPdpModifyRequestMapParams { } @Test - public void testValidate() { + void testValidate() { assertThatCode(builder.build()::validate).doesNotThrowAnyException(); } @Test - public void testValidate_InvalidMaxPdpAge() { + void testValidate_InvalidMaxPdpAge() { assertThatIllegalArgumentException().isThrownBy(() -> builder.maxPdpAgeMs(0).build().validate()) .withMessageContaining("maxPdpAgeMs"); assertThatIllegalArgumentException().isThrownBy(() -> builder.maxPdpAgeMs(-1).build().validate()) @@ -92,37 +93,37 @@ public class TestPdpModifyRequestMapParams { } @Test - public void testValidate_MissingPublisher() { + void testValidate_MissingPublisher() { assertThatIllegalArgumentException().isThrownBy(() -> builder.pdpPublisher(null).build().validate()) .withMessageContaining("publisher"); } @Test - public void testValidate_MissingDispatcher() { + void testValidate_MissingDispatcher() { assertThatIllegalArgumentException().isThrownBy(() -> builder.responseDispatcher(null).build().validate()) .withMessageContaining("Dispatch"); } @Test - public void testValidate_MissingLock() { + void testValidate_MissingLock() { assertThatIllegalArgumentException().isThrownBy(() -> builder.modifyLock(null).build().validate()) .withMessageContaining("Lock"); } @Test - public void testValidate_MissingPdpParams() { + void testValidate_MissingPdpParams() { assertThatIllegalArgumentException().isThrownBy(() -> builder.params(null).build().validate()) .withMessageContaining("PDP param"); } @Test - public void testValidate_MissingStateChangeTimers() { + void testValidate_MissingStateChangeTimers() { assertThatIllegalArgumentException().isThrownBy(() -> builder.stateChangeTimers(null).build().validate()) .withMessageContaining("state"); } @Test - public void testValidate_MissingUpdateTimers() { + void testValidate_MissingUpdateTimers() { assertThatIllegalArgumentException().isThrownBy(() -> builder.updateTimers(null).build().validate()) .withMessageContaining("update"); } 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..44a8a43f 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,23 +22,23 @@ 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; -public class TestPdpParameters { +class TestPdpParameters { private static final Coder coder = new StandardCoder(); private static final CommonTestData testData = new CommonTestData(); @Test - public void testGetters() { + void testGetters() { PdpParameters params = testData.getPapParameterGroup(1).getPdpParameters(); PdpUpdateParameters update = params.getUpdateParameters(); @@ -57,7 +58,7 @@ public class TestPdpParameters { } @Test - public void testValidate() throws Exception { + void testValidate() throws Exception { String json = testData.getPapParameterGroupAsString(1); // valid 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..df7a5397 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,28 +22,28 @@ 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; -public class TestPdpRequestParameters { +class TestPdpRequestParameters { private static final Coder coder = new StandardCoder(); @Test - public void test() throws Exception { + void test() throws Exception { PdpRequestParameters params = makeParams(10, 20); assertEquals(10, params.getMaxRetryCount()); assertEquals(20, params.getMaxWaitMs()); } @Test - public void testValidate() throws Exception { + void testValidate() throws Exception { // valid, zeroes PdpRequestParameters params = makeParams(0, 0); ValidationResult result = params.validate(); 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..d4a0b151 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; @@ -32,11 +33,11 @@ import org.onap.policy.common.utils.coder.StandardCoder; * As {@link TestPdpRequestParameters} tests the "getXxx()" methods, all we need to verify * here is that the object is valid after loading from JSON. */ -public class TestPdpStateChangeParameters { +class TestPdpStateChangeParameters { private static final Coder coder = new StandardCoder(); @Test - public void testValidate() throws Exception { + void testValidate() throws Exception { // valid, zeroes PdpStateChangeParameters params = makeParams(10, 20); ValidationResult result = params.validate(); 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..9d351ae4 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; @@ -32,11 +33,11 @@ import org.onap.policy.common.utils.coder.StandardCoder; * As {@link TestPdpRequestParameters} tests the "getXxx()" methods, all we need to verify * here is that the object is valid after loading from JSON. */ -public class TestPdpUpdateParameters { +class TestPdpUpdateParameters { private static final Coder coder = new StandardCoder(); @Test - public void testValidate() throws Exception { + void testValidate() throws Exception { // valid, zeroes PdpUpdateParameters params = makeParams(10, 20); ValidationResult result = params.validate(); 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..f853f01d 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,19 +22,19 @@ 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; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.TimerManager; -public class TestRequestParams { +class TestRequestParams { private static final int RETRIES = 1; private RequestParams params; @@ -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); @@ -58,7 +59,7 @@ public class TestRequestParams { } @Test - public void testGettersSetters() { + void testGettersSetters() { assertSame(params, params.setModifyLock(lock).setPdpPublisher(pub).setResponseDispatcher(disp)); assertSame(pub, params.getPdpPublisher()); @@ -69,31 +70,31 @@ public class TestRequestParams { } @Test - public void testValidate() { + void testValidate() { // no exception params.validate(); } @Test - public void testValidate_MissingLock() { + void testValidate_MissingLock() { assertThatIllegalArgumentException().isThrownBy(() -> params.setModifyLock(null).validate()) .withMessageContaining("Lock"); } @Test - public void testValidate_MissingDispatcher() { + void testValidate_MissingDispatcher() { assertThatIllegalArgumentException().isThrownBy(() -> params.setResponseDispatcher(null).validate()) .withMessageContaining("Dispatcher"); } @Test - public void testValidate_MissingPublisher() { + void testValidate_MissingPublisher() { assertThatIllegalArgumentException().isThrownBy(() -> params.setPdpPublisher(null).validate()) .withMessageContaining("publisher"); } @Test - public void testValidate_MissingTimers() { + void testValidate_MissingTimers() { assertThatIllegalArgumentException().isThrownBy(() -> params.setTimers(null).validate()) .withMessageContaining("timer"); } 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..93f73b08 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"); @@ -23,20 +23,20 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.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; import org.springframework.http.ResponseEntity.BodyBuilder; -public class PapRestControllerV1Test { +class PapRestControllerV1Test { @Mock SecurityContext mockSecurityContext; @@ -44,19 +44,19 @@ 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(); } @Test - public void testAddVersionControlHeaders() { + void testAddVersionControlHeaders() { ResponseEntity<Object> resp = PapRestControllerV1.addVersionControlHeaders(bldr).build(); assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_MINOR_NAME).get(0)); assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_PATCH_NAME).get(0)); @@ -64,20 +64,20 @@ public class PapRestControllerV1Test { } @Test - public void testAddLoggingHeaders_Null() { + void testAddLoggingHeaders_Null() { ResponseEntity<Object> resp = PapRestControllerV1.addLoggingHeaders(bldr, null).build(); assertNotNull(resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME)); } @Test - public void testAddLoggingHeaders_NonNull() { + void testAddLoggingHeaders_NonNull() { UUID uuid = UUID.randomUUID(); ResponseEntity<Object> resp = PapRestControllerV1.addLoggingHeaders(bldr, uuid).build(); assertEquals(uuid.toString(), resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME).get(0)); } @Test - public void testGetPrincipal() { + void testGetPrincipal() { assertThat(new PapRestControllerV1().getPrincipal()).isEmpty(); } } 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..a1a16bf5 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,33 +20,34 @@ 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.actuate.observability.AutoConfigureObservability; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; 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 +@AutoConfigureObservability @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class TestActuatorEndpoints { @@ -57,7 +58,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 +72,16 @@ public class TestActuatorEndpoints { } @Test - public void testMetricsEndpoint() throws Exception { - mock.perform(get("/plain-metrics").with(SecurityMockMvcRequestPostProcessors.httpBasic( - "policyAdmin", "zb!XztG34"))) + void testMetricsEndpoint() throws Exception { + mock.perform(get("/plain-metrics").with(mockSecurity)) .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..4a33e9f1 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. @@ -21,15 +22,15 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -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.assertFalse; +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.PdpGroup; -public class TestGroupData { +class TestGroupData { private static final String NAME = "my-name"; private PdpGroup oldGroup; @@ -39,7 +40,7 @@ public class TestGroupData { /** * Sets up. */ - @Before + @BeforeEach public void setUp() { oldGroup = new PdpGroup(); oldGroup.setName(NAME); @@ -50,7 +51,7 @@ public class TestGroupData { } @Test - public void testNew() { + void testNew() { data = new GroupData(oldGroup, true); assertSame(oldGroup, data.getGroup()); @@ -74,7 +75,7 @@ public class TestGroupData { } @Test - public void testUpdateOnly() { + void testUpdateOnly() { assertTrue(data.isUnchanged()); assertFalse(data.isUpdated()); assertSame(oldGroup, data.getGroup()); 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..67f637a1 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. @@ -20,15 +20,15 @@ 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 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; @@ -39,17 +39,17 @@ import org.springframework.test.context.ActiveProfiles; * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. */ @ActiveProfiles({ "test", "default" }) -public class TestPdpGroupCreateOrUpdateControllerV1 extends CommonPapRestServer { +class TestPdpGroupCreateOrUpdateControllerV1 extends CommonPapRestServer { private static final String CREATEORUPDATE_GROUPS_ENDPOINT = "pdps/groups/batch"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(CREATEORUPDATE_GROUPS_ENDPOINT); } @Test - public void testCreateOrUpdateGroups() throws Exception { + void testCreateOrUpdateGroups() throws Exception { Entity<PdpGroups> entgrp = makePdpGroupsEntity(); Invocation.Builder invocationBuilder = sendRequest(CREATEORUPDATE_GROUPS_ENDPOINT); 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..445a921f 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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.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 + void testCreateOrUpdateGroups() throws Exception { + prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); + + // no groups, so no action should have been taken + assertNoGroupAction(); + } + + @Test + void testCreateOrUpdateGroups_InvalidRequest() throws Exception { + assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) + .hasMessageContaining("is null"); + + assertNoGroupAction(); + } + + @Test + 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 + 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 + 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 + 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 + void testValidateGroupOnly_NullState() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(null); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + void testValidateGroupOnly_Active() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + void testValidateGroupOnly_Passive() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..104fd86e 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"); @@ -21,12 +21,12 @@ package org.onap.policy.pap.main.rest; -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.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.springframework.test.context.ActiveProfiles; @@ -34,22 +34,21 @@ import org.springframework.test.context.ActiveProfiles; * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. */ @ActiveProfiles({ "test", "default" }) -public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { +class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { private static final String GROUP_NOT_FOUND = "group not found"; private static final String DELETE_GROUP_ENDPOINT = "pdps/groups"; private static final String DELETE_POLICIES_ENDPOINT = "pdps/policies"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(DELETE_GROUP_ENDPOINT + "/{name}"); - super.testSwagger(DELETE_POLICIES_ENDPOINT + "/{name}"); super.testSwagger(DELETE_POLICIES_ENDPOINT + "/{name}/versions/{version}"); } @Test - public void testDeleteGroup() throws Exception { + void testDeleteGroup() throws Exception { String uri = DELETE_GROUP_ENDPOINT + "/my-name"; Invocation.Builder invocationBuilder = sendRequest(uri); @@ -68,7 +67,7 @@ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { } @Test - public void testDeletePolicy() throws Exception { + void testDeletePolicy() throws Exception { String uri = DELETE_POLICIES_ENDPOINT + "/my-name"; Invocation.Builder invocationBuilder = sendRequest(uri); @@ -87,7 +86,7 @@ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { } @Test - public void testDeletePolicyVersion() throws Exception { + void testDeletePolicyVersion() throws Exception { String uri = DELETE_POLICIES_ENDPOINT + "/my-name/versions/3"; Invocation.Builder invocationBuilder = sendRequest(uri); 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..aff3fa2b 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"); @@ -23,10 +23,10 @@ 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.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.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; @@ -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(); @@ -96,7 +96,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testDeleteGroup_Active() throws Exception { + void testDeleteGroup_Active() throws Exception { PdpGroup group = loadGroup("deleteGroup.json"); group.setPdpGroupState(PdpState.ACTIVE); @@ -104,19 +104,19 @@ 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() { + 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 - public void testDeleteGroup_Inactive() throws Exception { + void testDeleteGroup_Inactive() throws Exception { PdpGroup group = loadGroup("deleteGroup.json"); when(session.getGroup(GROUP1_NAME)).thenReturn(group); @@ -130,7 +130,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testDeleteGroup_Ex() throws Exception { + void testDeleteGroup_Ex() throws Exception { PdpGroup group = loadGroup("deleteGroup.json"); when(session.getGroup(GROUP1_NAME)).thenReturn(group); @@ -147,7 +147,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { * @throws Exception if an error occurs */ @Test - public void testUndeploy_Full() throws Exception { + void testUndeploy_Full() throws Exception { when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); PdpGroup group = loadGroup("undeploy.json"); @@ -179,15 +179,15 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testUndeployPolicy_NotFound() { + void testUndeployPolicy_NotFound() { 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 - public void testUndeployPolicy_DaoEx() throws Exception { + void testUndeployPolicy_DaoEx() throws Exception { PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); prov = spy(prov); @@ -197,7 +197,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testUndeployPolicy_RtEx() throws Exception { + void testUndeployPolicy_RtEx() throws Exception { RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); prov = spy(prov); @@ -205,11 +205,11 @@ 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 - public void testMakeUpdater_WithVersion() throws PfModelException { + void testMakeUpdater_WithVersion() throws PfModelException { /* * this group has two matching policies and one policy with a different name. */ @@ -230,7 +230,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testMakeUpdater_NullVersion() throws PfModelException { + void testMakeUpdater_NullVersion() throws PfModelException { /* * this group has two matching policies and one policy with a different name. */ @@ -249,7 +249,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testMakeUpdater_NotFound() throws PfModelException { + void testMakeUpdater_NotFound() throws PfModelException { /* * this group has one policy with a different name and one with a different * version, but not the policy of interest. @@ -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..338f2028 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"); @@ -21,16 +21,16 @@ 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 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; @@ -43,19 +43,19 @@ import org.springframework.test.context.ActiveProfiles; * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. */ @ActiveProfiles({ "test", "default" }) -public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { +class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { private static final String DEPLOY_GROUP_ENDPOINT = "pdps/deployments/batch"; private static final String DEPLOY_POLICIES_ENDPOINT = "pdps/policies"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(DEPLOY_GROUP_ENDPOINT); super.testSwagger(DEPLOY_POLICIES_ENDPOINT); } @Test - public void testUpdateGroupPolicies() throws Exception { + void testUpdateGroupPolicies() throws Exception { Entity<DeploymentGroups> entgrp = makeDeploymentGroupsEntity(); Invocation.Builder invocationBuilder = sendRequest(DEPLOY_GROUP_ENDPOINT); @@ -74,7 +74,7 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { } @Test - public void testDeployPolicies() throws Exception { + void testDeployPolicies() throws Exception { Entity<PdpDeployPolicies> entgrp = makePdpPoliciesEntity(); Invocation.Builder invocationBuilder = sendRequest(DEPLOY_POLICIES_ENDPOINT); 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..0de42396 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"); @@ -25,21 +25,21 @@ 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.assertj.core.api.Assertions.assertThatThrownBy; -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.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,18 +92,18 @@ 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"))); } /** * Tests updateGroupPolicies when policies are being added. */ @Test - public void testUpdateGroupPoliciesAdd() throws Exception { + void testUpdateGroupPoliciesAdd() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); // add new policies List<ToscaConceptIdentifier> policies = newgrp.getPdpSubgroups().get(0).getPolicies(); @@ -127,7 +127,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * Tests updateGroupPolicies when policies are being deleted. */ @Test - public void testUpdateGroupPoliciesDelete() throws Exception { + void testUpdateGroupPoliciesDelete() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); @@ -137,7 +137,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); // policy that should be left final ToscaConceptIdentifier policyId1 = policies.remove(0); @@ -163,7 +163,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * subgroup. */ @Test - public void testUpdateGroupPoliciesAddAndDelete() throws Exception { + void testUpdateGroupPoliciesAddAndDelete() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpSubGroup subgrp = newgrp.getPdpSubgroups().get(0); @@ -171,7 +171,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // put policy3 into db subgroup subgrp.getPolicies().add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); // now make the subgrp reflect our final expectation subgrp.getPolicies().remove(1); @@ -181,19 +181,19 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { DeploymentSubGroup depsub1 = new DeploymentSubGroup(); depsub1.setAction(Action.POST); depsub1.setPdpType(subgrp.getPdpType()); - depsub1.setPolicies(Arrays.asList(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION))); + depsub1.setPolicies(List.of(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION))); DeploymentSubGroup depsub2 = new DeploymentSubGroup(); depsub2.setAction(Action.DELETE); depsub2.setPdpType(subgrp.getPdpType()); - depsub2.setPolicies(Arrays.asList(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION))); + depsub2.setPolicies(List.of(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION))); DeploymentGroup depgroup = new DeploymentGroup(); depgroup.setName(newgrp.getName()); depgroup.setDeploymentSubgroups(Arrays.asList(depsub1, depsub2)); DeploymentGroups depgroups = new DeploymentGroups(); - depgroups.setGroups(Arrays.asList(depgroup)); + depgroups.setGroups(List.of(depgroup)); when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy2.json")); @@ -205,11 +205,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroupPolicies() throws Exception { + void testUpdateGroupPolicies() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -221,7 +221,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroupPolicies_EmptyRequest() throws Exception { + void testUpdateGroupPolicies_EmptyRequest() throws Exception { prov.updateGroupPolicies(toDeploymentGroups(loadPdpGroups("emptyGroups.json")), DEFAULT_USER); // no groups, so no action should have been taken @@ -229,7 +229,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroupPolicies_InvalidRequest() throws Exception { + void testUpdateGroupPolicies_InvalidRequest() throws Exception { assertThatThrownBy(() -> prov.updateGroupPolicies(new DeploymentGroups(), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("is null"); @@ -237,7 +237,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroup_UnknownGroup() throws Exception { + void testUpdateGroup_UnknownGroup() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); String groupName = groups.getGroups().get(0).getName(); @@ -253,12 +253,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroup() throws Exception { + void testUpdateGroup() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); // DB group = new group PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); @@ -266,10 +266,10 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroup_NewSubGroup() throws Exception { + void testUpdateGroup_NewSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("deployGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("pdpTypeB") @@ -279,11 +279,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateGroup_UpdatedSubGroup() throws Exception { + void testUpdateGroup_UpdatedSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -295,14 +295,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_Invalid() throws Exception { + void testUpdateSubGroup_Invalid() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); // group has no policies yet group.getPdpSubgroups().get(0).getPolicies().clear(); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // unknown policy when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); @@ -316,7 +316,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_Policies() throws Exception { + void testUpdateSubGroup_Policies() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); @@ -327,7 +327,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.getPdpSubgroups().add(subgrp2); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // add two new policies ToscaConceptIdentifier policyId2 = new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION); @@ -354,12 +354,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_PolicyVersionPrefix() throws Exception { + void testUpdateSubGroup_PolicyVersionPrefix() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // use version prefix PdpSubGroup subgrp = newgrp.getPdpSubgroups().get(0); @@ -381,12 +381,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_PolicyVersionPrefixMismatch() throws Exception { + void testUpdateSubGroup_PolicyVersionPrefixMismatch() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // use incorrect version prefix newgrp.getPdpSubgroups().get(0).getPolicies().get(0).setVersion("9"); @@ -398,11 +398,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_Unchanged() throws Exception { + void testUpdateSubGroup_Unchanged() throws Exception { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER); @@ -419,11 +419,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_PolicyVersionMismatch() throws Exception { + void testUpdateSubGroup_PolicyVersionMismatch() throws Exception { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); // arrange for DB policy version to be different PdpSubGroup dbsubgrp = dbgroup.getPdpSubgroups().get(0); @@ -438,11 +438,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testUpdateSubGroup_UnsupportedType() throws Exception { + void testUpdateSubGroup_UnsupportedType() throws Exception { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); final DeploymentGroups groups = toDeploymentGroups(dbgroups); @@ -464,7 +464,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeployPolicies() throws PfModelException { + void testDeployPolicies() { assertThatCode(() -> prov.deployPolicies(loadEmptyRequest(), DEFAULT_USER)).doesNotThrowAnyException(); } @@ -472,7 +472,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * Tests deployPolicies() when the policies are invalid. */ @Test - public void testDeployPoliciesInvalidPolicies() throws Exception { + void testDeployPoliciesInvalidPolicies() { // valid list PdpDeployPolicies policies0 = loadFile("PapPoliciesList.json", PdpDeployPolicies.class); assertThatCode(() -> prov.deployPolicies(policies0, DEFAULT_USER)).doesNotThrowAnyException(); @@ -512,7 +512,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * @throws Exception if an error occurs */ @Test - public void testDeployPoliciesWildCard() throws Exception { + void testDeployPoliciesWildCard() throws Exception { when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); @@ -537,12 +537,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeploySimplePolicies() throws Exception { + void testDeploySimplePolicies() { assertThatCode(() -> prov.deployPolicies(loadEmptyRequest(), DEFAULT_USER)).doesNotThrowAnyException(); } @Test - public void testDeploySimplePolicies_PfRtEx() throws Exception { + void testDeploySimplePolicies_PfRtEx() { PfModelRuntimeException exc = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(exc); @@ -550,7 +550,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeploySimplePolicies_RuntimeEx() throws Exception { + void testDeploySimplePolicies_RuntimeEx() throws Exception { RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); @@ -559,7 +559,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeploySimplePolicies_NoGroups() throws Exception { + void testDeploySimplePolicies_NoGroups() { when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class) @@ -567,7 +567,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testMakeUpdater() throws Exception { + void testMakeUpdater() throws Exception { /* * Each subgroup has a different PDP type and name. * @@ -595,7 +595,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testMakeUpdater_PolicyVersionMismatch() throws Exception { + void testMakeUpdater_PolicyVersionMismatch() { // subgroup has a different version of the Policy when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json")); @@ -610,7 +610,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testMakeUpdater_NoPdps() throws Exception { + void testMakeUpdater_NoPdps() { // subgroup has no PDPs when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); @@ -634,13 +634,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { assertThat(update.getPoliciesToBeDeployed()).contains(policy1); } - private void assertNoGroupAction() throws Exception { + private void assertNoGroupAction() { verify(pdpGroupService, never()).createPdpGroups(any()); verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(), any()); } - private void assertGroupUpdate(PdpGroup group, PdpSubGroup subgrp) throws Exception { + private void assertGroupUpdate(PdpGroup group, PdpSubGroup subgrp) { verify(pdpGroupService, never()).createPdpGroups(any()); assertEquals(0, getStateChangeRequests(1).size()); @@ -655,13 +655,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { assertEquals(subgrp.getPdpType(), pdpUpdate.getPdpSubgroup()); List<ToscaConceptIdentifier> pdpPolicies = pdpUpdate.getPoliciesToBeDeployed().stream() - .map(ToscaPolicy::getIdentifier).collect(Collectors.toList()); - Collections.sort(pdpPolicies); + .map(ToscaPolicy::getIdentifier).sorted().collect(Collectors.toList()); assertThat(subgrp.getPolicies()).containsAll(pdpPolicies); List<PdpGroup> updates = getGroupUpdates(); - assertEquals(Arrays.asList(group), updates); + assertEquals(List.of(group), updates); } /** 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..dff023cc 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. * ================================================================================ @@ -22,17 +22,18 @@ 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.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.runner.RunWith; +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.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -51,28 +52,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 +88,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..0dd311c4 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. @@ -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.PdpGroups; import org.springframework.test.context.ActiveProfiles; @@ -35,18 +35,18 @@ import org.springframework.test.context.ActiveProfiles; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@ActiveProfiles({ "test", "default" }) -public class TestPdpGroupQueryControllerV1 extends CommonPapRestServer { +@ActiveProfiles({"test", "default"}) +class TestPdpGroupQueryControllerV1 extends CommonPapRestServer { private static final String GROUP_ENDPOINT = "pdps"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(GROUP_ENDPOINT); } @Test - public void testChangeGroupState() throws Exception { + void testChangeGroupState() throws Exception { final String uri = GROUP_ENDPOINT; final Invocation.Builder invocationBuilder = sendRequest(uri); 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..0701bd97 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. @@ -20,13 +20,13 @@ package org.onap.policy.pap.main.rest; -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 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,18 +35,18 @@ import org.springframework.test.context.ActiveProfiles; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@ActiveProfiles({ "test", "default" }) -public class TestPdpGroupStateChangeControllerV1 extends CommonPapRestServer { +@ActiveProfiles({"test", "default"}) +class TestPdpGroupStateChangeControllerV1 extends CommonPapRestServer { private static final String GROUP_ENDPOINT = "pdps/groups"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(GROUP_ENDPOINT + "/{name}"); } @Test - public void testChangeGroupState() throws Exception { + void testChangeGroupState() throws Exception { final String uri = GROUP_ENDPOINT + "/my-name?state=ACTIVE"; final Invocation.Builder invocationBuilder = sendRequest(uri); 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..8c4cd821 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. @@ -19,24 +19,23 @@ package org.onap.policy.pap.main.rest; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.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" }) -public class TestPolicyAuditControllerV1 extends CommonPapRestServer { +@ActiveProfiles({"test", "default"}) +class TestPolicyAuditControllerV1 extends CommonPapRestServer { private static final String POLICY_AUDIT_ENDPOINT = "policies/audit"; @Test - public void testSwagger() throws Exception { - + void testSwagger() throws Exception { super.testSwagger(POLICY_AUDIT_ENDPOINT); super.testSwagger(POLICY_AUDIT_ENDPOINT + "/{pdpGroupName}"); super.testSwagger(POLICY_AUDIT_ENDPOINT + "/{pdpGroupName}/{policyName}/{policyVersion}"); @@ -44,7 +43,7 @@ public class TestPolicyAuditControllerV1 extends CommonPapRestServer { } @Test - public void testGetAllAuditRecords() throws Exception { + void testGetAllAuditRecords() throws Exception { String uri = POLICY_AUDIT_ENDPOINT; // verify it fails when no authorization info is included @@ -52,12 +51,12 @@ public class TestPolicyAuditControllerV1 extends CommonPapRestServer { } @Test - public void testGetAuditRecordsByGroup() throws Exception { + void testGetAuditRecordsByGroup() throws Exception { checkRequest(POLICY_AUDIT_ENDPOINT + "/my-group-name"); } @Test - public void testGetAuditRecordsOfPolicy() throws Exception { + void testGetAuditRecordsOfPolicy() throws Exception { checkRequest(POLICY_AUDIT_ENDPOINT + "/my-group-name/my-name/1.2.3"); checkRequest(POLICY_AUDIT_ENDPOINT + "/my-name/1.2.3"); } 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..12b9b351 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,19 +23,18 @@ 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; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; - public class TestPolicyAuditManager extends ProviderSuper { private static final ToscaConceptIdentifier MY_POLICY = new ToscaConceptIdentifier("myPolicy", "1.0.0"); @@ -50,19 +49,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 +75,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..b0928071 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; @@ -43,7 +43,7 @@ import org.springframework.test.context.ActiveProfiles; * @author Yehui Wang (yehui.wang@est.tech) */ @ActiveProfiles({ "test", "default" }) -public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestServer { +class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestServer { private static final String ENDPOINT = "components/healthcheck"; private List<RestClientParameters> savedRestClientParameters; @@ -52,13 +52,13 @@ public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestSe private PapParameterGroup papParameterGroup; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(ENDPOINT); } @Test @SuppressWarnings("unchecked") - public void testPolicyComponentsHealthCheck() throws Exception { + void testPolicyComponentsHealthCheck() throws Exception { // take out the other components for healthcheck savedRestClientParameters = papParameterGroup.getHealthCheckRestClientParameters(); papParameterGroup.setHealthCheckRestClientParameters(null); 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..41597218 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,24 +22,23 @@ 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.runner.RunWith; +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.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; import org.onap.policy.common.endpoints.report.HealthCheckReport; @@ -61,8 +60,7 @@ import org.onap.policy.pap.main.startstop.PapActivator; import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class TestPolicyComponentsHealthCheckProvider { +class TestPolicyComponentsHealthCheckProvider { private static final String CLIENT_1 = "client1"; private static final String PDP_GROUP_DATA_FILE = "rest/pdpGroup.json"; @@ -102,13 +100,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 +156,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 +209,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 +219,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 +227,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..08ec80a4 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,25 +23,25 @@ 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; /** * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. */ @ActiveProfiles({ "test", "default" }) -public class TestPolicyStatusControllerV1 extends CommonPapRestServer { +class TestPolicyStatusControllerV1 extends CommonPapRestServer { private static final String POLICY_STATUS_ENDPOINT = "policies/deployed"; private static final String POLICY_DEPLOYMENT_STATUS_ENDPOINT = "policies/status"; @Test - public void testSwagger() throws Exception { + void testSwagger() throws Exception { super.testSwagger(POLICY_STATUS_ENDPOINT); super.testSwagger(POLICY_STATUS_ENDPOINT + "/{name}"); super.testSwagger(POLICY_STATUS_ENDPOINT + "/{name}/{version}"); @@ -53,40 +53,40 @@ public class TestPolicyStatusControllerV1 extends CommonPapRestServer { } @Test - public void testQueryAllDeployedPolicies() throws Exception { + void testQueryAllDeployedPolicies() throws Exception { // verify it fails when no authorization info is included checkUnauthRequest(POLICY_STATUS_ENDPOINT, SyncInvoker::get); checkRequest(POLICY_STATUS_ENDPOINT); } @Test - public void testQueryAllDeployedPoliciesWithRegex() throws Exception { + void testQueryAllDeployedPoliciesWithRegex() throws Exception { checkRequest(POLICY_STATUS_ENDPOINT + "?regex=my.(1)name"); checkEmptyRegexRequest(POLICY_STATUS_ENDPOINT + "?regex="); checkInvalidRegexRequest(POLICY_STATUS_ENDPOINT + "?regex=my-(name"); } @Test - public void testQueryDeployedPolicies() throws Exception { + void testQueryDeployedPolicies() throws Exception { checkRequest(POLICY_STATUS_ENDPOINT + "/my-name"); checkRequest(POLICY_STATUS_ENDPOINT + "/my-name/1.2.3"); } @Test - public void testGetStatusOfAllPolicies() throws Exception { + void testGetStatusOfAllPolicies() throws Exception { // verify it fails when no authorization info is included checkUnauthRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT, SyncInvoker::get); } @Test - public void testGetStatusOfPolicies() throws Exception { + void testGetStatusOfPolicies() throws Exception { checkRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/my-group-name"); checkRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/my-group-name/my-name"); checkRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/my-group-name/my-name/1.2.3"); } @Test - public void testGetStatusOfPoliciesWithRegex() throws Exception { + void testGetStatusOfPoliciesWithRegex() throws Exception { checkRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/my-group-name?regex=my-%3F%5Bmn%5Da.%7B1%7De"); checkRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/my-group-name?regex=my.(1)name"); // my-?[mna.{1}e 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..9b809095 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 { + 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 { + void testGetStatusToscaConceptIdentifierOptVersion() { ToscaConceptIdentifierOptVersion optIdent = buildPolicyStatusToReturn2(); @@ -131,12 +130,12 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatus() throws PfModelException { + 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 { + void testGetPolicyStatusByGroupAndPolicyIdVersion() { ToscaConceptIdentifierOptVersion optIdent = buildPolicyStatusToReturn2(); @@ -199,7 +198,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusByRegexNoMatch() throws PfModelException { + void testGetPolicyStatusByRegexNoMatch() { buildPolicyStatusToReturn1(); final String pattern = "Hello"; @@ -208,7 +207,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { } @Test - public void testGetPolicyStatusOneMatch() throws PfModelException { + 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 { + 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..eab65a3d 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,20 +21,20 @@ 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; import static org.mockito.Mockito.when; -import java.util.Arrays; 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 +66,7 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { private MyProvider prov; - @AfterClass + @AfterAll public static void tearDownAfterClass() { Registry.newRegistry(); } @@ -77,7 +77,7 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { * @throws Exception if an error occurs */ @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -96,15 +96,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); @@ -113,16 +113,16 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { } @Test - public void testUndeployPolicies() throws PfModelException { - subgroup.setPolicies(new LinkedList<>(Arrays.asList(ident1, ident2, ident3, ident4))); + void testUndeployPolicies() throws PfModelException { + 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()); @@ -132,11 +132,11 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { * Tests undeployPolicies() when the policies do not exist in the subgroup. */ @Test - public void testUndeployPoliciesUnchanged() throws PfModelException { - List<ToscaConceptIdentifier> origlist = Arrays.asList(ident3, ident4); + void testUndeployPoliciesUnchanged() throws PfModelException { + 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); @@ -152,13 +152,13 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { * Tests undeployPolicies() when the group is not found. */ @Test - public void testUndeployPoliciesGroupNotFound() throws PfModelException { + 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(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); @@ -171,13 +171,13 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { * Tests undeployPolicies() when the subgroup is not found. */ @Test - public void testUndeployPoliciesSubGroupNotFound() throws PfModelException { + 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,12 +186,11 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { verify(session, never()).addUpdate(any()); } - @Test(expected = UnsupportedOperationException.class) - public void testMakeUpdater() { - prov.makeUpdater(null, null, null); + @Test + void testMakeUpdater() { + assertThrows(UnsupportedOperationException.class, () -> prov.makeUpdater(null, null, null)); } - private class MyProvider extends PolicyUndeployerImpl { @Override 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..9a95590e 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(); @@ -91,13 +90,13 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testProviderBase() { + void testProviderBase() { assertSame(lockit, ReflectionTestUtils.getField(prov, "updateLock")); assertSame(reqmap, ReflectionTestUtils.getField(prov, "requestMap")); } @Test - public void testProcess() throws Exception { + void testProcess() throws Exception { prov.process(loadRequest(), this::handle); assertGroup(getGroupUpdates(), GROUP1_NAME); @@ -108,7 +107,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testProcess_PfRtEx() throws Exception { + void testProcess_PfRtEx() throws Exception { PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); @@ -116,7 +115,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testProcess_RuntimeEx() throws Exception { + void testProcess_RuntimeEx() throws Exception { RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION); when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); @@ -125,7 +124,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testProcessPolicy_NoGroups() throws Exception { + void testProcessPolicy_NoGroups() throws Exception { when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); SessionData session = @@ -137,7 +136,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testGetPolicy() throws Exception { + void testGetPolicy() throws Exception { PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); @@ -147,7 +146,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testGetPolicy_NotFound() throws Exception { + void testGetPolicy_NotFound() throws Exception { when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); ToscaConceptIdentifierOptVersion req = loadRequest(); @@ -158,7 +157,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testGetGroup() throws Exception { + void testGetGroup() throws Exception { when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) .thenReturn(loadGroups("groups.json")); @@ -168,7 +167,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testUpgradeGroup() throws Exception { + void testUpgradeGroup() throws Exception { /* * Each subgroup has a different PDP type and name. * @@ -196,7 +195,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testUpgradeGroup_Multiple() throws Exception { + void testUpgradeGroup_Multiple() throws Exception { /* * Policy data in the DB: policy1=type1, policy2=type2, policy3=type3, * policy4=type1 @@ -254,7 +253,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testUpgradeGroup_NothingUpdated() throws Exception { + void testUpgradeGroup_NothingUpdated() throws Exception { prov.clear(); prov.add(false); @@ -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..82f34616 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; @@ -64,7 +63,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.pap.main.notification.DeploymentStatus; import org.onap.policy.pap.main.service.PolicyStatusService; -public class TestSessionData extends ProviderSuper { +class TestSessionData extends ProviderSuper { private static final String GROUP_NAME = "groupA"; private static final String PDP_TYPE = "MySubGroup"; private static final String PDP1 = "pdp_1"; @@ -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(); @@ -104,9 +103,9 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicyType() throws Exception { + 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)); @@ -115,14 +114,14 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicyType_NotFound() throws Exception { + void testGetPolicyType_NotFound() throws Exception { when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicyType(type)); } @Test - public void testGetPolicyType_DaoEx() throws Exception { + void testGetPolicyType_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex); @@ -130,9 +129,9 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicy_NullVersion() throws Exception { + 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()))); @@ -148,9 +147,9 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicy_MajorVersion() throws Exception { + 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)); @@ -166,9 +165,9 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicy_MajorMinorVersion() throws Exception { + 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()))); @@ -184,14 +183,14 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetPolicy_NotFound() throws Exception { + void testGetPolicy_NotFound() throws Exception { when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicy(ident)); } @Test - public void testGetPolicy_DaoEx() throws Exception { + void testGetPolicy_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); when(toscaService.getFilteredPolicyList(any())).thenThrow(ex); @@ -199,7 +198,7 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testIsVersionPrefix() { + void testIsVersionPrefix() { assertTrue(SessionData.isVersionPrefix("1")); assertTrue(SessionData.isVersionPrefix("12")); assertTrue(SessionData.isVersionPrefix("1.2")); @@ -213,7 +212,7 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testAddRequests_testGetPdpStateChanges_testGetPdpUpdates() { + void testAddRequests_testGetPdpStateChanges_testGetPdpUpdates() { // pre-load with a update and state-change for other PDPs PdpUpdate update2 = makeUpdate(PDP2); session.addUpdate(update2); @@ -262,15 +261,15 @@ 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)); } @Test - public void testAddRequests_MismatchedNames() { + void testAddRequests_MismatchedNames() { PdpUpdate update = makeUpdate(PDP1); PdpStateChange change = makeStateChange(PDP2); assertThatIllegalArgumentException().isThrownBy(() -> session.addRequests(update, change)) @@ -278,7 +277,7 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testAddUpdate_testGetPdpUpdates() { + void testAddUpdate_testGetPdpUpdates() { // several different updates, but one duplicate PdpUpdate update1 = makeUpdate(PDP1); session.addUpdate(update1); @@ -290,18 +289,18 @@ 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 - public void testAddStateChange_testGetPdpStateChanges() { + void testAddStateChange_testGetPdpStateChanges() { // several different changes, but one duplicate PdpStateChange change1 = makeStateChange(PDP1); session.addStateChange(change1); @@ -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) { @@ -342,7 +341,7 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testCreate() throws Exception { + void testCreate() throws Exception { assertTrue(session.isUnchanged()); session.create(group1); @@ -361,17 +360,17 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testUpdate() throws Exception { + void testUpdate() { 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()); @@ -396,16 +395,16 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testUpdate_NotInCache() throws Exception { - when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + void testUpdate_NotInCache() { + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); assertThatIllegalStateException().isThrownBy(() -> session.update(new PdpGroup(group1))) .withMessage("group not cached: groupA"); } @Test - public void testGetGroup() throws Exception { - when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + void testGetGroup() throws Exception { + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(List.of(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); verify(pdpGroupService).getPdpGroups(any(String.class)); @@ -418,7 +417,7 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testGetGroup_NotFound() throws Exception { + void testGetGroup_NotFound() throws Exception { when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Collections.emptyList()); assertNull(session.getGroup(GROUP_NAME)); @@ -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); + void testGetActivePdpGroupsByPolicyType() { + List<PdpGroup> groups = List.of(group1, group2); when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // repeat @@ -451,8 +450,8 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testAddGroup() throws Exception { - List<PdpGroup> groups = Arrays.asList(group1, group2); + void testAddGroup() { + List<PdpGroup> groups = List.of(group1, group2); when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // query by each type @@ -469,10 +468,10 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testUpdateDb() throws Exception { + void testUpdateDb() { // 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); @@ -520,9 +519,9 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testUpdateDb_Empty() throws Exception { + void testUpdateDb_Empty() { // 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(); @@ -534,19 +533,19 @@ public class TestSessionData extends ProviderSuper { } @Test - public void testDeleteGroupFromDb() throws Exception { + void testDeleteGroupFromDb() { session.deleteGroupFromDb(group1); verify(pdpGroupService).deletePdpGroup(group1.getName()); } @Test - public void testTrackDeploy() throws PfModelException { + void testTrackDeploy() throws PfModelException { testTrack(true); } @Test - public void testTrackUndeploy() throws PfModelException { + void testTrackUndeploy() throws PfModelException { testTrack(false); } @@ -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..d1c89b21 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,19 +21,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 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 { +class HealthCheckTest extends End2EndBase { private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; @Test - public void testHealthCheckSuccess() throws Exception { + void testHealthCheckSuccess() throws Exception { final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); 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..e7fc09c6 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; @@ -40,7 +40,7 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PdpGroupCreateOrUpdateTest extends End2EndBase { +class PdpGroupCreateOrUpdateTest extends End2EndBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupCreateOrUpdateTest.class); private static final String CREATEORUPDATE_GROUPS_ENDPOINT = "pdps/groups/batch"; @@ -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 { @@ -77,13 +77,13 @@ public class PdpGroupCreateOrUpdateTest extends End2EndBase { } @Test - public void testCreateGroupsJson() throws Exception { + void testCreateGroupsJson() throws Exception { createPdpGroups("createGroups.json", MediaType.APPLICATION_JSON); } @Test - public void testCreateGroupsYaml() throws Exception { + void testCreateGroupsYaml() throws Exception { createPdpGroups("createGroups.yaml", "application/yaml"); } 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..647a60e8 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; @@ -46,7 +46,7 @@ import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1; -public class PdpGroupDeleteTest extends End2EndBase { +class PdpGroupDeleteTest extends End2EndBase { private static final String DELETE_GROUP_ENDPOINT = "pdps/groups"; private static final String DELETE_POLICIES_ENDPOINT = "pdps/policies"; @@ -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"); @@ -64,7 +64,7 @@ public class PdpGroupDeleteTest extends End2EndBase { } @Test - public void testDeleteGroup() throws Exception { + void testDeleteGroup() throws Exception { addGroups("deleteGroup.json"); context.addPdp("pdpAA_1", "pdpTypeA"); @@ -95,7 +95,7 @@ public class PdpGroupDeleteTest extends End2EndBase { } @Test - public void testDeletePolicy() throws Exception { + void testDeletePolicy() throws Exception { addGroups("undeployPolicy.json"); PdpStatus status1 = new PdpStatus(); @@ -156,7 +156,7 @@ public class PdpGroupDeleteTest extends End2EndBase { } @Test - public void testDeletePolicyVersion() throws Exception { + void testDeletePolicyVersion() throws Exception { addGroups("undeployPolicyVersion.json"); PdpStatus status1 = new PdpStatus(); 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..5bc8dd09 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; @@ -51,7 +51,7 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1; -public class PdpGroupDeployTest extends End2EndBase { +class PdpGroupDeployTest extends End2EndBase { private static final String DEPLOY_GROUP_ENDPOINT = "pdps/deployments/batch"; private static final String DEPLOY_POLICIES_ENDPOINT = "pdps/policies"; private static final String DEPLOY_SUBGROUP = "pdpTypeA"; @@ -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"); @@ -70,7 +70,7 @@ public class PdpGroupDeployTest extends End2EndBase { } @Test - public void testUpdateGroupPolicies() throws Exception { + void testUpdateGroupPolicies() throws Exception { addGroups("deployGroups.json"); @@ -132,7 +132,7 @@ public class PdpGroupDeployTest extends End2EndBase { } @Test - public void testDeployPolicies() throws Exception { + void testDeployPolicies() throws Exception { addGroups("deployPolicies.json"); PdpStatus status11 = new PdpStatus(); 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..cf466c29 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; @@ -43,7 +43,7 @@ import org.onap.policy.models.pdp.enums.PdpHealthStatus; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -public class PdpGroupQueryTest extends End2EndBase { +class PdpGroupQueryTest extends End2EndBase { private static final String GROUP_ENDPOINT = "pdps"; /** @@ -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"); @@ -63,7 +63,7 @@ public class PdpGroupQueryTest extends End2EndBase { } @Test - public void test() throws Exception { + void test() throws Exception { Invocation.Builder invocationBuilder = sendRequest(GROUP_ENDPOINT); Response rawresp = invocationBuilder.get(); PdpGroups resp = rawresp.readEntity(PdpGroups.class); 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..63abc917 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,22 +22,22 @@ 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; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -public class PdpGroupStateChangeTest extends End2EndBase { +class PdpGroupStateChangeTest extends End2EndBase { private static final String PDP1 = "pdpAA_1"; private static final String PDP2 = "pdpAA_2"; private static final String PDP3 = "pdpAB_1"; @@ -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"); @@ -60,7 +60,7 @@ public class PdpGroupStateChangeTest extends End2EndBase { } @Test - public void testMakePassive() throws Exception { + void testMakePassive() throws Exception { addGroups("stateChangeGroupDeactivate.json"); ToscaConceptIdentifier policy = 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..f036d552 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; @@ -38,7 +39,7 @@ import org.onap.policy.pap.main.rest.PolicyAuditControllerV1; import org.onap.policy.pap.main.service.PolicyAuditService; import org.springframework.beans.factory.annotation.Autowired; -public class PolicyAuditTest extends End2EndBase { +class PolicyAuditTest extends End2EndBase { private static final String TEST_GROUP = "testGroup"; private static final String TEST_PDP_TYPE = "testPdpType"; private static final ToscaConceptIdentifier POLICY_A = new ToscaConceptIdentifier("PolicyA", "1.0.0"); @@ -49,8 +50,8 @@ public class PolicyAuditTest extends End2EndBase { private static final String QUERY_PARAMS_INVALID = "?recordCount=5&startTime=2021-07-25T01:25:15"; private static final String QUERY_PARAMS_CORRECT = "?recordCount=5&startTime=1627219515&endTime=1627478715"; private static final String QUERY_PARAMS_INCORRECT = "?recordCount=5&startTime=1627478715&endTime=1627565115"; - private static int NOT_FOUND_STATUS_CODE = 404; - private static int BAD_REQUEST_STATUS_CODE = 400; + private static final int NOT_FOUND_STATUS_CODE = 404; + private static final int BAD_REQUEST_STATUS_CODE = 400; private static final String BAD_REQUEST_MSG = "NumberFormatException For"; @Autowired @@ -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(); @@ -96,13 +97,13 @@ public class PolicyAuditTest extends End2EndBase { } @Test - public void testGetAllAuditRecords() throws Exception { + void testGetAllAuditRecords() throws Exception { String uri = POLICY_AUDIT_ENDPOINT; sendAndValidateSuccess(uri, 2); } @Test - public void testGetAllAuditRecordsWithParams() throws Exception { + void testGetAllAuditRecordsWithParams() throws Exception { // try with correct dates in query, should result in 2 records String uri = POLICY_AUDIT_ENDPOINT + QUERY_PARAMS_CORRECT; sendAndValidateSuccess(uri, 2); @@ -117,13 +118,13 @@ public class PolicyAuditTest extends End2EndBase { } @Test - public void testGetAuditRecordsByGroup() throws Exception { + void testGetAuditRecordsByGroup() throws Exception { String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP; sendAndValidateSuccess(uri, 2); } @Test - public void testGetAuditRecordsByGroupWithParams() throws Exception { + void testGetAuditRecordsByGroupWithParams() throws Exception { // try with correct dates in query, should result in 2 records String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + QUERY_PARAMS_CORRECT; sendAndValidateSuccess(uri, 2); @@ -138,14 +139,14 @@ public class PolicyAuditTest extends End2EndBase { } @Test - public void testGetAuditRecordsOfPolicyWithGroup() throws Exception { + void testGetAuditRecordsOfPolicyWithGroup() throws Exception { String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion(); sendAndValidateSuccess(uri, 1); } @Test - public void testGetAuditRecordsOfPolicyWithGroupWithParams() throws Exception { + void testGetAuditRecordsOfPolicyWithGroupWithParams() throws Exception { // try with correct dates in query, should result in 1 record String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_CORRECT; @@ -163,13 +164,13 @@ public class PolicyAuditTest extends End2EndBase { } @Test - public void testGetAuditRecordsOfPolicyWithoutGroup() throws Exception { + void testGetAuditRecordsOfPolicyWithoutGroup() throws Exception { String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion(); sendAndValidateSuccess(uri, 1); } @Test - public void testGetAuditRecordsOfPolicyWithoutGroupWithParams() throws Exception { + void testGetAuditRecordsOfPolicyWithoutGroupWithParams() throws Exception { // try with correct dates in query, should result in 1 record String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_CORRECT; 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..513fb62c 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,20 +22,20 @@ 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; -public class PolicyStatusTest extends End2EndBase { +class PolicyStatusTest extends End2EndBase { private static final String POLICY_NAME = "onap.restart.tca"; private static final String POLICY_TYPE_NAME = "onap.policies.monitoring.cdap.tca.hi.lo.app"; private static final String VERSION = "1.0.0"; @@ -43,14 +43,14 @@ 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(); } @Test - public void testQueryAllDeployedPolicies() throws Exception { + void testQueryAllDeployedPolicies() throws Exception { Invocation.Builder invocationBuilder = sendRequest(POLICY_STATUS_ENDPOINT); Response rawresp = invocationBuilder.get(); assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); @@ -61,7 +61,7 @@ public class PolicyStatusTest extends End2EndBase { } @Test - public void testQueryDeployedPolicies() throws Exception { + void testQueryDeployedPolicies() throws Exception { String uri = POLICY_STATUS_ENDPOINT + "/onap.restart.tca"; Invocation.Builder invocationBuilder = sendRequest(uri); @@ -74,7 +74,7 @@ public class PolicyStatusTest extends End2EndBase { } @Test - public void testQueryDeployedPolicy() throws Exception { + void testQueryDeployedPolicy() throws Exception { String uri = POLICY_STATUS_ENDPOINT + "/onap.restart.tca/1.0.0"; Invocation.Builder invocationBuilder = sendRequest(uri); @@ -86,7 +86,7 @@ public class PolicyStatusTest extends End2EndBase { } @Test - public void testGetStatusOfAllDeployedPolicies() throws Exception { + void testGetStatusOfAllDeployedPolicies() throws Exception { Invocation.Builder invocationBuilder = sendRequest(POLICY_DEPLOYMENT_STATUS_ENDPOINT); Response rawresp = invocationBuilder.get(); assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); @@ -97,7 +97,7 @@ public class PolicyStatusTest extends End2EndBase { } @Test - public void testGetStatusOfDeployedPolicies() throws Exception { + void testGetStatusOfDeployedPolicies() throws Exception { String uri = POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/policyStatus/onap.restart.tca"; Invocation.Builder invocationBuilder = sendRequest(uri); @@ -110,7 +110,7 @@ public class PolicyStatusTest extends End2EndBase { } @Test - public void testGetStatusOfDeployedPolicy() throws Exception { + void testGetStatusOfDeployedPolicy() throws Exception { String uri = POLICY_DEPLOYMENT_STATUS_ENDPOINT + "/policyStatus/onap.restart.tca/1.0.0"; Invocation.Builder invocationBuilder = sendRequest(uri); 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..11f2045d 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; @@ -40,7 +40,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; @ActiveProfiles("test") -public class PolicyAuditServiceTest extends CommonPapRestServer { +class PolicyAuditServiceTest extends CommonPapRestServer { private static final String FIELD_IS_NULL = "%s is marked .*ull but is null"; private static final String GROUP_A = "groupA"; @@ -59,20 +59,20 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { * Teardown after tests. */ @Override - @After + @AfterEach public void tearDown() { policyAuditRepository.deleteAll(); } @Test - public void testCreateAuditRecordsSuccess() { + void testCreateAuditRecordsSuccess() { policyAuditService.createAuditRecords(generatePolicyAudits(Instant.now(), GROUP_A, MY_POLICY)); assertThat(policyAuditService.getAuditRecords(NUMBER_RECORDS, null, null)).hasSize(2); } @Test - public void testCreatePolicyAuditFailure() { + void testCreatePolicyAuditFailure() { List<PolicyAudit> audits = List.of( PolicyAudit.builder().pdpType("pdpType").action(AuditAction.DEPLOYMENT).timestamp(Instant.now()).build()); @@ -86,7 +86,7 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { } @Test - public void testGetAuditRecords() { + void testGetAuditRecords() { Instant startDate1 = Instant.now(); policyAuditService.createAuditRecords(generatePolicyAudits(startDate1, GROUP_A, MY_POLICY)); 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..ecdecf36 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; @@ -37,7 +37,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; @ActiveProfiles("test") -public class PolicyStatusServiceTest extends CommonPapRestServer { +class PolicyStatusServiceTest extends CommonPapRestServer { private static final String GROUP_A = "groupA"; private static final String GROUP_B = "groupB"; @@ -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"); @@ -65,7 +65,7 @@ public class PolicyStatusServiceTest extends CommonPapRestServer { } @Test - public void testGetAllPolicyStatus() { + void testGetAllPolicyStatus() { assertThat(policyStatusService.getAllPolicyStatus()).isEmpty(); var statusList = createStatusList(); @@ -75,11 +75,10 @@ public class PolicyStatusServiceTest extends CommonPapRestServer { } @Test - public void testGetAllPolicyStatusPfDaoToscaConceptIdentifierOptVersion() { + void testGetAllPolicyStatusPfDaoToscaConceptIdentifierOptVersion() { - assertThatThrownBy(() -> { - policyStatusService.getAllPolicyStatus(null); - }).hasMessageContaining("policy").hasMessageContaining("null"); + assertThatThrownBy(() -> policyStatusService.getAllPolicyStatus(null)).hasMessageContaining("policy") + .hasMessageContaining("null"); assertThat(policyStatusService.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion("somePdp", null))) .isEmpty(); @@ -95,11 +94,10 @@ public class PolicyStatusServiceTest extends CommonPapRestServer { } @Test - public void testGetGroupPolicyStatus() { + void testGetGroupPolicyStatus() { - assertThatThrownBy(() -> { - policyStatusService.getGroupPolicyStatus(null); - }).hasMessage("pdpGroup is marked non-null but is null"); + assertThatThrownBy(() -> policyStatusService.getGroupPolicyStatus(null)) + .hasMessage("pdpGroup is marked non-null but is null"); assertThat(policyStatusService.getGroupPolicyStatus("PdpGroup0")).isEmpty(); @@ -110,17 +108,18 @@ public class PolicyStatusServiceTest extends CommonPapRestServer { } @Test - public void testCudPolicyStatus() { - assertThatCode(() -> policyStatusService.cudPolicyStatus(null, null, null)).doesNotThrowAnyException(); - - assertThatThrownBy(() -> { - policyStatusService.cudPolicyStatus(List.of(new PdpPolicyStatus()), null, null); - }).isInstanceOf(PfModelRuntimeException.class); - PdpPolicyStatus invalidStatus = statusBuilder.state(PdpPolicyStatus.State.WAITING).deploy(false).pdpGroup(null) - .pdpId("pdp1").policy(MY_POLICY).build(); - assertThatThrownBy(() -> { - policyStatusService.cudPolicyStatus(List.of(invalidStatus), null, null); - }).isInstanceOf(PfModelRuntimeException.class) + void testCudPolicyStatus() { + assertThatCode(() -> policyStatusService.cudPolicyStatus(null, null, null)) + .doesNotThrowAnyException(); + + var listOfNew = List.of(new PdpPolicyStatus()); + assertThatThrownBy(() -> policyStatusService.cudPolicyStatus(listOfNew, null, null)) + .isInstanceOf(PfModelRuntimeException.class); + + var invalidStatusList = List.of(statusBuilder.state(PdpPolicyStatus.State.WAITING).deploy(false).pdpGroup(null) + .pdpId("pdp1").policy(MY_POLICY).build()); + assertThatThrownBy(() -> policyStatusService.cudPolicyStatus(invalidStatusList, null, null)) + .isInstanceOf(PfModelRuntimeException.class) .hasMessageContaining("item \"pdpGroup\" value \"null\" INVALID, is null"); // Test create 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..7b64c47f 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,13 +25,13 @@ 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.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.StandardYamlCoder; @@ -43,8 +43,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; 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 +56,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..f3716c19 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,17 +24,17 @@ 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.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.StandardYamlCoder; @@ -48,8 +48,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; 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 +71,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 +99,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 +111,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 +127,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 +143,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 |