diff options
Diffstat (limited to 'policy-management/src/test/java')
25 files changed, 855 insertions, 846 deletions
diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java index 03301470..93d5ee43 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java @@ -3,6 +3,7 @@ * policy-management * ================================================================================ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,16 +21,16 @@ package org.onap.policy.drools.controller; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.onap.policy.drools.properties.DroolsPropertyConstants.PROPERTY_CONTROLLER_TYPE; import java.util.List; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.drools.controller.internal.NullDroolsController; import org.onap.policy.drools.features.DroolsControllerFeatureApi; import org.onap.policy.drools.properties.DroolsPropertyConstants; @@ -43,7 +44,7 @@ public class DroolsControllerFactoryTest { public static final String TEST_VERSION = "testVersion"; @Test - public void testBuildNullController() { + void testBuildNullController() { Properties droolsProps = new Properties(); DroolsController droolsController = DroolsControllerConstants.getFactory().build(droolsProps, null, null); @@ -53,7 +54,7 @@ public class DroolsControllerFactoryTest { } @Test - public void testGetNullController() { + void testGetNullController() { DroolsController controller = DroolsControllerConstants.getFactory().get(DroolsControllerConstants.NO_GROUP_ID, DroolsControllerConstants.NO_ARTIFACT_ID, DroolsControllerConstants.NO_VERSION); @@ -65,26 +66,26 @@ public class DroolsControllerFactoryTest { } @Test - public void testInventory() { + void testInventory() { List<DroolsController> controllers = DroolsControllerConstants.getFactory().inventory(); assertNotNull(controllers); - for (int i = 0; i < controllers.size(); i++) { - if (!isNullController(controllers.get(i)) && !isActualController(controllers.get(i))) { + for (DroolsController controller : controllers) { + if (!isNullController(controller) && !isActualController(controller)) { fail("drools controller is not a null controller"); } } } @Test - public void testShutdown() { + void testShutdown() { DroolsControllerFactory droolsFactory = new IndexedDroolsControllerFactory(); droolsFactory.shutdown(); assertTrue(droolsFactory.inventory().isEmpty()); } @Test - public void testDestroy() { + void testDestroy() { DroolsControllerFactory droolsFactory = new IndexedDroolsControllerFactory(); droolsFactory.destroy(); assertTrue(droolsFactory.inventory().isEmpty()); @@ -107,7 +108,7 @@ public class DroolsControllerFactoryTest { } @Test - public void testControllerType() { + void testControllerType() { DroolsControllerFactory droolsFactory = new IndexedDroolsControllerFactory(); Properties props = new Properties(); diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java index f91c437a..fdbfab8f 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,14 @@ package org.onap.policy.drools.controller.internal; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.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.Mockito.doThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -41,9 +42,10 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; -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.junit.jupiter.api.extension.ExtendWith; import org.kie.api.KieBase; import org.kie.api.definition.KiePackage; import org.kie.api.definition.rule.Query; @@ -54,7 +56,8 @@ import org.kie.api.runtime.rule.QueryResults; import org.kie.api.runtime.rule.QueryResultsRow; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.core.PolicyContainer; @@ -69,8 +72,8 @@ import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter; -@RunWith(MockitoJUnitRunner.class) -public class MavenDroolsController2Test { +@ExtendWith(MockitoExtension.class) +class MavenDroolsController2Test { private static final int FACT1_OBJECT = 1000; private static final int FACT3_OBJECT = 1001; @@ -186,113 +189,121 @@ public class MavenDroolsController2Test { private MavenDroolsController drools; + AutoCloseable autoCloseable; + /** * Initializes objects, including the drools controller. */ - @Before + @BeforeEach public void setUp() { - when(droolsProviders.getList()).thenReturn(List.of(prov1, prov2)); + autoCloseable = MockitoAnnotations.openMocks(this); + lenient().when(droolsProviders.getList()).thenReturn(List.of(prov1, prov2)); - when(coderMgr.isDecodingSupported(GROUP, ARTIFACT, TOPIC)).thenReturn(true); - when(coderMgr.decode(GROUP, ARTIFACT, TOPIC, EVENT_TEXT)).thenReturn(EVENT); + lenient().when(coderMgr.isDecodingSupported(GROUP, ARTIFACT, TOPIC)).thenReturn(true); + lenient().when(coderMgr.decode(GROUP, ARTIFACT, TOPIC, EVENT_TEXT)).thenReturn(EVENT); - when(kieSess.getFactCount()).thenReturn(FACT_COUNT); - when(kieSess.getFactHandles()).thenReturn(List.of(fact1, fact2, factex, fact3)); - when(kieSess.getFactHandles(any())).thenReturn(List.of(fact1, fact3)); - when(kieSess.getKieBase()).thenReturn(kieBase); - when(kieSess.getQueryResults(QUERY, PARM1, PARM2)).thenReturn(queryResults); + lenient().when(kieSess.getFactCount()).thenReturn(FACT_COUNT); + lenient().when(kieSess.getFactHandles()).thenReturn(List.of(fact1, fact2, factex, fact3)); + lenient().when(kieSess.getFactHandles(any())).thenReturn(List.of(fact1, fact3)); + lenient().when(kieSess.getKieBase()).thenReturn(kieBase); + lenient().when(kieSess.getQueryResults(QUERY, PARM1, PARM2)).thenReturn(queryResults); - when(kieSess.getFactHandle(FACT3_OBJECT)).thenReturn(fact3); + lenient().when(kieSess.getFactHandle(FACT3_OBJECT)).thenReturn(fact3); - when(kieSess.getObject(fact1)).thenReturn(FACT1_OBJECT); - when(kieSess.getObject(fact2)).thenReturn(""); - when(kieSess.getObject(fact3)).thenReturn(FACT3_OBJECT); - when(kieSess.getObject(factex)).thenThrow(RUNTIME_EX); + lenient().when(kieSess.getObject(fact1)).thenReturn(FACT1_OBJECT); + lenient().when(kieSess.getObject(fact2)).thenReturn(""); + lenient().when(kieSess.getObject(fact3)).thenReturn(FACT3_OBJECT); + lenient().when(kieSess.getObject(factex)).thenThrow(RUNTIME_EX); - when(kieBase.getKiePackages()).thenReturn(List.of(pkg1, pkg2)); + lenient().when(kieBase.getKiePackages()).thenReturn(List.of(pkg1, pkg2)); - when(pkg1.getQueries()).thenReturn(List.of(query3)); - when(pkg2.getQueries()).thenReturn(List.of(query2, query1)); + lenient().when(pkg1.getQueries()).thenReturn(List.of(query3)); + lenient().when(pkg2.getQueries()).thenReturn(List.of(query2, query1)); - when(query1.getName()).thenReturn(QUERY); - when(query2.getName()).thenReturn(QUERY2); + lenient().when(query1.getName()).thenReturn(QUERY); + lenient().when(query2.getName()).thenReturn(QUERY2); - when(queryResults.iterator()).thenReturn(List.of(row1, row2).iterator()); + lenient().when(queryResults.iterator()).thenReturn(List.of(row1, row2).iterator()); - when(row1.get(ENTITY)).thenReturn(FACT1_OBJECT); - when(row2.get(ENTITY)).thenReturn(FACT3_OBJECT); + lenient().when(row1.get(ENTITY)).thenReturn(FACT1_OBJECT); + lenient().when(row2.get(ENTITY)).thenReturn(FACT3_OBJECT); - when(row1.getFactHandle(ENTITY)).thenReturn(fact1); - when(row2.getFactHandle(ENTITY)).thenReturn(fact3); + lenient().when(row1.getFactHandle(ENTITY)).thenReturn(fact1); + lenient().when(row2.getFactHandle(ENTITY)).thenReturn(fact3); - when(sess1.getKieSession()).thenReturn(kieSess); - when(sess2.getKieSession()).thenReturn(kieSess2); + lenient().when(sess1.getKieSession()).thenReturn(kieSess); + lenient().when(sess2.getKieSession()).thenReturn(kieSess2); - when(sess1.getName()).thenReturn(SESSION1); - when(sess2.getName()).thenReturn(SESSION2); + lenient().when(sess1.getName()).thenReturn(SESSION1); + lenient().when(sess2.getName()).thenReturn(SESSION2); - when(sess1.getFullName()).thenReturn(FULL_SESSION1); - when(sess2.getFullName()).thenReturn(FULL_SESSION2); + lenient().when(sess1.getFullName()).thenReturn(FULL_SESSION1); + lenient().when(sess2.getFullName()).thenReturn(FULL_SESSION2); - when(container.getClassLoader()).thenReturn(CLASS_LOADER); - when(container.getPolicySessions()).thenReturn(List.of(sess1, sess2)); - when(container.insertAll(EVENT)).thenReturn(true); + lenient().when(container.getClassLoader()).thenReturn(CLASS_LOADER); + lenient().when(container.getPolicySessions()).thenReturn(List.of(sess1, sess2)); + lenient().when(container.insertAll(EVENT)).thenReturn(true); - when(decoder1.getTopic()).thenReturn(TOPIC); - when(decoder2.getTopic()).thenReturn(TOPIC2); + lenient().when(decoder1.getTopic()).thenReturn(TOPIC); + lenient().when(decoder2.getTopic()).thenReturn(TOPIC2); - when(encoder1.getTopic()).thenReturn(TOPIC); - when(encoder2.getTopic()).thenReturn(TOPIC2); + lenient().when(encoder1.getTopic()).thenReturn(TOPIC); + lenient().when(encoder2.getTopic()).thenReturn(TOPIC2); decoders = List.of(decoder1, decoder2); encoders = List.of(encoder1, encoder2); - when(decoder1.getCustomGsonCoder()).thenReturn(gson1); - when(encoder2.getCustomGsonCoder()).thenReturn(gson2); + lenient().when(decoder1.getCustomGsonCoder()).thenReturn(gson1); + lenient().when(encoder2.getCustomGsonCoder()).thenReturn(gson2); - when(filter1a.getCodedClass()).thenReturn(Object.class.getName()); - when(filter1a.getFilter()).thenReturn(jsonFilter1a); + lenient().when(filter1a.getCodedClass()).thenReturn(Object.class.getName()); + lenient().when(filter1a.getFilter()).thenReturn(jsonFilter1a); - when(filter1b.getCodedClass()).thenReturn(String.class.getName()); - when(filter1b.getFilter()).thenReturn(jsonFilter1b); + lenient().when(filter1b.getCodedClass()).thenReturn(String.class.getName()); + lenient().when(filter1b.getFilter()).thenReturn(jsonFilter1b); - when(filter2.getCodedClass()).thenReturn(Integer.class.getName()); - when(filter2.getFilter()).thenReturn(jsonFilter2); + lenient().when(filter2.getCodedClass()).thenReturn(Integer.class.getName()); + lenient().when(filter2.getFilter()).thenReturn(jsonFilter2); - when(decoder1.getCoderFilters()).thenReturn(List.of(filter1a, filter1b)); - when(decoder2.getCoderFilters()).thenReturn(Collections.emptyList()); + lenient().when(decoder1.getCoderFilters()).thenReturn(List.of(filter1a, filter1b)); + lenient().when(decoder2.getCoderFilters()).thenReturn(Collections.emptyList()); - when(encoder1.getCoderFilters()).thenReturn(Collections.emptyList()); - when(encoder2.getCoderFilters()).thenReturn(List.of(filter2)); + lenient().when(encoder1.getCoderFilters()).thenReturn(Collections.emptyList()); + lenient().when(encoder2.getCoderFilters()).thenReturn(List.of(filter2)); - when(sink.getTopic()).thenReturn(TOPIC); - when(sink.send(EVENT_TEXT)).thenReturn(true); + lenient().when(sink.getTopic()).thenReturn(TOPIC); + lenient().when(sink.send(EVENT_TEXT)).thenReturn(true); drools = new MyDrools(GROUP, ARTIFACT, VERSION, null, null); - when(coderMgr.encode(TOPIC, EVENT, drools)).thenReturn(EVENT_TEXT); + lenient().when(coderMgr.encode(TOPIC, EVENT, drools)).thenReturn(EVENT_TEXT); + } + + @AfterEach + void closeMocks() throws Exception { + autoCloseable.close(); } @Test - public void testMavenDroolsController_InvalidArgs() { + void testMavenDroolsController_InvalidArgs() { assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools(null, ARTIFACT, VERSION, null, null)) - .withMessageContaining("group"); + .withMessageContaining("group"); assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools("", ARTIFACT, VERSION, null, null)) - .withMessageContaining("group"); + .withMessageContaining("group"); assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools(GROUP, null, VERSION, null, null)) - .withMessageContaining("artifact"); + .withMessageContaining("artifact"); assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools(GROUP, "", VERSION, null, null)) - .withMessageContaining("artifact"); + .withMessageContaining("artifact"); assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, null, null, null)) - .withMessageContaining("version"); + .withMessageContaining("version"); assertThatIllegalArgumentException().isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, "", null, null)) - .withMessageContaining("version"); + .withMessageContaining("version"); } @Test - public void testUpdateToVersion() { + void testUpdateToVersion() { // add coders drools.updateToVersion(GROUP, ARTIFACT, VERSION2, decoders, encoders); @@ -320,7 +331,7 @@ public class MavenDroolsController2Test { } @Test - public void testUpdateToVersion_Unchanged() { + void testUpdateToVersion_Unchanged() { drools.updateToVersion(GROUP, ARTIFACT, VERSION, decoders, encoders); verify(coderMgr, never()).addDecoder(any()); @@ -328,53 +339,53 @@ public class MavenDroolsController2Test { } @Test - public void testUpdateToVersion_InvalidArgs() { + void testUpdateToVersion_InvalidArgs() { assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion(null, ARTIFACT, VERSION, null, null)) - .withMessageContaining("group"); + .isThrownBy(() -> drools.updateToVersion(null, ARTIFACT, VERSION, null, null)) + .withMessageContaining("group"); assertThatIllegalArgumentException().isThrownBy(() -> drools.updateToVersion("", ARTIFACT, VERSION, null, null)) - .withMessageContaining("group"); + .withMessageContaining("group"); assertThatIllegalArgumentException().isThrownBy(() -> drools.updateToVersion(GROUP, null, VERSION, null, null)) - .withMessageContaining("artifact"); + .withMessageContaining("artifact"); assertThatIllegalArgumentException().isThrownBy(() -> drools.updateToVersion(GROUP, "", VERSION, null, null)) - .withMessageContaining("artifact"); + .withMessageContaining("artifact"); assertThatIllegalArgumentException().isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT, null, null, null)) - .withMessageContaining("version"); + .withMessageContaining("version"); assertThatIllegalArgumentException().isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT, "", null, null)) - .withMessageContaining("version"); + .withMessageContaining("version"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion("no-group-id", ARTIFACT, VERSION, null, null)) - .withMessageContaining("BRAINLESS"); + .isThrownBy(() -> drools.updateToVersion("no-group-id", ARTIFACT, VERSION, null, null)) + .withMessageContaining("BRAINLESS"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion(GROUP, "no-artifact-id", VERSION, null, null)) - .withMessageContaining("BRAINLESS"); + .isThrownBy(() -> drools.updateToVersion(GROUP, "no-artifact-id", VERSION, null, null)) + .withMessageContaining("BRAINLESS"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT, "no-version", null, null)) - .withMessageContaining("BRAINLESS"); + .isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT, "no-version", null, null)) + .withMessageContaining("BRAINLESS"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion(GROUP2, ARTIFACT, VERSION, null, null)) - .withMessageContaining("coordinates must be identical"); + .isThrownBy(() -> drools.updateToVersion(GROUP2, ARTIFACT, VERSION, null, null)) + .withMessageContaining("coordinates must be identical"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT2, VERSION, null, null)) - .withMessageContaining("coordinates must be identical"); + .isThrownBy(() -> drools.updateToVersion(GROUP, ARTIFACT2, VERSION, null, null)) + .withMessageContaining("coordinates must be identical"); } @Test - public void testInitCoders_NullCoders() { + void testInitCoders_NullCoders() { // already constructed with null coders verify(coderMgr, never()).addDecoder(any()); verify(coderMgr, never()).addEncoder(any()); } @Test - public void testInitCoders_NullOrEmptyFilters() { + void testInitCoders_NullOrEmptyFilters() { when(decoder1.getCoderFilters()).thenReturn(Collections.emptyList()); when(decoder2.getCoderFilters()).thenReturn(null); @@ -388,7 +399,7 @@ public class MavenDroolsController2Test { } @Test - public void testInitCoders_GsonClass() { + void testInitCoders_GsonClass() { when(gson1.getClassContainer()).thenReturn(""); when(gson2.getClassContainer()).thenReturn(Long.class.getName()); @@ -400,25 +411,25 @@ public class MavenDroolsController2Test { } @Test - public void testInitCoders_InvalidGsonClass() { + void testInitCoders_InvalidGsonClass() { when(gson1.getClassContainer()).thenReturn(UNKNOWN_CLASS); assertThatIllegalArgumentException() - .isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders)) - .withMessageContaining("cannot be retrieved"); + .isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders)) + .withMessageContaining("cannot be retrieved"); } @Test - public void testInitCoders_InvalidFilterClass() { + void testInitCoders_InvalidFilterClass() { when(filter2.getCodedClass()).thenReturn(UNKNOWN_CLASS); assertThatIllegalArgumentException() - .isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders)) - .withMessageContaining("cannot be retrieved"); + .isThrownBy(() -> new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders)) + .withMessageContaining("cannot be retrieved"); } @Test - public void testInitCoders_Filters() { + void testInitCoders_Filters() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); @@ -458,7 +469,7 @@ public class MavenDroolsController2Test { } @Test - public void testOwnsCoder() { + void testOwnsCoder() { int hc = CLASS_LOADER_HASHCODE; // wrong hash code @@ -478,7 +489,7 @@ public class MavenDroolsController2Test { } @Test - public void testStart_testStop_testIsAlive() { + void testStart_testStop_testIsAlive() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); when(container.start()).thenReturn(true); @@ -525,7 +536,7 @@ public class MavenDroolsController2Test { } @Test - public void testShutdown() { + void testShutdown() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); // start it @@ -546,7 +557,7 @@ public class MavenDroolsController2Test { } @Test - public void testShutdown_Ex() { + void testShutdown_Ex() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); // start it @@ -564,7 +575,7 @@ public class MavenDroolsController2Test { } @Test - public void testHalt() { + void testHalt() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); // start it @@ -584,7 +595,7 @@ public class MavenDroolsController2Test { } @Test - public void testHalt_Ex() { + void testHalt_Ex() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders); // start it @@ -601,7 +612,7 @@ public class MavenDroolsController2Test { } @Test - public void testRemoveCoders_Ex() { + void testRemoveCoders_Ex() { drools = new MyDrools(GROUP, ARTIFACT, VERSION, decoders, encoders) { @Override protected void removeDecoders() { @@ -618,7 +629,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferStringString() { + void testOfferStringString() { drools.start(); assertTrue(drools.offer(TOPIC, EVENT_TEXT)); @@ -626,7 +637,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferStringString_NoDecode() { + void testOfferStringString_NoDecode() { when(coderMgr.isDecodingSupported(GROUP, ARTIFACT, TOPIC)).thenReturn(false); drools.start(); @@ -636,9 +647,9 @@ public class MavenDroolsController2Test { } @Test - public void testOfferStringString_DecodeUnsupported() { + void testOfferStringString_DecodeUnsupported() { when(coderMgr.decode(GROUP, ARTIFACT, TOPIC, EVENT_TEXT)) - .thenThrow(new UnsupportedOperationException(EXPECTED_EXCEPTION)); + .thenThrow(new UnsupportedOperationException(EXPECTED_EXCEPTION)); drools.start(); assertTrue(drools.offer(TOPIC, EVENT_TEXT)); @@ -647,7 +658,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferStringString_DecodeEx() { + void testOfferStringString_DecodeEx() { when(coderMgr.decode(GROUP, ARTIFACT, TOPIC, EVENT_TEXT)).thenThrow(RUNTIME_EX); drools.start(); @@ -657,7 +668,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferStringString_Ignored() { + void testOfferStringString_Ignored() { drools.start(); drools.lock(); @@ -677,7 +688,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT() { + void testOfferT() { drools.start(); assertTrue(drools.offer(EVENT)); assertEquals(1, drools.getRecentSourceEvents().length); @@ -692,7 +703,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT_Ex() { + void testOfferT_Ex() { when(prov1.beforeInsert(drools, EVENT)).thenThrow(RUNTIME_EX); when(prov1.afterInsert(drools, EVENT, true)).thenThrow(RUNTIME_EX); @@ -709,7 +720,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT_NotInserted() { + void testOfferT_NotInserted() { when(container.insertAll(EVENT)).thenReturn(false); drools.start(); @@ -726,7 +737,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT_BeforeInsertIntercept() { + void testOfferT_BeforeInsertIntercept() { drools.start(); when(prov1.beforeInsert(drools, EVENT)).thenReturn(true); @@ -744,7 +755,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT_AfterInsertIntercept() { + void testOfferT_AfterInsertIntercept() { drools.start(); when(prov1.afterInsert(drools, EVENT, true)).thenReturn(true); @@ -764,7 +775,7 @@ public class MavenDroolsController2Test { } @Test - public void testOfferT_Ignored() { + void testOfferT_Ignored() { drools.start(); drools.lock(); @@ -784,7 +795,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeliver() { + void testDeliver() { drools.start(); assertTrue(drools.deliver(sink, EVENT)); assertEquals(1, drools.getRecentSinkEvents().length); @@ -800,14 +811,14 @@ public class MavenDroolsController2Test { } @Test - public void testDeliver_InvalidArgs() { + void testDeliver_InvalidArgs() { drools.start(); assertThatIllegalArgumentException().isThrownBy(() -> drools.deliver(null, EVENT)) - .withMessageContaining("sink"); + .withMessageContaining("sink"); assertThatIllegalArgumentException().isThrownBy(() -> drools.deliver(sink, null)) - .withMessageContaining("event"); + .withMessageContaining("event"); drools.lock(); assertThatIllegalStateException().isThrownBy(() -> drools.deliver(sink, EVENT)).withMessageContaining("locked"); @@ -815,14 +826,14 @@ public class MavenDroolsController2Test { drools.stop(); assertThatIllegalStateException().isThrownBy(() -> drools.deliver(sink, EVENT)) - .withMessageContaining("stopped"); + .withMessageContaining("stopped"); drools.start(); assertEquals(0, drools.getRecentSinkEvents().length); } @Test - public void testDeliver_BeforeIntercept() { + void testDeliver_BeforeIntercept() { when(prov1.beforeDeliver(drools, sink, EVENT)).thenReturn(true); drools.start(); @@ -839,7 +850,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeliver_AfterIntercept() { + void testDeliver_AfterIntercept() { when(prov1.afterDeliver(drools, sink, EVENT, EVENT_TEXT, true)).thenReturn(true); drools.start(); @@ -859,7 +870,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeliver_InterceptEx() { + void testDeliver_InterceptEx() { when(prov1.beforeDeliver(drools, sink, EVENT)).thenThrow(RUNTIME_EX); when(prov1.afterDeliver(drools, sink, EVENT, EVENT_TEXT, true)).thenThrow(RUNTIME_EX); @@ -874,7 +885,7 @@ public class MavenDroolsController2Test { } @Test - public void testGetXxx() { + void testGetXxx() { assertEquals(VERSION, drools.getVersion()); assertEquals(ARTIFACT, drools.getArtifactId()); assertEquals(GROUP, drools.getGroupId()); @@ -895,7 +906,7 @@ public class MavenDroolsController2Test { } @Test - public void testLock_testUnlock_testIsLocked() { + void testLock_testUnlock_testIsLocked() { assertFalse(drools.isLocked()); assertTrue(drools.lock()); @@ -913,7 +924,7 @@ public class MavenDroolsController2Test { } @Test - public void testGetSessionNames_testGetCanonicalSessionNames() { + void testGetSessionNames_testGetCanonicalSessionNames() { assertEquals("[session-A, session-B]", drools.getSessionNames(true).toString()); assertEquals("[full-A, full-B]", drools.getSessionNames(false).toString()); @@ -927,7 +938,7 @@ public class MavenDroolsController2Test { } @Test - public void testGetBaseDomainNames() { + void testGetBaseDomainNames() { KieContainer kiecont = mock(KieContainer.class); when(kiecont.getKieBaseNames()).thenReturn(List.of("kieA", "kieB")); when(container.getKieContainer()).thenReturn(kiecont); @@ -936,12 +947,12 @@ public class MavenDroolsController2Test { } @Test - public void testGetSession() { + void testGetSession() { assertThatIllegalArgumentException().isThrownBy(() -> drools.getSession(null)) - .withMessageContaining("must be provided"); + .withMessageContaining("must be provided"); assertThatIllegalArgumentException().isThrownBy(() -> drools.getSession("")) - .withMessageContaining("must be provided"); + .withMessageContaining("must be provided"); assertSame(sess1, drools.getSession(SESSION1)); assertSame(sess1, drools.getSession(FULL_SESSION1)); @@ -949,35 +960,35 @@ public class MavenDroolsController2Test { assertSame(sess2, drools.getSession(SESSION2)); assertThatIllegalArgumentException().isThrownBy(() -> drools.getSession("unknown session")) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); } @Test - public void testFactClassNames() { + void testFactClassNames() { // copy to a sorted map so the order remains unchanged Map<String, Integer> map = new TreeMap<>(drools.factClassNames(SESSION1)); assertEquals("{java.lang.Integer=2, java.lang.String=1}", map.toString()); assertThatIllegalArgumentException().isThrownBy(() -> drools.factClassNames(null)) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.factClassNames("")) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); } @Test - public void testFactCount() { + void testFactCount() { assertEquals(FACT_COUNT, drools.factCount(SESSION1)); assertThatIllegalArgumentException().isThrownBy(() -> drools.factCount(null)) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.factCount("")) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); } @Test - public void testFactsStringStringBoolean() { + void testFactsStringStringBoolean() { assertEquals("[1000, 1001]", drools.facts(SESSION1, Integer.class.getName(), false).toString()); verify(kieSess, never()).delete(fact1); verify(kieSess, never()).delete(fact2); @@ -992,23 +1003,23 @@ public class MavenDroolsController2Test { verify(kieSess, never()).delete(factex); assertThatIllegalArgumentException().isThrownBy(() -> drools.facts(null, Integer.class.getName(), false)) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.facts("", Integer.class.getName(), false)) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.facts(SESSION1, null, false)) - .withMessageContaining("Invalid Class Name"); + .withMessageContaining("Invalid Class Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.facts(SESSION1, "", false)) - .withMessageContaining("Invalid Class Name"); + .withMessageContaining("Invalid Class Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.facts(SESSION1, UNKNOWN_CLASS, false)) - .withMessageContaining("classloader"); + .withMessageContaining("classloader"); } @Test - public void testFactsStringStringBoolean_DeleteEx() { + void testFactsStringStringBoolean_DeleteEx() { doThrow(RUNTIME_EX).when(kieSess).delete(fact1); assertEquals("[1000, 1001]", drools.facts(SESSION1, Integer.class.getName(), true).toString()); @@ -1018,47 +1029,47 @@ public class MavenDroolsController2Test { } @Test - public void testFactsStringClassOfT() { + void testFactsStringClassOfT() { assertEquals("[1000, 1001]", drools.facts(SESSION1, Integer.class).toString()); } @Test - public void testFactQuery() { + void testFactQuery() { assertEquals("[1000, 1001]", drools.factQuery(SESSION1, QUERY, ENTITY, false, PARM1, PARM2).toString()); verify(kieSess, never()).delete(fact1); verify(kieSess, never()).delete(fact3); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.factQuery(null, QUERY, ENTITY, false, PARM1, PARM2)) - .withMessageContaining("Invalid Session Name"); + .isThrownBy(() -> drools.factQuery(null, QUERY, ENTITY, false, PARM1, PARM2)) + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException().isThrownBy(() -> drools.factQuery("", QUERY, ENTITY, false, PARM1, PARM2)) - .withMessageContaining("Invalid Session Name"); + .withMessageContaining("Invalid Session Name"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.factQuery(SESSION1, null, ENTITY, false, PARM1, PARM2)) - .withMessageContaining("Invalid Query Name"); + .isThrownBy(() -> drools.factQuery(SESSION1, null, ENTITY, false, PARM1, PARM2)) + .withMessageContaining("Invalid Query Name"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.factQuery(SESSION1, "", ENTITY, false, PARM1, PARM2)) - .withMessageContaining("Invalid Query Name"); + .isThrownBy(() -> drools.factQuery(SESSION1, "", ENTITY, false, PARM1, PARM2)) + .withMessageContaining("Invalid Query Name"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.factQuery(SESSION1, QUERY, null, false, PARM1, PARM2)) - .withMessageContaining("Invalid Queried Entity"); + .isThrownBy(() -> drools.factQuery(SESSION1, QUERY, null, false, PARM1, PARM2)) + .withMessageContaining("Invalid Queried Entity"); assertThatIllegalArgumentException() - .isThrownBy(() -> drools.factQuery(SESSION1, QUERY, "", false, PARM1, PARM2)) - .withMessageContaining("Invalid Queried Entity"); + .isThrownBy(() -> drools.factQuery(SESSION1, QUERY, "", false, PARM1, PARM2)) + .withMessageContaining("Invalid Queried Entity"); assertThatIllegalArgumentException().isThrownBy( - () -> drools.factQuery(SESSION1, QUERY + "-unknown-query", ENTITY, false, PARM1, PARM2)) + () -> drools.factQuery(SESSION1, QUERY + "-unknown-query", ENTITY, false, PARM1, PARM2)) .withMessageContaining("Invalid Query Name"); } @Test - public void testFactQuery_Delete() { + void testFactQuery_Delete() { doThrow(RUNTIME_EX).when(kieSess).delete(fact1); assertEquals("[1000, 1001]", drools.factQuery(SESSION1, QUERY, ENTITY, true, PARM1, PARM2).toString()); @@ -1068,7 +1079,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeleteStringT() { + void testDeleteStringT() { assertTrue(drools.delete(SESSION1, FACT3_OBJECT)); verify(kieSess, never()).delete(fact1); @@ -1087,14 +1098,14 @@ public class MavenDroolsController2Test { } @Test - public void testDeleteT() { + void testDeleteT() { assertTrue(drools.delete(FACT3_OBJECT)); verify(kieSess).delete(fact3); } @Test - public void testDeleteStringClassOfT() { + void testDeleteStringClassOfT() { assertTrue(drools.delete(SESSION1, Integer.class)); verify(kieSess).delete(fact1); @@ -1102,7 +1113,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeleteStringClassOfT_Ex() { + void testDeleteStringClassOfT_Ex() { doThrow(RUNTIME_EX).when(kieSess).delete(fact1); assertFalse(drools.delete(SESSION1, Integer.class)); @@ -1112,7 +1123,7 @@ public class MavenDroolsController2Test { } @Test - public void testDeleteClassOfT() { + void testDeleteClassOfT() { assertTrue(drools.delete(Integer.class)); verify(kieSess).delete(fact1); @@ -1120,17 +1131,17 @@ public class MavenDroolsController2Test { } @Test - public void testFetchModelClass() { + void testFetchModelClass() { assertSame(Long.class, drools.fetchModelClass(Long.class.getName())); } @Test - public void testIsBrained() { + void testIsBrained() { assertTrue(drools.isBrained()); } @Test - public void testToString() { + void testToString() { assertNotNull(drools.toString()); } @@ -1155,9 +1166,9 @@ public class MavenDroolsController2Test { @Override protected PolicyContainer makePolicyContainer(String groupId, String artifactId, String version) { - when(container.getGroupId()).thenReturn(groupId); - when(container.getArtifactId()).thenReturn(artifactId); - when(container.getVersion()).thenReturn(version); + lenient().when(container.getGroupId()).thenReturn(groupId); + lenient().when(container.getArtifactId()).thenReturn(artifactId); + lenient().when(container.getVersion()).thenReturn(version); return container; } diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java index a2f41bc6..fbaf8433 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +21,17 @@ package org.onap.policy.drools.controller.internal; +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.io.IOException; import java.nio.file.Paths; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.onap.policy.common.utils.gson.GsonTestUtils; import org.onap.policy.drools.controller.DroolsController; @@ -49,7 +53,7 @@ public class MavenDroolsControllerTest { * * @throws IOException throws an IO exception */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws IOException { releaseId = KieUtils.installArtifact(Paths.get(JUNIT_ECHO_KMODULE_PATH).toFile(), @@ -58,7 +62,7 @@ public class MavenDroolsControllerTest { Paths.get(JUNIT_ECHO_KMODULE_DRL_PATH).toFile()); } - @Before + @BeforeEach public void setUp() { running = new CountDownLatch(1); } @@ -68,58 +72,58 @@ public class MavenDroolsControllerTest { } @Test - public void stop() throws InterruptedException { + void stop() throws InterruptedException { createDroolsController(10000L).stop(); } @Test - public void shutdown() throws InterruptedException { + void shutdown() throws InterruptedException { createDroolsController(10000L).shutdown(); } @Test - public void testLock() throws InterruptedException { + void testLock() throws InterruptedException { DroolsController controller = createDroolsController(30000L); controller.lock(); - Assert.assertTrue(controller.isLocked()); + assertTrue(controller.isLocked()); controller.unlock(); - Assert.assertFalse(controller.isLocked()); + assertFalse(controller.isLocked()); controller.halt(); - Assert.assertFalse(controller.isAlive()); + assertFalse(controller.isAlive()); new GsonTestUtils().compareGson(controller, MavenDroolsControllerTest.class); } @Test - public void testFact() throws InterruptedException { + void testFact() throws InterruptedException { DroolsController controller = createDroolsController(30000L); Integer one = 1; Integer two = 2; - Assert.assertTrue(controller.offer(one)); - Assert.assertTrue(controller.exists(one)); - Assert.assertFalse(controller.exists(two)); + assertTrue(controller.offer(one)); + assertTrue(controller.exists(one)); + assertFalse(controller.exists(two)); - Assert.assertTrue(controller.offer(two)); - Assert.assertTrue(controller.exists(one)); - Assert.assertTrue(controller.exists(two)); + assertTrue(controller.offer(two)); + assertTrue(controller.exists(one)); + assertTrue(controller.exists(two)); Integer three = 3; - Assert.assertFalse(controller.delete(three)); - Assert.assertTrue(controller.exists(one)); - Assert.assertTrue(controller.exists(two)); + assertFalse(controller.delete(three)); + assertTrue(controller.exists(one)); + assertTrue(controller.exists(two)); - Assert.assertTrue(controller.delete(two)); - Assert.assertTrue(controller.exists(one)); - Assert.assertFalse(controller.exists(two)); + assertTrue(controller.delete(two)); + assertTrue(controller.exists(one)); + assertFalse(controller.exists(two)); - Assert.assertTrue(controller.delete(one)); - Assert.assertFalse(controller.exists(one)); - Assert.assertFalse(controller.exists(two)); + assertTrue(controller.delete(one)); + assertFalse(controller.exists(one)); + assertFalse(controller.exists(two)); } private DroolsController createDroolsController(long courtesyStartTimeMs) throws InterruptedException { @@ -130,31 +134,31 @@ public class MavenDroolsControllerTest { DroolsController controller = new MavenDroolsController(releaseId.getGroupId(), releaseId.getArtifactId(), releaseId.getVersion(), null, null); - Assert.assertFalse(controller.isAlive()); - Assert.assertTrue(controller.isBrained()); + assertFalse(controller.isAlive()); + assertTrue(controller.isBrained()); controller.start(); - Assert.assertTrue(controller.isAlive()); - Assert.assertTrue(controller.isBrained()); + assertTrue(controller.isAlive()); + assertTrue(controller.isBrained()); - Assert.assertEquals(releaseId.getGroupId(), controller.getGroupId()); - Assert.assertEquals(releaseId.getArtifactId(), controller.getArtifactId()); - Assert.assertEquals(releaseId.getVersion(), controller.getVersion()); + assertEquals(releaseId.getGroupId(), controller.getGroupId()); + assertEquals(releaseId.getArtifactId(), controller.getArtifactId()); + assertEquals(releaseId.getVersion(), controller.getVersion()); - Assert.assertEquals(releaseId.getGroupId(), controller.getContainer().getGroupId()); - Assert.assertEquals(releaseId.getArtifactId(), controller.getContainer().getArtifactId()); - Assert.assertEquals(releaseId.getVersion(), controller.getContainer().getVersion()); + assertEquals(releaseId.getGroupId(), controller.getContainer().getGroupId()); + assertEquals(releaseId.getArtifactId(), controller.getContainer().getArtifactId()); + assertEquals(releaseId.getVersion(), controller.getContainer().getVersion()); /* allow full initialization from local maven repository */ - Assert.assertTrue(running.await(courtesyStartTimeMs, TimeUnit.MILLISECONDS)); + assertTrue(running.await(courtesyStartTimeMs, TimeUnit.MILLISECONDS)); - Assert.assertEquals(1, controller.getSessionNames().size()); - Assert.assertEquals(JUNIT_ECHO_KSESSION, controller.getSessionNames().get(0)); - Assert.assertEquals(1, controller.getCanonicalSessionNames().size()); - Assert.assertTrue(controller.getCanonicalSessionNames().get(0).contains(JUNIT_ECHO_KSESSION)); + assertEquals(1, controller.getSessionNames().size()); + assertEquals(JUNIT_ECHO_KSESSION, controller.getSessionNames().get(0)); + assertEquals(1, controller.getCanonicalSessionNames().size()); + assertTrue(controller.getCanonicalSessionNames().get(0).contains(JUNIT_ECHO_KSESSION)); - Assert.assertEquals(JUNIT_ECHO_KBASE, String.join(",", controller.getBaseDomainNames())); + assertEquals(JUNIT_ECHO_KBASE, String.join(",", controller.getBaseDomainNames())); return controller; } diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerUpgradesTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerUpgradesTest.java index b71403e7..38b38a8c 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerUpgradesTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerUpgradesTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +21,12 @@ package org.onap.policy.drools.controller.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; @@ -33,10 +35,10 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; @@ -93,15 +95,16 @@ public class MavenDroolsControllerUpgradesTest { /** * Test Class Initialization. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws IOException { + Path path = Paths.get(DROOLS_RESOURCES_DIR + "rules1" + DRL_EXT); rulesDescriptor1 = install("rules1", - Stream.of(Paths.get(DROOLS_RESOURCES_DIR + "rules1" + DRL_EXT).toFile()).collect(Collectors.toList())); + Stream.of(path.toFile()).collect(Collectors.toList())); rulesDescriptor2 = install("rules2", - Stream.of(Paths.get(DROOLS_RESOURCES_DIR + "rules1" + DRL_EXT).toFile(), + Stream.of(path.toFile(), Paths.get(DROOLS_RESOURCES_DIR + "rules2" + DRL_EXT).toFile()) .collect(Collectors.toList())); @@ -112,7 +115,7 @@ public class MavenDroolsControllerUpgradesTest { /** * Creates a controller before each test. */ - @Before + @BeforeEach public void beforeTest() { controller = new MavenDroolsController( @@ -123,7 +126,7 @@ public class MavenDroolsControllerUpgradesTest { /** * Shuts down the controller after each test. */ - @After + @AfterEach public void afterTest() { if (controller != null) { controller.halt(); @@ -134,13 +137,13 @@ public class MavenDroolsControllerUpgradesTest { * Upgrades test. */ @Test - public void upgrades() throws InterruptedException { + void upgrades() throws InterruptedException { assertTrue(controller.start()); logKieEvents(); assertTrue(running1a.await(30, TimeUnit.SECONDS)); summary(); - assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12"), 1); + assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12")); controller.updateToVersion( rulesDescriptor2.getGroupId(), @@ -152,7 +155,7 @@ public class MavenDroolsControllerUpgradesTest { assertTrue(running2b.await(30, TimeUnit.SECONDS)); assertTrue(running1b.await(30, TimeUnit.SECONDS)); summary(); - assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12", "SETUP.2", "VERSION.2"), 1); + assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12", "SETUP.2", "VERSION.2")); controller.updateToVersion( rulesDescriptor1.getGroupId(), @@ -161,7 +164,7 @@ public class MavenDroolsControllerUpgradesTest { null, null); summary(); - assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12"), 1); + assertKie(Arrays.asList("run-drools-runnable", "SETUP.1", "VERSION.12")); } private void summary() { @@ -176,11 +179,11 @@ public class MavenDroolsControllerUpgradesTest { logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } - private void assertKie(List<String> expectedRuleNames, long expectedFactCount) { + private void assertKie(List<String> expectedRuleNames) { assertEquals(Collections.singletonList("kbRules"), KieUtils.getBases(controller.getContainer().getKieContainer())); assertEquals(expectedRuleNames, KieUtils.getRuleNames(controller.getContainer().getKieContainer())); - assertEquals(expectedFactCount, controller.factCount(controller.getSessionNames().get(0))); + assertEquals(1, controller.factCount(controller.getSessionNames().get(0))); } private void logKieEvents() { diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java index 010056bb..f61412d9 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,147 +22,158 @@ package org.onap.policy.drools.controller.internal; import static org.assertj.core.api.Assertions.assertThatCode; - -import org.junit.Assert; -import org.junit.Test; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.gson.GsonTestUtils; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.controller.DroolsControllerConstants; -public class NullDroolsControllerTest { +class NullDroolsControllerTest { @Test - public void testStart() { + void testStart() { DroolsController controller = new NullDroolsController(); controller.start(); - Assert.assertFalse(controller.isAlive()); + assertFalse(controller.isAlive()); controller.stop(); - Assert.assertFalse(controller.isAlive()); + assertFalse(controller.isAlive()); controller.shutdown(); - Assert.assertFalse(controller.isAlive()); + assertFalse(controller.isAlive()); controller.halt(); - Assert.assertFalse(controller.isAlive()); + assertFalse(controller.isAlive()); } @Test - public void testSerialize() { + void testSerialize() { assertThatCode(() -> new GsonTestUtils().compareGson(new NullDroolsController(), NullDroolsControllerTest.class)).doesNotThrowAnyException(); } @Test - public void testLock() { + void testLock() { DroolsController controller = new NullDroolsController(); controller.lock(); - Assert.assertFalse(controller.isLocked()); + assertFalse(controller.isLocked()); controller.unlock(); - Assert.assertFalse(controller.isLocked()); + assertFalse(controller.isLocked()); } @Test - public void getGroupId() { - Assert.assertEquals(DroolsControllerConstants.NO_GROUP_ID, new NullDroolsController().getGroupId()); + void getGroupId() { + assertEquals(DroolsControllerConstants.NO_GROUP_ID, new NullDroolsController().getGroupId()); } @Test - public void getArtifactId() { - Assert.assertEquals(DroolsControllerConstants.NO_ARTIFACT_ID, new NullDroolsController().getArtifactId()); + void getArtifactId() { + assertEquals(DroolsControllerConstants.NO_ARTIFACT_ID, new NullDroolsController().getArtifactId()); } @Test - public void getVersion() { - Assert.assertEquals(DroolsControllerConstants.NO_VERSION, new NullDroolsController().getVersion()); + void getVersion() { + assertEquals(DroolsControllerConstants.NO_VERSION, new NullDroolsController().getVersion()); } @Test - public void getSessionNames() { - Assert.assertTrue(new NullDroolsController().getSessionNames().isEmpty()); + void getSessionNames() { + assertTrue(new NullDroolsController().getSessionNames().isEmpty()); } @Test - public void getCanonicalSessionNames() { - Assert.assertTrue(new NullDroolsController().getCanonicalSessionNames().isEmpty()); + void getCanonicalSessionNames() { + assertTrue(new NullDroolsController().getCanonicalSessionNames().isEmpty()); } @Test - public void offer() { - Assert.assertFalse(new NullDroolsController().offer(null, null)); + void offer() { + assertFalse(new NullDroolsController().offer(null, null)); } - @Test(expected = IllegalStateException.class) - public void deliver() { - new NullDroolsController().deliver(null, null); + @Test + void deliver() { + var controller = new NullDroolsController(); + assertThrows(IllegalStateException.class, () -> controller.deliver(null, null)); } @Test - public void getRecentSourceEvents() { - Assert.assertEquals(0, new NullDroolsController().getRecentSourceEvents().length); + void getRecentSourceEvents() { + assertEquals(0, new NullDroolsController().getRecentSourceEvents().length); } @Test - public void getRecentSinkEvents() { - Assert.assertEquals(0, new NullDroolsController().getRecentSinkEvents().length); + void getRecentSinkEvents() { + assertEquals(0, new NullDroolsController().getRecentSinkEvents().length); } @Test - public void getContainer() { - Assert.assertNull(new NullDroolsController().getContainer()); + void getContainer() { + assertNull(new NullDroolsController().getContainer()); } @Test - public void getDomains() { - Assert.assertTrue(new NullDroolsController().getBaseDomainNames().isEmpty()); + void getDomains() { + assertTrue(new NullDroolsController().getBaseDomainNames().isEmpty()); } - @Test(expected = IllegalStateException.class) - public void ownsCoder() { - new NullDroolsController().ownsCoder(null, 0); + @Test + void ownsCoder() { + var controller = new NullDroolsController(); + assertThrows(IllegalStateException.class, () -> controller.ownsCoder(null, 0)); } - @Test(expected = IllegalArgumentException.class) - public void fetchModelClass() { - new NullDroolsController().fetchModelClass(this.getClass().getName()); + @Test + void fetchModelClass() { + var controller = new NullDroolsController(); + var className = this.getClass().getName(); + assertThrows(IllegalArgumentException.class, () -> controller.fetchModelClass(className)); } @Test - public void isBrained() { - Assert.assertFalse(new NullDroolsController().isBrained()); + void isBrained() { + assertFalse(new NullDroolsController().isBrained()); } @Test - public void stringify() { - Assert.assertNotNull(new NullDroolsController().toString()); + void stringify() { + assertNotNull(new NullDroolsController().toString()); } - @Test(expected = IllegalArgumentException.class) - public void updateToVersion() { - new NullDroolsController().updateToVersion(null, null, null, null, null); + @Test + void updateToVersion() { + var controller = new NullDroolsController(); + assertThrows(IllegalArgumentException.class, () -> + controller.updateToVersion(null, null, null, null, null)); } @Test - public void factClassNames() { - Assert.assertTrue(new NullDroolsController().factClassNames(null).isEmpty()); + void factClassNames() { + assertTrue(new NullDroolsController().factClassNames(null).isEmpty()); } @Test - public void factCount() { - Assert.assertEquals(0, new NullDroolsController().factCount(null)); + void factCount() { + assertEquals(0, new NullDroolsController().factCount(null)); } @Test - public void facts() { - Assert.assertTrue(new NullDroolsController().facts(null, null, true).isEmpty()); + void facts() { + assertTrue(new NullDroolsController().facts(null, null, true).isEmpty()); } @Test - public void factQuery() { - Assert.assertTrue(new NullDroolsController().factQuery(null, null, null, false).isEmpty()); + void factQuery() { + assertTrue(new NullDroolsController().factQuery(null, null, null, false).isEmpty()); } @Test - public void exists() { + void exists() { Object o1 = new Object(); - Assert.assertFalse(new NullDroolsController().exists("blah", o1)); - Assert.assertFalse(new NullDroolsController().exists(o1)); + assertFalse(new NullDroolsController().exists("blah", o1)); + assertFalse(new NullDroolsController().exists(o1)); } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java b/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java index 15a0b18f..b6a9ce52 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +21,9 @@ package org.onap.policy.drools.persistence; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.assertTrue; import java.io.FileOutputStream; import java.io.IOException; @@ -32,17 +33,17 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Properties; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.onap.policy.drools.properties.DroolsPropertyConstants; /** * (File) System Persistence Tests. */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodOrderer.MethodName.class) public class SystemPersistenceTest { /** * sample configuration dir. @@ -124,18 +125,18 @@ public class SystemPersistenceTest { private static final String SYSTEM_PROPS = TEST_CONTROLLER_NAME; private static final String SYSTEM_PROPS_FILE = SYSTEM_PROPS + "-system.properties"; - @BeforeClass + @BeforeAll public static void setUp() throws IOException { cleanUpWorkingDirs(); } - @AfterClass + @AfterAll public static void tearDown() throws IOException { cleanUpWorkingDirs(); } @Test - public void test1NonDefaultConfigDir() { + void test1NonDefaultConfigDir() { SystemPersistenceConstants.getManager().setConfigurationDir(OTHER_CONFIG_DIR); assertEquals(OTHER_CONFIG_DIR, SystemPersistenceConstants.getManager().getConfigurationPath().toString()); @@ -149,7 +150,7 @@ public class SystemPersistenceTest { } @Test - public void test2Engine_Environment_System() throws IOException { + void test2Engine_Environment_System() throws IOException { SystemPersistenceConstants.getManager().setConfigurationDir(OTHER_CONFIG_DIR); final Path policyEnginePropsPath = @@ -191,7 +192,7 @@ public class SystemPersistenceTest { } @Test - public void test3Topic() { + void test3Topic() { SystemPersistenceConstants.getManager().setConfigurationDir(null); Path topicPath = Paths @@ -221,7 +222,7 @@ public class SystemPersistenceTest { } @Test - public void test4HttpServer() { + void test4HttpServer() { SystemPersistenceConstants.getManager().setConfigurationDir(null); Path httpServerPath = Paths @@ -251,7 +252,7 @@ public class SystemPersistenceTest { } @Test - public void test5HttpClient() { + void test5HttpClient() { SystemPersistenceConstants.getManager().setConfigurationDir(null); Path httpClientPath = Paths @@ -281,7 +282,7 @@ public class SystemPersistenceTest { } @Test - public void test6Controller() { + void test6Controller() { SystemPersistenceConstants.getManager().setConfigurationDir(null); Path controllerPath = Paths diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java index b6168a2e..6d461eef 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +22,12 @@ package org.onap.policy.drools.protocol.coders; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Properties; import lombok.AllArgsConstructor; import lombok.Getter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; @@ -34,7 +35,7 @@ import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; /** * Tests Coders. */ -public class EventProtocolCoderTest { +class EventProtocolCoderTest { /** * Coder Group. @@ -66,7 +67,7 @@ public class EventProtocolCoderTest { } @Test - public void test() { + void test() { final Properties noopSinkProperties = new Properties(); noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilterTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilterTest.java index e0baeb6d..28b3e040 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilterTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilterTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +21,14 @@ package org.onap.policy.drools.protocol.coders; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JsonProtocolFilterTest { +class JsonProtocolFilterTest { private static final String JSON = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\"," @@ -38,7 +40,7 @@ public class JsonProtocolFilterTest { * Tests getting the rule expression of the filter. */ @Test - public void getRuleTest() { + void getRuleTest() { assertEquals("$.test", new JsonProtocolFilter("$.test").getRule()); } @@ -46,7 +48,7 @@ public class JsonProtocolFilterTest { * Tests setting the rule expression of the filter. */ @Test - public void setRuleTest() { + void setRuleTest() { JsonProtocolFilter filter = new JsonProtocolFilter(); assertEquals(JsonProtocolFilter.MATCH_ANY, filter.getRule()); filter.setRule("$.test"); @@ -57,7 +59,7 @@ public class JsonProtocolFilterTest { * Tests that the rule expression will be set to match anything if an empty string is passed. */ @Test - public void setRuleEmptyTest() { + void setRuleEmptyTest() { assertEquals(JsonProtocolFilter.MATCH_ANY, new JsonProtocolFilter("").getRule()); } @@ -65,7 +67,7 @@ public class JsonProtocolFilterTest { * Tests that the rule expression will be set to match anything if a null string is passed. */ @Test - public void setRuleNullTest() { + void setRuleNullTest() { assertEquals(JsonProtocolFilter.MATCH_ANY, new JsonProtocolFilter(null).getRule()); } @@ -73,7 +75,7 @@ public class JsonProtocolFilterTest { * Tests accepting a message if all filter rules pass. */ @Test - public void acceptPassTest() { + void acceptPassTest() { assertTrue(new JsonProtocolFilter( "$.controllers[?(@.drools.version =~ /\\d\\.\\d\\.\\d/ && @.operation == 'update')]") .accept(JSON)); @@ -83,7 +85,7 @@ public class JsonProtocolFilterTest { * Tests accepting a message without having to filter if the rule is set to match anything. */ @Test - public void acceptAnyTest() { + void acceptAnyTest() { assertTrue(new JsonProtocolFilter(null).accept(JSON)); } @@ -91,7 +93,7 @@ public class JsonProtocolFilterTest { * Tests rejecting a message if one or more of the filter rules fail. */ @Test - public void acceptFailTest() { + void acceptFailTest() { assertFalse( new JsonProtocolFilter("$.controllers[?(@.drools.version =~ /\\\\d\\\\.\\\\d\\\\.2/)]") .accept(JSON)); @@ -101,7 +103,7 @@ public class JsonProtocolFilterTest { * Tests finding field matches for a filter rule corresponding to a topic. */ @Test - public void filterPassTest() { + void filterPassTest() { assertEquals("38adde30-cc22-11e8-a8d5-f2801f1b9fd1", new JsonProtocolFilter("$.requestID").filter(JSON).get(0)); } @@ -109,7 +111,7 @@ public class JsonProtocolFilterTest { * Tests that an empty list is returned when no matches are found. */ @Test - public void filterFailTest() { + void filterFailTest() { assertTrue(new JsonProtocolFilter("$.test").filter(JSON).isEmpty()); } @@ -117,7 +119,7 @@ public class JsonProtocolFilterTest { * Tests static method for filtering a JSON string with an arbitrary expression. */ @Test - public void staticFilterPassTest() { + void staticFilterPassTest() { assertEquals("controller", JsonProtocolFilter.filter(JSON, "$.entity").get(0)); } @@ -125,39 +127,39 @@ public class JsonProtocolFilterTest { * Tests that an empty list is returned when the static filter() method does not find any matches. */ @Test - public void staticFilterFailTest() { + void staticFilterFailTest() { assertTrue(JsonProtocolFilter.filter(JSON, "$.test").isEmpty()); } /** * Tests that an exception is thrown if a null JSON string is passed. */ - @Test(expected = IllegalArgumentException.class) - public void staticFilterNullJsonTest() { - JsonProtocolFilter.filter(null, "[?($ =~ /.*/"); + @Test + void staticFilterNullJsonTest() { + assertThrows(IllegalArgumentException.class, () -> JsonProtocolFilter.filter(null, "[?($ =~ /.*/")); } /** * Tests that an exception is thrown if an empty JSON string is passed. */ - @Test(expected = IllegalArgumentException.class) - public void staticFilterEmptyJsonTest() { - JsonProtocolFilter.filter("", "[?($ =~ /.*/"); + @Test + void staticFilterEmptyJsonTest() { + assertThrows(IllegalArgumentException.class, () -> JsonProtocolFilter.filter("", "[?($ =~ /.*/")); } /** * Tests that an exception is thrown if a null expression string is passed. */ - @Test(expected = IllegalArgumentException.class) - public void staticFilterNullExpressionTest() { - JsonProtocolFilter.filter("{\"hello\":\"world\"}", null); + @Test + void staticFilterNullExpressionTest() { + assertThrows(IllegalArgumentException.class, () -> JsonProtocolFilter.filter("{\"hello\":\"world\"}", null)); } /** * Tests that an exception is thrown if an empty expression string is passed. */ - @Test(expected = IllegalArgumentException.class) - public void staticFilterEmptyExpressionTest() { - JsonProtocolFilter.filter("{\"hello\":\"world\"}", ""); + @Test + void staticFilterEmptyExpressionTest() { + assertThrows(IllegalArgumentException.class, () -> JsonProtocolFilter.filter("{\"hello\":\"world\"}", "")); } }
\ No newline at end of file diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java index 6d1ec3d3..659965f8 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2021-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +22,11 @@ package org.onap.policy.drools.protocol.coders; 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.assertSame; +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.assertSame; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -35,10 +36,10 @@ import java.util.List; import java.util.Properties; import lombok.AllArgsConstructor; import lombok.Getter; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.event.comm.TopicSink; @@ -73,7 +74,7 @@ public class ProtocolCoderToolsetTest { /** * Test Class Initialization. */ - @BeforeClass + @BeforeAll public static void setUpClass() throws IOException { releaseId = KieUtils.installArtifact(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_PATH).toFile(), Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH).toFile(), @@ -84,7 +85,7 @@ public class ProtocolCoderToolsetTest { /** * Test Set Up. */ - @Before + @BeforeEach public void setUp() { controller = createController(); } @@ -92,7 +93,7 @@ public class ProtocolCoderToolsetTest { /** * Test Termination. */ - @After + @AfterEach public void tearDown() { if (controller != null) { DroolsControllerConstants.getFactory().destroy(controller); @@ -100,7 +101,7 @@ public class ProtocolCoderToolsetTest { } @Test - public void testToolsets() { + void testToolsets() { testGsonToolset(createFilterSet()); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java index 7248f11e..f251f9bf 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,16 +22,16 @@ package org.onap.policy.drools.protocol.configuration; 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.assertNotEquals; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.gson.GsonTestUtils; -public class ControllerConfigurationTest { +class ControllerConfigurationTest { private static final String NAME = "name"; private static final String OPERATION = "operation"; @@ -60,7 +61,7 @@ public class ControllerConfigurationTest { * Test. */ @Test - public void test() { + void test() { Properties additionalProperties = new Properties(); additionalProperties.put(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); @@ -104,7 +105,7 @@ public class ControllerConfigurationTest { } @Test - public void testSerialize() { + void testSerialize() { ControllerConfiguration controllerConfig = new ControllerConfiguration(NAME, OPERATION, DROOLS_CONFIG); controllerConfig.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); controllerConfig.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY2, ADDITIONAL_PROPERTY_VALUE2); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java index 2d1ed7e2..e693d000 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +22,15 @@ package org.onap.policy.drools.protocol.configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.gson.GsonTestUtils; -public class DroolsConfigurationTest { +class DroolsConfigurationTest { private static final String ARTIFACT_ID_STRING = "artifactId"; private static final String GROUP_ID_STRING = "groupId"; private static final String VERSION_STRING = "version"; @@ -51,7 +52,7 @@ public class DroolsConfigurationTest { private static final String ADDITIONAL_PROPERTY_VALUE2 = "world"; @Test - public void test() { + void test() { final Properties additionalProperties = new Properties(); additionalProperties.put(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); @@ -96,7 +97,7 @@ public class DroolsConfigurationTest { } @Test - public void testSerialize() { + void testSerialize() { final DroolsConfiguration droolsConfig = new DroolsConfiguration(ARTIFACT, GROUPID, VERSION); droolsConfig.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); droolsConfig.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY2, ADDITIONAL_PROPERTY_VALUE2); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java index a8a0a2ac..f8f542c8 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +21,19 @@ package org.onap.policy.drools.protocol.configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.gson.GsonTestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PdpdConfigurationTest { +class PdpdConfigurationTest { private static final Logger logger = LoggerFactory.getLogger(PdpdConfigurationTest.class); @@ -64,7 +64,7 @@ public class PdpdConfigurationTest { private static final String OPERATION2 = "operation2"; @Test - public void test() { + void test() { // // Empty constructor test // @@ -246,14 +246,14 @@ public class PdpdConfigurationTest { } @Test - public void testConstructor() { + void testConstructor() { PdpdConfiguration config = new PdpdConfiguration(REQUEST_ID, ENTITY, null); assertEquals(REQUEST_ID, config.getRequestId()); assertEquals(ENTITY, config.getEntity()); } @Test - public void testSerialize() throws IOException { + void testSerialize() { List<ControllerConfiguration> controllers = Arrays.asList(new ControllerConfiguration(NAME, OPERATION, null), new ControllerConfiguration(NAME2, OPERATION2, null)); PdpdConfiguration pdpConfig = new PdpdConfiguration(REQUEST_ID, ENTITY, controllers); diff --git a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java index ad0d1afc..65447d80 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java @@ -21,7 +21,7 @@ package org.onap.policy.drools.server.restful.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.file.Files; @@ -44,11 +44,11 @@ import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.http.server.YamlJacksonHandler; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; @@ -60,7 +60,7 @@ import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodOrderer.DisplayName.class) public class RestManagerTest { private static final int DEFAULT_TELEMETRY_PORT = 7887; private static final String HOST = "localhost"; @@ -71,31 +71,19 @@ public class RestManagerTest { private static final String FOO_CONTROLLER = "foo"; private static final String UEB_TOPIC = "ueb-topic-test"; - private static final String DMAAP_TOPIC = "dmaap-topic-test"; + private static final String KAFKA_TOPIC = "kafka-topic-test"; private static final String NOOP_TOPIC = "noop_topic"; private static final String UEB_SOURCE_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + UEB_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; private static final String UEB_SINK_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + UEB_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String DMAAP_SOURCE_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS - + "." + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String DMAAP_SINK_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String KAFKA_SOURCE_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS + + "." + KAFKA_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String KAFKA_SINK_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS + "." + + KAFKA_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; private static final String UEB_SERVER = "localhost"; - private static final String DMAAP_SERVER = "localhost"; - private static final String DMAAP_MECHID = "blah"; - private static final String DMAAP_PASSWD = "blah"; - - private static final String DMAAP_SOURCE_MECHID_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; - private static final String DMAAP_SOURCE_PASSWD_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; - - private static final String DMAAP_SINK_MECHID_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; - private static final String DMAAP_SINK_PASSWD_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; + private static final String KAFKA_SERVER = "localhost:9092"; private static final String FOO_CONTROLLER_FILE = FOO_CONTROLLER + "-controller.properties"; private static final String FOO_CONTROLLER_FILE_BAK = FOO_CONTROLLER_FILE + ".bak"; @@ -111,7 +99,7 @@ public class RestManagerTest { * * @throws IOException throws an IO exception */ - @BeforeClass + @BeforeAll public static void setUp() throws IOException, InterruptedException { cleanUpWorkingDirs(); @@ -124,10 +112,6 @@ public class RestManagerTest { + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "" + DEFAULT_TELEMETRY_PORT); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME - + PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, - TestAafTelemetryAuthFilter.class.getName()); - engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, TELEMETRY_USER); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." @@ -142,16 +126,12 @@ public class RestManagerTest { /* other properties */ engineProps.put(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS, UEB_TOPIC); engineProps.put(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS, UEB_TOPIC); - engineProps.put(PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS, DMAAP_TOPIC); - engineProps.put(PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS, DMAAP_TOPIC); + engineProps.put(PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS, KAFKA_TOPIC); + engineProps.put(PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS, KAFKA_TOPIC); engineProps.put(UEB_SOURCE_SERVER_PROPERTY, UEB_SERVER); engineProps.put(UEB_SINK_SERVER_PROPERTY, UEB_SERVER); - engineProps.put(DMAAP_SOURCE_SERVER_PROPERTY, DMAAP_SERVER); - engineProps.put(DMAAP_SINK_SERVER_PROPERTY, DMAAP_SERVER); - engineProps.put(DMAAP_SOURCE_MECHID_KEY, DMAAP_MECHID); - engineProps.put(DMAAP_SOURCE_PASSWD_KEY, DMAAP_PASSWD); - engineProps.put(DMAAP_SINK_MECHID_KEY, DMAAP_MECHID); - engineProps.put(DMAAP_SINK_PASSWD_KEY, DMAAP_PASSWD); + engineProps.put(KAFKA_SOURCE_SERVER_PROPERTY, KAFKA_SERVER); + engineProps.put(KAFKA_SINK_SERVER_PROPERTY, KAFKA_SERVER); PolicyEngineConstants.getManager().configure(engineProps); PolicyEngineConstants.getManager().start(); @@ -181,7 +161,7 @@ public class RestManagerTest { * * @throws IOException IO exception */ - @AfterClass + @AfterAll public static void tearDown() throws IOException { try { client.close(); @@ -198,7 +178,7 @@ public class RestManagerTest { @Test - public void testPutDelete() throws IOException { + void testPutDelete() throws IOException { putTest(HOST_URL + "/engine/switches/lock", 406); deleteTest(HOST_URL + "/engine/switches/lock", 406); @@ -218,24 +198,24 @@ public class RestManagerTest { private void putDeleteTopicSwitches() throws IOException { putDeleteSwitch("/engine/topics/sources/ueb/", UEB_TOPIC, "lock"); - putDeleteSwitch("/engine/topics/sources/dmaap/", DMAAP_TOPIC, "lock"); + putDeleteSwitch("/engine/topics/sources/kafka/", KAFKA_TOPIC, "lock"); putDeleteSwitch("/engine/topics/sources/noop/", NOOP_TOPIC, "lock"); putDeleteSwitch("/engine/topics/sinks/ueb/", UEB_TOPIC, "lock"); - putDeleteSwitch("/engine/topics/sinks/dmaap/", DMAAP_TOPIC, "lock"); + putDeleteSwitch("/engine/topics/sinks/kafka/", KAFKA_TOPIC, "lock"); putDeleteSwitch("/engine/topics/sinks/noop/", NOOP_TOPIC, "lock"); putDeleteSwitch("/engine/topics/sources/ueb/", UEB_TOPIC, "activation"); - putDeleteSwitch("/engine/topics/sources/dmaap/", DMAAP_TOPIC, "activation"); + putDeleteSwitch("/engine/topics/sources/kafka/", KAFKA_TOPIC, "activation"); putDeleteSwitch("/engine/topics/sources/noop/", NOOP_TOPIC, "activation"); putDeleteSwitch("/engine/topics/sinks/ueb/", UEB_TOPIC, "activation"); - putDeleteSwitch("/engine/topics/sinks/dmaap/", DMAAP_TOPIC, "activation"); + putDeleteSwitch("/engine/topics/sinks/kafka/", KAFKA_TOPIC, "activation"); putDeleteSwitch("/engine/topics/sinks/noop/", NOOP_TOPIC, "activation"); putSwitch("/engine/topics/sources/ueb/", UEB_TOPIC, "activation"); - putSwitch("/engine/topics/sources/dmaap/", DMAAP_TOPIC, "activation"); + putSwitch("/engine/topics/sources/kafka/", KAFKA_TOPIC, "activation"); putSwitch("/engine/topics/sources/noop/", NOOP_TOPIC, "activation"); putSwitch("/engine/topics/sinks/ueb/", UEB_TOPIC, "activation"); - putSwitch("/engine/topics/sinks/dmaap/", DMAAP_TOPIC, "activation"); + putSwitch("/engine/topics/sinks/kafka/", KAFKA_TOPIC, "activation"); putSwitch("/engine/topics/sinks/noop/", NOOP_TOPIC, "activation"); } @@ -244,15 +224,15 @@ public class RestManagerTest { "{x:y}", ContentType.TEXT_PLAIN); putTest(HOST_URL + "/engine/topics/sources/noop/" + NOOP_TOPIC + "/events", 200, "{x:y}", ContentType.TEXT_PLAIN); - putTest(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events", 200, + putTest(HOST_URL + "/engine/topics/sources/kafka/" + KAFKA_TOPIC + "/events", 200, "FOOOO", ContentType.TEXT_PLAIN); putTest(HOST_URL + "/engine/topics/sources/ueb/fiznits/events", 406, "FOOOO", ContentType.TEXT_PLAIN); - putTest(HOST_URL + "/engine/topics/sources/dmaap/fiznits/events", 406, + putTest(HOST_URL + "/engine/topics/sources/kafka/fiznits/events", 406, "FOOOO", ContentType.TEXT_PLAIN); putTest(HOST_URL + "/engine/topics/switches/lock", 200); putTest(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events", 406, "FOOOO", ContentType.TEXT_PLAIN); - putTest(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events", + putTest(HOST_URL + "/engine/topics/sources/kafka/" + KAFKA_TOPIC + "/events", 406, "FOOOO", ContentType.TEXT_PLAIN); deleteTest(HOST_URL + "/engine/topics/switches/lock", 200); } @@ -311,7 +291,7 @@ public class RestManagerTest { } @Test - public void testPost() throws IOException { + void testPost() throws IOException { postTest(HOST_URL + "/engine/inputs/configuration", 406, Files.readString(Paths.get(PDP_CONFIGURATION_JSON)), ContentType.APPLICATION_JSON); @@ -338,7 +318,7 @@ public class RestManagerTest { } @Test - public void testGetSwagger() throws IOException { + void testGetSwagger() throws IOException { HttpGet httpGet; CloseableHttpResponse response; httpGet = new HttpGet(HOST_URL + "/engine/swagger"); @@ -349,7 +329,7 @@ public class RestManagerTest { } @Test - public void testGet() throws IOException { + void testGet() throws IOException { HttpGet httpGet; CloseableHttpResponse response; @@ -630,13 +610,13 @@ public class RestManagerTest { /* * GET: /engine/topics /engine/topics/switches /engine/topics/sources /engine/topics/sinks - * /engine/topics/sinks/ueb /engine/topics/sources/ueb /engine/topics/sinks/dmaap - * /engine/topics/sources/dmaap /engine/topics/sinks/ueb/topic - * /engine/topics/sources/ueb/topic /engine/topics/sinks/dmaap/topic - * /engine/topics/sources/dmaap/topic /engine/topics/sinks/ueb/topic/events - * /engine/topics/sources/ueb/topic/events /engine/topics/sinks/dmaap/topic/events - * /engine/topics/sources/dmaap/topic/events /engine/topics/sources/ueb/topic/switches - * /engine/topics/sources/dmaap/topic/switches + * /engine/topics/sinks/ueb /engine/topics/sources/ueb /engine/topics/sinks/kafka + * /engine/topics/sources/kafka /engine/topics/sinks/ueb/topic + * /engine/topics/sources/ueb/topic /engine/topics/sinks/kafka/topic + * /engine/topics/sources/kafka/topic /engine/topics/sinks/ueb/topic/events + * /engine/topics/sources/ueb/topic/events /engine/topics/sinks/kafka/topic/events + * /engine/topics/sources/kafka/topic/events /engine/topics/sources/ueb/topic/switches + * /engine/topics/sources/kafka/topic/switches */ httpGet = new HttpGet(HOST_URL + "/engine/topics"); response = client.execute(httpGet); @@ -674,13 +654,13 @@ public class RestManagerTest { assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); @@ -722,25 +702,25 @@ public class RestManagerTest { assertEquals(500, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka/" + KAFKA_TOPIC); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka/foobar"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(500, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka/" + KAFKA_TOPIC); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka/foobar"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(500, response.getStatusLine().getStatusCode()); @@ -794,25 +774,25 @@ public class RestManagerTest { assertEquals(500, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka/" + KAFKA_TOPIC + "/events"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar/events"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka/foobar/events"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(500, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC + "/events"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka/" + KAFKA_TOPIC + "/events"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar/events"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka/foobar/events"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(500, response.getStatusLine().getStatusCode()); @@ -848,7 +828,7 @@ public class RestManagerTest { assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/kafka/" + KAFKA_TOPIC + "/switches"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); @@ -866,7 +846,7 @@ public class RestManagerTest { assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC + "/switches"); + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/kafka/" + KAFKA_TOPIC + "/switches"); response = client.execute(httpGet); logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode()); diff --git a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/TestAafTelemetryAuthFilter.java b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/TestAafTelemetryAuthFilter.java deleted file mode 100644 index 6a9be8a2..00000000 --- a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/TestAafTelemetryAuthFilter.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.server.restful.test; - -import jakarta.servlet.http.HttpServletRequest; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.drools.server.restful.aaf.AafTelemetryAuthFilter; - -/** - * Test AAF Telemetry Authorization Filter for Junits. - */ -public class TestAafTelemetryAuthFilter extends AafTelemetryAuthFilter { - - @Override - protected String getRole(HttpServletRequest request) { - String expectedPerm = "org.onap.policy.pdpd.telemetry|" - + NetworkUtil.getHostname() + "|" - + request.getMethod().toLowerCase(); - if (!expectedPerm.equals(super.getRole(request))) { - throw new IllegalStateException("unexpected permission"); - } else { - return "user"; - } - } -} diff --git a/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsManagerTest.java index a12fb50a..118c4d7e 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsManagerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +21,15 @@ package org.onap.policy.drools.stats; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.drools.metrics.Metric; -public class PolicyStatsManagerTest { +class PolicyStatsManagerTest { @Test - public void testStat() { + void testStat() { PolicyStatsManager stats = new PolicyStatsManager(); assertEquals(0, stats.getGroupStat().getPolicyExecutedCount()); diff --git a/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsTest.java b/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsTest.java index 631e85b8..3f26e82e 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/stats/PolicyStatsTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +22,15 @@ package org.onap.policy.drools.stats; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.drools.metrics.Metric; -public class PolicyStatsTest { +class PolicyStatsTest { @Test - public void testStat() { + void testStat() { Metric trans1 = createTrans(); trans1.setSuccess(true); diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyControllerFactoryTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyControllerFactoryTest.java index 818f8fc1..615ffe2b 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyControllerFactoryTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyControllerFactoryTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +23,9 @@ package org.onap.policy.drools.system; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -35,10 +36,11 @@ import static org.onap.policy.drools.properties.DroolsPropertyConstants.PROPERTY import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.Properties; -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.gson.GsonTestUtils; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.controller.internal.NullDroolsController; @@ -48,7 +50,7 @@ import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; import org.onap.policy.drools.system.internal.AggregatedPolicyController; -public class PolicyControllerFactoryTest { +class PolicyControllerFactoryTest { private static final String POLICY_CONTROLLER_BUILDER_TAG = "PolicyControllerFactoryTest"; private static final String MY_NAME = "my-name-a"; @@ -79,7 +81,7 @@ public class PolicyControllerFactoryTest { /** * Initializes the object to be tested. */ - @Before + @BeforeEach public void setUp() { controller = mock(PolicyController.class); controller2 = mock(PolicyController.class); @@ -114,14 +116,14 @@ public class PolicyControllerFactoryTest { } @Test - public void testFactory() { + void testFactory() { // use a REAL object instead of an Impl ipc = new IndexedPolicyControllerFactory(); assertNotNull(ipc.getProviders()); } @Test - public void testBuild() { + void testBuild() { assertEquals(controller, ipc.build(MY_NAME, properties)); // re-build - should not create another one @@ -134,14 +136,14 @@ public class PolicyControllerFactoryTest { } @Test - public void testSerialize() { + void testSerialize() { assertEquals(controller, ipc.build(MY_NAME, properties)); new GsonTestUtils().compareGson(ipc, PolicyControllerFactoryTest.class); } @Test - public void testPatchStringDroolsConfiguration() { + void testPatchStringDroolsConfiguration() { // unknown controller assertThatIllegalArgumentException().isThrownBy(() -> ipc.patch(MY_NAME, config)); @@ -173,7 +175,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testPatchPolicyControllerDroolsConfiguration() { + void testPatchPolicyControllerDroolsConfiguration() { ipc.patch(controller, config); verify(controller).updateDrools(config); @@ -194,7 +196,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testShutdownString() { + void testShutdownString() { // null name String nullName = null; assertThatIllegalArgumentException().isThrownBy(() -> ipc.shutdown(nullName)); @@ -213,7 +215,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testShutdownPolicyController() { + void testShutdownPolicyController() { ipc.build(MY_NAME, properties); ipc.shutdown(controller); @@ -225,7 +227,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testShutdown() { + void testShutdown() { ipc.build(MY_NAME, properties); ipc.build(MY_NAME2, properties); @@ -240,7 +242,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testUnmanage() { + void testUnmanage() { ipc.build(MY_NAME, properties); ipc.build(MY_NAME2, properties); @@ -265,7 +267,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testDestroyString() { + void testDestroyString() { // null name String nullName = null; assertThatIllegalArgumentException().isThrownBy(() -> ipc.destroy(nullName)); @@ -284,7 +286,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testDestroyPolicyController() { + void testDestroyPolicyController() { ipc.build(MY_NAME, properties); ipc.destroy(controller); @@ -296,7 +298,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testDestroy() { + void testDestroy() { ipc.build(MY_NAME, properties); ipc.build(MY_NAME2, properties); @@ -311,7 +313,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testGetString() { + void testGetString() { // unknown name assertThatIllegalArgumentException().isThrownBy(() -> ipc.get(MY_NAME)); @@ -330,7 +332,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testGetStringString_testToKey() { + void testGetStringString_testToKey() { // unknown controller assertThatIllegalArgumentException().isThrownBy(() -> ipc.get(GROUP1, ARTIFACT1)); @@ -357,7 +359,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testGetDroolsController() { + void testGetDroolsController() { // unknown controller assertThatIllegalStateException().isThrownBy(() -> ipc.get(drools)); @@ -376,27 +378,27 @@ public class PolicyControllerFactoryTest { } @Test - public void testInventory() { + void testInventory() { ipc.build(MY_NAME, properties); ipc.build(MY_NAME2, properties); List<PolicyController> lst = ipc.inventory(); - Collections.sort(lst, (left, right) -> left.getName().compareTo(right.getName())); + lst.sort(Comparator.comparing(PolicyController::getName)); assertEquals(Arrays.asList(controller, controller2), lst); } @Test - public void testGetFeatures() { + void testGetFeatures() { assertEquals(Arrays.asList(FEATURE1, FEATURE2), ipc.getFeatures()); } @Test - public void testGetFeatureProviders() { + void testGetFeatureProviders() { assertEquals(providers, ipc.getFeatureProviders()); } @Test - public void testGetFeatureProvider() { + void testGetFeatureProvider() { // null name assertThatIllegalArgumentException().isThrownBy(() -> ipc.getFeatureProvider(null)); @@ -411,7 +413,7 @@ public class PolicyControllerFactoryTest { } @Test - public void testControllerType() { + void testControllerType() { PolicyControllerFactory factory = new IndexedPolicyControllerFactory(); Properties props = new Properties(); diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyDroolsPdpRuntimeExceptionTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyDroolsPdpRuntimeExceptionTest.java index 64595178..f4b26307 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyDroolsPdpRuntimeExceptionTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyDroolsPdpRuntimeExceptionTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +23,15 @@ package org.onap.policy.drools.system; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; -public class PolicyDroolsPdpRuntimeExceptionTest { +class PolicyDroolsPdpRuntimeExceptionTest { @Test - public void test() { + void test() { assertEquals(2, new ExceptionsTester().test(PolicyDroolsPdpRuntimeException.class)); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java index 93c0f348..4006c9ed 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,13 @@ import static org.assertj.core.api.Assertions.assertThatCode; 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.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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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.anyLong; import static org.mockito.Mockito.doThrow; @@ -50,9 +51,9 @@ import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiConsumer; 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.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; import org.onap.policy.common.endpoints.event.comm.TopicSink; @@ -80,7 +81,7 @@ import org.onap.policy.drools.system.internal.SimpleLockManager; import org.onap.policy.drools.system.internal.SimpleLockProperties; import org.onap.policy.models.pdp.enums.PdpResponseStatus; -public class PolicyEngineManagerTest { +class PolicyEngineManagerTest { private static final String EXPECTED = "expected exception"; private static final String NOOP_STR = CommInfrastructure.NOOP.name(); @@ -158,7 +159,7 @@ public class PolicyEngineManagerTest { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { CollectorRegistry.defaultRegistry.clear(); properties = new Properties(); @@ -324,13 +325,13 @@ public class PolicyEngineManagerTest { mgr = new PolicyEngineManagerImpl(); } - @After + @AfterEach public void tearDown() { CollectorRegistry.defaultRegistry.clear(); } @Test - public void testSerialize() { + void testSerialize() { mgr.setHostName("foo"); mgr.setClusterName("bar"); mgr.configure(properties); @@ -338,7 +339,7 @@ public class PolicyEngineManagerTest { } @Test - public void testFactory() { + void testFactory() { mgr = new PolicyEngineManager(); assertNotNull(mgr.getEngineProviders()); @@ -353,7 +354,7 @@ public class PolicyEngineManagerTest { } @Test - public void testBoot() throws Exception { + void testBoot() throws Exception { String[] args = {"boot-a", "boot-b"}; // arrange for first provider to throw exceptions @@ -392,7 +393,7 @@ public class PolicyEngineManagerTest { } @Test - public void testSetEnvironment_testGetEnvironment_testGetEnvironmentProperty_setEnvironmentProperty() { + void testSetEnvironment_testGetEnvironment_testGetEnvironmentProperty_setEnvironmentProperty() { Properties props1 = new Properties(); props1.put("prop1-a", "value1-a"); props1.put("prop1-b", "value1-b"); @@ -440,14 +441,14 @@ public class PolicyEngineManagerTest { } @Test - public void testDefaultTelemetryConfig() { + void testDefaultTelemetryConfig() { Properties config = mgr.defaultTelemetryConfig(); assertNotNull(config); assertFalse(config.isEmpty()); } @Test - public void testGetPdpName() { + void testGetPdpName() { properties.setProperty(PolicyEngineManager.CLUSTER_NAME_PROP, "east1"); mgr.configure(properties); @@ -480,7 +481,7 @@ public class PolicyEngineManagerTest { * property. */ @Test - public void testMakeExecutorServicePropertyProvided() { + void testMakeExecutorServicePropertyProvided() { PolicyEngineManager mgrspy = spy(mgr); properties.setProperty(PolicyEngineManager.EXECUTOR_THREAD_PROP, "3"); @@ -494,7 +495,7 @@ public class PolicyEngineManagerTest { * property is provided. */ @Test - public void testMakeExecutorServiceNoProperty() { + void testMakeExecutorServiceNoProperty() { PolicyEngineManager mgrspy = spy(mgr); mgrspy.configure(properties); @@ -507,7 +508,7 @@ public class PolicyEngineManagerTest { * property is invalid. */ @Test - public void testMakeExecutorServiceInvalidProperty() { + void testMakeExecutorServiceInvalidProperty() { PolicyEngineManager mgrspy = spy(mgr); properties.setProperty(PolicyEngineManager.EXECUTOR_THREAD_PROP, "abc"); @@ -521,7 +522,7 @@ public class PolicyEngineManagerTest { * manager. */ @Test - public void testCreateLockManagerHaveProvider() { + void testCreateLockManagerHaveProvider() { // first provider throws an exception when(prov1.beforeCreateLockManager(any(), any())).thenThrow(new RuntimeException(EXPECTED)); @@ -533,7 +534,7 @@ public class PolicyEngineManagerTest { * Tests createLockManager() when SimpleLockManager throws an exception. */ @Test - public void testCreateLockManagerSimpleEx() { + void testCreateLockManagerSimpleEx() { when(prov2.beforeCreateLockManager(any(), any())).thenReturn(null); // invalid property for SimpleLockManager @@ -541,22 +542,22 @@ public class PolicyEngineManagerTest { mgr.configure(properties); // should create a manager using default properties - assertTrue(mgr.getLockManager() instanceof SimpleLockManager); + assertInstanceOf(SimpleLockManager.class, mgr.getLockManager()); } /** * Tests createLockManager() when SimpleLockManager is returned. */ @Test - public void testCreateLockManagerSimple() { + void testCreateLockManagerSimple() { when(prov2.beforeCreateLockManager(any(), any())).thenReturn(null); mgr.configure(properties); - assertTrue(mgr.getLockManager() instanceof SimpleLockManager); + assertInstanceOf(SimpleLockManager.class, mgr.getLockManager()); } @Test - public void testConfigureProperties() throws Exception { + void testConfigureProperties() throws Exception { // arrange for first provider to throw exceptions when(prov1.beforeConfigure(mgr, properties)).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterConfigure(mgr)).thenThrow(new RuntimeException(EXPECTED)); @@ -605,7 +606,7 @@ public class PolicyEngineManagerTest { } @Test - public void testConfigurePdpdConfiguration() throws Exception { + void testConfigurePdpdConfiguration() throws Exception { mgr.configure(properties); assertTrue(mgr.configure(pdpConfig)); @@ -630,7 +631,7 @@ public class PolicyEngineManagerTest { } @Test - public void testCreatePolicyController() throws Exception { + void testCreatePolicyController() throws Exception { assertEquals(controller, mgr.createPolicyController(MY_NAME, properties)); verify(contProv1).beforeCreate(MY_NAME, properties); @@ -698,7 +699,7 @@ public class PolicyEngineManagerTest { } @Test - public void testUpdatePolicyControllers() throws Exception { + void testUpdatePolicyControllers() throws Exception { assertEquals(Arrays.asList(controller3, controller4), mgr.updatePolicyControllers(pdpConfig.getControllers())); // controller3 was CREATE @@ -730,7 +731,7 @@ public class PolicyEngineManagerTest { } @Test - public void testUpdatePolicyController() throws Exception { + void testUpdatePolicyController() throws Exception { assertEquals(controller3, mgr.updatePolicyController(config3)); verify(engine).createPolicyController(CONTROLLER3, properties); @@ -825,7 +826,7 @@ public class PolicyEngineManagerTest { } @Test - public void testStart() throws Throwable { + void testStart() throws Throwable { // normal success case testStart(true, () -> { // arrange for first provider, server, source, and sink to throw exceptions @@ -935,7 +936,7 @@ public class PolicyEngineManagerTest { } @Test - public void testStop() throws Throwable { + void testStop() throws Throwable { // normal success case testStop(true, () -> { // arrange for first provider, server, source, and sink to throw exceptions @@ -1043,7 +1044,7 @@ public class PolicyEngineManagerTest { } @Test - public void testShutdown() throws Throwable { + void testShutdown() throws Throwable { // normal success case testShutdown(() -> { // arrange for first provider, source, and sink to throw exceptions @@ -1112,7 +1113,7 @@ public class PolicyEngineManagerTest { } @Test - public void testShutdownThreadRun() throws Throwable { + void testShutdownThreadRun() throws Throwable { // arrange for first server to throw exceptions testShutdownThreadRun(() -> doThrow(new RuntimeException(EXPECTED)).when(server1).shutdown()); @@ -1148,7 +1149,7 @@ public class PolicyEngineManagerTest { } @Test - public void testIsAlive() { + void testIsAlive() { mgr.configure(properties); assertFalse(mgr.isAlive()); @@ -1160,7 +1161,7 @@ public class PolicyEngineManagerTest { } @Test - public void testLock() throws Throwable { + void testLock() throws Throwable { // normal success case testLock(true, () -> { // arrange for first provider to throw exceptions @@ -1237,7 +1238,7 @@ public class PolicyEngineManagerTest { } @Test - public void testUnlock() throws Throwable { + void testUnlock() throws Throwable { // normal success case testUnlock(true, () -> { // arrange for first provider to throw exceptions @@ -1314,7 +1315,7 @@ public class PolicyEngineManagerTest { } @Test - public void testIsLocked() { + void testIsLocked() { mgr.configure(properties); assertFalse(mgr.isLocked()); @@ -1326,31 +1327,31 @@ public class PolicyEngineManagerTest { } @Test - public void testRemovePolicyControllerString() { + void testRemovePolicyControllerString() { mgr.removePolicyController(MY_NAME); verify(controllerFactory).destroy(MY_NAME); } @Test - public void testRemovePolicyControllerPolicyController() { + void testRemovePolicyControllerPolicyController() { mgr.removePolicyController(controller); verify(controllerFactory).destroy(controller); } @Test - public void testGetPolicyControllers() { + void testGetPolicyControllers() { assertEquals(controllers, mgr.getPolicyControllers()); } @Test - public void testGetPolicyControllerIds() { + void testGetPolicyControllerIds() { assertEquals(Arrays.asList(CONTROLLER1, CONTROLLER2), mgr.getPolicyControllerIds()); } @Test - public void testGetProperties() { + void testGetProperties() { properties.setProperty("prop-x", "value-x"); properties.setProperty("prop-y", "value-y"); @@ -1359,35 +1360,35 @@ public class PolicyEngineManagerTest { } @Test - public void testGetSources() { + void testGetSources() { mgr.configure(properties); assertEquals(sources, mgr.getSources()); } @Test - public void testGetSinks() { + void testGetSinks() { mgr.configure(properties); assertEquals(sinks, mgr.getSinks()); } @Test - public void testGetHttpServers() { + void testGetHttpServers() { mgr.configure(properties); assertEquals(servers, mgr.getHttpServers()); } @Test - public void testGetFeatures() { + void testGetFeatures() { assertEquals(Arrays.asList(FEATURE1, FEATURE2), mgr.getFeatures()); } @Test - public void testGetFeatureProviders() { + void testGetFeatureProviders() { assertEquals(providers, mgr.getFeatureProviders()); } @Test - public void testGetFeatureProvider() { + void testGetFeatureProvider() { assertEquals(prov1, mgr.getFeatureProvider(FEATURE1)); assertEquals(prov2, mgr.getFeatureProvider(FEATURE2)); @@ -1402,7 +1403,7 @@ public class PolicyEngineManagerTest { } @Test - public void testTransaction() { + void testTransaction() { mgr.metric(CONTROLLER1, POLICY, new Metric()); assertEquals(0, mgr.getStats().getGroupStat().getPolicyExecutedCount()); assertEquals(0, mgr.getStats().getSubgroupStats().size()); @@ -1434,7 +1435,7 @@ public class PolicyEngineManagerTest { } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { mgr.onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, pdpConfigJson); verify(controllerFactory).patch(controller3, drools3); @@ -1448,7 +1449,7 @@ public class PolicyEngineManagerTest { } @Test - public void testDeliverStringObject() throws Exception { + void testDeliverStringObject() throws Exception { mgr.configure(properties); mgr.start(); @@ -1492,7 +1493,7 @@ public class PolicyEngineManagerTest { } @Test - public void testDeliverStringStringObject() { + void testDeliverStringStringObject() { mgr.configure(properties); mgr.start(); @@ -1523,7 +1524,7 @@ public class PolicyEngineManagerTest { } @Test - public void testDeliverCommInfrastructureStringObject() throws Exception { + void testDeliverCommInfrastructureStringObject() throws Exception { mgr.configure(properties); mgr.start(); @@ -1590,7 +1591,7 @@ public class PolicyEngineManagerTest { } @Test - public void testDeliverCommInfrastructureStringString() { + void testDeliverCommInfrastructureStringString() { mgr.configure(properties); // not started yet @@ -1622,7 +1623,7 @@ public class PolicyEngineManagerTest { } @Test - public void testActivate() throws Throwable { + void testActivate() throws Throwable { // normal success case testActivate(() -> { // arrange for first provider and controller to throw exceptions @@ -1679,7 +1680,7 @@ public class PolicyEngineManagerTest { } @Test - public void testDeactivate() throws Throwable { + void testDeactivate() throws Throwable { // normal success case testDeactivate(() -> { // arrange for first provider and controller to throw exceptions @@ -1733,7 +1734,7 @@ public class PolicyEngineManagerTest { } @Test - public void testCreateLock() { + void testCreateLock() { Lock lock = mock(Lock.class); LockCallback callback = mock(LockCallback.class); when(lockmgr.createLock(MY_RESOURCE, MY_OWNER, 10, callback, false)).thenReturn(lock); @@ -1759,7 +1760,7 @@ public class PolicyEngineManagerTest { } @Test - public void testOpen() throws Throwable { + void testOpen() throws Throwable { when(prov1.beforeOpen(mgr)).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterOpen(mgr)).thenThrow(new RuntimeException(EXPECTED)); @@ -1814,7 +1815,7 @@ public class PolicyEngineManagerTest { } @Test - public void testControllerConfig() throws Exception { + void testControllerConfig() throws Exception { mgr.configure(properties); assertTrue(mgr.configure(pdpConfig)); @@ -1845,7 +1846,7 @@ public class PolicyEngineManagerTest { } @Test - public void testToString() { + void testToString() { assertTrue(mgr.toString().startsWith("PolicyEngineManager(")); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java index 2054d91d..a6b8ac3f 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +22,9 @@ package org.onap.policy.drools.system; import static org.awaitility.Awaitility.await; -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.io.File; import java.io.IOException; @@ -32,11 +33,11 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import java.util.concurrent.TimeUnit; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; @@ -55,8 +56,8 @@ import org.slf4j.LoggerFactory; * PolicyEngine unit tests. */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class PolicyEngineTest { +@TestMethodOrder(MethodOrderer.DisplayName.class) +class PolicyEngineTest { /** * Default Telemetry port for JUnits. */ @@ -132,9 +133,9 @@ public class PolicyEngineTest { * * @throws IOException throws IO exception */ - @BeforeClass - public static void startUp() throws IOException { - logger.info("enter"); + @BeforeAll + static void startUp() throws IOException { + logger.info("startUp"); gson = new GsonTestUtils(); @@ -147,14 +148,8 @@ public class PolicyEngineTest { } } - @AfterClass - public static void tearDown() { - logger.info("enter"); - cleanUpWorkingDir(); - } - @Test - public void test100Configure() { + void test100Configure() { var manager = (PolicyEngineManager) PolicyEngineConstants.getManager(); var engineProps = manager.defaultTelemetryConfig(); @@ -177,7 +172,7 @@ public class PolicyEngineTest { } @Test - public void test200Start() { + void test200Start() { logger.info("enter"); PolicyEngineConstants.getManager().start(); @@ -189,7 +184,7 @@ public class PolicyEngineTest { } @Test - public void test300Lock() { + void test300Lock() { logger.info("enter"); PolicyEngineConstants.getManager().lock(); @@ -201,7 +196,7 @@ public class PolicyEngineTest { } @Test - public void test301Unlock() { + void test301Unlock() { logger.info("enter"); PolicyEngineConstants.getManager().unlock(); @@ -213,7 +208,7 @@ public class PolicyEngineTest { } @Test - public void test350TopicDeliver() { + void test350TopicDeliver() { final Properties noopSinkProperties = new Properties(); noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); @@ -236,7 +231,7 @@ public class PolicyEngineTest { } @Test - public void test400ControllerAdd() { + void test400ControllerAdd() { logger.info("enter"); final Properties controllerProperties = new Properties(); @@ -251,7 +246,7 @@ public class PolicyEngineTest { } @Test - public void test401ControllerVerify() { + void test401ControllerVerify() { logger.info("enter"); final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME); @@ -266,7 +261,7 @@ public class PolicyEngineTest { } @Test - public void test500Deactivate() { + void test500Deactivate() { logger.info("enter"); PolicyEngineConstants.getManager().deactivate(); @@ -279,7 +274,7 @@ public class PolicyEngineTest { } @Test - public void test501Activate() { + void test501Activate() { logger.info("enter"); PolicyEngineConstants.getManager().activate(); @@ -292,7 +287,7 @@ public class PolicyEngineTest { } @Test - public void test900ControllerRemove() { + void test900ControllerRemove() { logger.info("enter"); PolicyEngineConstants.getManager().removePolicyController(TEST_CONTROLLER_NAME); @@ -300,7 +295,7 @@ public class PolicyEngineTest { } @Test - public void test901Stop() { + void test901Stop() { logger.info("enter"); /* Shutdown managed resources */ diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/internal/AggregatedPolicyControllerTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/internal/AggregatedPolicyControllerTest.java index a6aa9d9d..bc81a3cb 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/internal/AggregatedPolicyControllerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/internal/AggregatedPolicyControllerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +24,11 @@ package org.onap.policy.drools.system.internal; import static org.assertj.core.api.Assertions.assertThatCode; 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.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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -39,8 +41,8 @@ import java.util.List; import java.util.Properties; import java.util.function.BiConsumer; import java.util.function.Consumer; -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.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; import org.onap.policy.common.endpoints.event.comm.TopicSink; @@ -53,7 +55,7 @@ import org.onap.policy.drools.persistence.SystemPersistence; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; import org.onap.policy.drools.system.GsonMgmtTestBuilder; -public class AggregatedPolicyControllerTest { +class AggregatedPolicyControllerTest { private static final String AGG_NAME = "agg-name"; private static final String SINK_TOPIC1 = "sink-a"; @@ -93,7 +95,7 @@ public class AggregatedPolicyControllerTest { /** * Initializes the object to be tested. */ - @Before + @BeforeEach public void setUp() { properties = new Properties(); @@ -144,7 +146,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testFactory() { + void testFactory() { apc = new AggregatedPolicyController(AGG_NAME, properties); assertNotNull(apc.getDroolsFactory()); assertNotNull(apc.getEndpointManager()); @@ -153,32 +155,34 @@ public class AggregatedPolicyControllerTest { } @Test - public void testAggregatedPolicyController_() { + void testAggregatedPolicyController_() { verify(persist).storeController(AGG_NAME, properties); } - @Test(expected = IllegalArgumentException.class) - public void testInitDrools_Ex() { + @Test + void testInitDrools_Ex() { + assertThrows(IllegalArgumentException.class, () -> new AggregatedPolicyControllerImpl(AGG_NAME, properties) { @Override protected DroolsControllerFactory getDroolsFactory() { throw new RuntimeException(EXPECTED); } - }; + }); } - @Test(expected = IllegalArgumentException.class) - public void testInitDrools_Error() { + @Test + void testInitDrools_Error() { + assertThrows(IllegalArgumentException.class, () -> new AggregatedPolicyControllerImpl(AGG_NAME, properties) { @Override protected DroolsControllerFactory getDroolsFactory() { throw new LinkageError(EXPECTED); } - }; + }); } @Test - public void testUpdateDrools_ConfigVariations() { + void testUpdateDrools_ConfigVariations() { // config should return same values as current controller when(config.getArtifactId()).thenReturn(ARTIFACT1.toUpperCase()); @@ -233,7 +237,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testUpdateDrools_LockVariations() { + void testUpdateDrools_LockVariations() { // not locked apc.updateDrools(config); verify(drools, never()).lock(); @@ -248,7 +252,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testUpdateDrools_AliveVariations() { + void testUpdateDrools_AliveVariations() { // not started apc.updateDrools(config); verify(drools, never()).start(); @@ -263,19 +267,19 @@ public class AggregatedPolicyControllerTest { } @Test - public void testSerialize() { + void testSerialize() { GsonTestUtils gson = new GsonMgmtTestBuilder().addDroolsControllerMock().addTopicSinkMock().addTopicSourceMock() .build(); assertThatCode(() -> gson.compareGson(apc, AggregatedPolicyControllerTest.class)).doesNotThrowAnyException(); } @Test - public void testGetName() { + void testGetName() { assertEquals(AGG_NAME, apc.getName()); } @Test - public void testStart() { + void testStart() { // arrange for first provider to throw exceptions when(prov1.beforeStart(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterStart(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -310,7 +314,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testStart_AlreadyStarted() { + void testStart_AlreadyStarted() { apc.start(); // re-start it @@ -329,7 +333,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testStart_Locked() { + void testStart_Locked() { apc.lock(); // start it @@ -347,7 +351,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testStop() { + void testStop() { // arrange for first provider to throw exceptions when(prov1.beforeStop(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterStop(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -387,7 +391,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testStop_AlreadyStopped() { + void testStop_AlreadyStopped() { apc.start(); apc.stop(); @@ -404,7 +408,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testShutdown() { + void testShutdown() { // arrange for first provider to throw exceptions when(prov1.beforeShutdown(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterShutdown(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -444,7 +448,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testHalt() { + void testHalt() { // arrange for first provider to throw exceptions when(prov1.beforeHalt(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterHalt(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -485,7 +489,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { // arrange for first provider to throw exceptions when(prov1.beforeOffer(apc, CommInfrastructure.NOOP, SOURCE_TOPIC1, MY_EVENT)) .thenThrow(new RuntimeException(EXPECTED)); @@ -522,7 +526,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testOnTopicEvent_Locked() { + void testOnTopicEvent_Locked() { // start it apc.start(); @@ -540,7 +544,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testOnTopicEvent_NotStarted() { + void testOnTopicEvent_NotStarted() { // offer it apc.onTopicEvent(CommInfrastructure.NOOP, SOURCE_TOPIC1, MY_EVENT); @@ -554,7 +558,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testDeliver_testInitSinks() { + void testDeliver_testInitSinks() { // arrange for first provider to throw exceptions when(prov1.beforeDeliver(apc, CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT)) .thenThrow(new RuntimeException(EXPECTED)); @@ -598,42 +602,43 @@ public class AggregatedPolicyControllerTest { prov -> verify(prov).afterDeliver(apc, CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT, true)); } - @Test(expected = IllegalArgumentException.class) - public void testDeliver_NullTopic() { - validateDeliverFailure(null, MY_EVENT); + @Test + void testDeliver_NullTopic() { + assertThrows(IllegalArgumentException.class, () -> validateDeliverFailure(null, MY_EVENT)); } - @Test(expected = IllegalArgumentException.class) - public void testDeliver_EmptyTopic() { - validateDeliverFailure("", MY_EVENT); + @Test + void testDeliver_EmptyTopic() { + assertThrows(IllegalArgumentException.class, () -> validateDeliverFailure("", MY_EVENT)); } - @Test(expected = IllegalArgumentException.class) - public void testDeliver_NullEvent() { - validateDeliverFailure(SINK_TOPIC1, null); + @Test + void testDeliver_NullEvent() { + assertThrows(IllegalArgumentException.class, () -> validateDeliverFailure(SINK_TOPIC1, null)); } - @Test(expected = IllegalStateException.class) - public void testDeliver_NotStarted() { + @Test + void testDeliver_NotStarted() { // do NOT start - apc.deliver(CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT); + assertThrows(IllegalStateException.class, () -> apc.deliver(CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT)); } - @Test(expected = IllegalStateException.class) - public void testDeliver_Locked() { + @Test + void testDeliver_Locked() { apc.start(); apc.lock(); - apc.deliver(CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT); + assertThrows(IllegalStateException.class, () -> apc.deliver(CommInfrastructure.NOOP, SINK_TOPIC1, MY_EVENT)); } - @Test(expected = IllegalArgumentException.class) - public void testDeliver_UnknownTopic() { + @Test + void testDeliver_UnknownTopic() { apc.start(); - apc.deliver(CommInfrastructure.NOOP, "unknown-topic", MY_EVENT); + assertThrows(IllegalArgumentException.class, + () -> apc.deliver(CommInfrastructure.NOOP, "unknown-topic", MY_EVENT)); } @Test - public void testIsAlive() { + void testIsAlive() { assertFalse(apc.isAlive()); apc.start(); @@ -644,7 +649,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testLock() { + void testLock() { // arrange for first provider to throw exceptions when(prov1.beforeLock(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterLock(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -678,7 +683,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testLock_AlreadyLocked() { + void testLock_AlreadyLocked() { apc.start(); apc.lock(); @@ -697,7 +702,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testUnlock() { + void testUnlock() { // arrange for first provider to throw exceptions when(prov1.beforeUnlock(any())).thenThrow(new RuntimeException(EXPECTED)); when(prov1.afterUnlock(any())).thenThrow(new RuntimeException(EXPECTED)); @@ -733,7 +738,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testUnlock_NotLocked() { + void testUnlock_NotLocked() { apc.start(); // now unlock it @@ -750,7 +755,7 @@ public class AggregatedPolicyControllerTest { } @Test - public void testIsLocked() { + void testIsLocked() { assertFalse(apc.isLocked()); apc.lock(); @@ -761,27 +766,27 @@ public class AggregatedPolicyControllerTest { } @Test - public void testGetTopicSources() { + void testGetTopicSources() { assertEquals(sources, apc.getTopicSources()); } @Test - public void testGetTopicSinks() { + void testGetTopicSinks() { assertEquals(sinks, apc.getTopicSinks()); } @Test - public void testGetDrools() { + void testGetDrools() { assertEquals(drools, apc.getDrools()); } @Test - public void testGetProperties() { + void testGetProperties() { assertEquals(properties, apc.getProperties()); } @Test - public void testToString() { + void testToString() { assertTrue(apc.toString().startsWith("AggregatedPolicyController(")); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/internal/FeatureLockImplTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/internal/FeatureLockImplTest.java index 2ba7cde9..23511abd 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/internal/FeatureLockImplTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/internal/FeatureLockImplTest.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ package org.onap.policy.drools.system.internal; 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.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.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.mock; import static org.mockito.Mockito.never; @@ -40,15 +40,18 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serial; import java.util.concurrent.ScheduledExecutorService; -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.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.drools.core.DroolsRunnable; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.core.lock.LockCallback; @@ -56,8 +59,8 @@ import org.onap.policy.drools.core.lock.LockState; import org.onap.policy.drools.system.PolicyEngineConstants; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class FeatureLockImplTest { +@ExtendWith(MockitoExtension.class) +class FeatureLockImplTest { private static final String POLICY_ENGINE_EXECUTOR_FIELD = "executorService"; private static final String OWNER_KEY = "my key"; private static final String RESOURCE = "my resource"; @@ -72,11 +75,13 @@ public class FeatureLockImplTest { @Mock private LockCallback callback; + AutoCloseable closeable; + /** * Saves static fields and configures the location of the property files. */ - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { saveExec = (ScheduledExecutorService) ReflectionTestUtils.getField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD); } @@ -84,8 +89,8 @@ public class FeatureLockImplTest { /** * Restores static fields. */ - @AfterClass - public static void tearDownAfterClass() { + @AfterAll + static void tearDownAfterClass() { ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, saveExec); } @@ -93,13 +98,19 @@ public class FeatureLockImplTest { * Initializes the mocks and creates a feature that uses {@link #exsvc} to execute * tasks. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, exsvc); } + @AfterEach + void closeMocks() throws Exception { + closeable.close(); + } + @Test - public void testNoArgs() { + void testNoArgs() { MyLock lock = new MyLock(); assertNull(lock.getResourceId()); assertNull(lock.getOwnerKey()); @@ -108,7 +119,7 @@ public class FeatureLockImplTest { } @Test - public void testFeatureLockImpl() { + void testFeatureLockImpl() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); assertTrue(lock.isWaiting()); assertEquals(RESOURCE, lock.getResourceId()); @@ -118,7 +129,7 @@ public class FeatureLockImplTest { } @Test - public void testSerializable() throws Exception { + void testSerializable() throws Exception { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock = roundTrip(lock); @@ -131,14 +142,14 @@ public class FeatureLockImplTest { } @Test - public void testGrant() { + void testGrant() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock.grant(); assertTrue(lock.isActive()); assertEquals(1, lock.nupdates); - invokeCallback(1); + invokeCallback(); verify(callback).lockAvailable(any()); verify(callback, never()).lockUnavailable(any()); } @@ -147,7 +158,7 @@ public class FeatureLockImplTest { * Tests grant() when the lock is already unavailable. */ @Test - public void testGrantUnavailable() { + void testGrantUnavailable() { MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock.setState(LockState.UNAVAILABLE); lock.grant(); @@ -159,13 +170,13 @@ public class FeatureLockImplTest { } @Test - public void testDeny() { + void testDeny() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock.deny("my reason"); assertTrue(lock.isUnavailable()); - invokeCallback(1); + invokeCallback(); verify(callback, never()).lockAvailable(any()); verify(callback).lockUnavailable(any()); } @@ -174,10 +185,11 @@ public class FeatureLockImplTest { * Tests doNotify() when a session exists. */ @Test - public void testDoNotifySession() { + void testDoNotifySession() { PolicySession session = mock(PolicySession.class); MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback) { + @Serial private static final long serialVersionUID = 1L; @Override @@ -207,20 +219,20 @@ public class FeatureLockImplTest { * Tests doNotify() when there is no session. */ @Test - public void testDoNotifyNoSession() { + void testDoNotifyNoSession() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock.grant(); assertTrue(lock.isActive()); assertEquals(1, lock.nupdates); - invokeCallback(1); + invokeCallback(); verify(callback).lockAvailable(any()); verify(callback, never()).lockUnavailable(any()); } @Test - public void testFreeAllowed() { + void testFreeAllowed() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); assertTrue(lock.freeAllowed()); } @@ -229,7 +241,7 @@ public class FeatureLockImplTest { * Tests freeAllowed() when the lock is unavailable. */ @Test - public void testFreeAllowedUnavailable() { + void testFreeAllowedUnavailable() { MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback); assertFalse(lock.freeAllowed()); assertTrue(lock.isUnavailable()); @@ -241,7 +253,7 @@ public class FeatureLockImplTest { * @throws Exception if an error occurs */ @Test - public void testFreeAllowedSerialized() throws Exception { + void testFreeAllowedSerialized() throws Exception { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock = roundTrip(lock); @@ -254,7 +266,7 @@ public class FeatureLockImplTest { * @throws Exception if an error occurs */ @Test - public void testFreeAllowedNoFeature() throws Exception { + void testFreeAllowedNoFeature() throws Exception { MyLock lock = new MyLockNoFeature(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock = roundTrip(lock); @@ -263,7 +275,7 @@ public class FeatureLockImplTest { } @Test - public void testExtendAllowed() { + void testExtendAllowed() { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); LockCallback scallback = mock(LockCallback.class); @@ -288,7 +300,7 @@ public class FeatureLockImplTest { * Tests extendAllowed() when the lock is unavailable. */ @Test - public void testExtendAllowedUnavailable() { + void testExtendAllowedUnavailable() { MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback); LockCallback scallback = mock(LockCallback.class); @@ -297,7 +309,7 @@ public class FeatureLockImplTest { assertEquals(HOLD_SEC2, lock.getHoldSec()); assertSame(scallback, lock.getCallback()); - invokeCallback(1); + invokeCallback(); verify(scallback, never()).lockAvailable(lock); verify(scallback).lockUnavailable(lock); } @@ -308,7 +320,7 @@ public class FeatureLockImplTest { * @throws Exception if an error occurs */ @Test - public void testExtendAllowedSerialized() throws Exception { + void testExtendAllowedSerialized() throws Exception { MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock = roundTrip(lock); @@ -328,7 +340,7 @@ public class FeatureLockImplTest { * @throws Exception if an error occurs */ @Test - public void testExtendAllowedNoFeature() throws Exception { + void testExtendAllowedNoFeature() throws Exception { MyLock lock = new MyLockNoFeature(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); lock = roundTrip(lock); @@ -339,21 +351,21 @@ public class FeatureLockImplTest { assertEquals(HOLD_SEC2, lock.getHoldSec()); assertSame(scallback, lock.getCallback()); - invokeCallback(1); + invokeCallback(); verify(scallback, never()).lockAvailable(lock); verify(scallback).lockUnavailable(lock); } @Test - public void testGetSession() { + void testGetSession() { MyLockStdSession lock = new MyLockStdSession(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback); // this should invoke the real policy session without throwing an exception - assertThatCode(() -> lock.grant()).doesNotThrowAnyException(); + assertThatCode(lock::grant).doesNotThrowAnyException(); } @Test - public void testToString() { + void testToString() { String text = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback).toString(); assertNotNull(text); assertThat(text).contains("LockImpl"); @@ -374,21 +386,18 @@ public class FeatureLockImplTest { /** * Invokes the last call-back in the work queue. * - * @param nexpected number of call-backs expected in the work queue */ - private void invokeCallback(int nexpected) { + private void invokeCallback() { ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(exsvc, times(nexpected)).execute(captor.capture()); - - if (nexpected > 0) { - captor.getAllValues().get(nexpected - 1).run(); - } + verify(exsvc, times(1)).execute(captor.capture()); + captor.getAllValues().get(0).run(); } /** * Lock that inherits the normal getSession() method. */ public static class MyLockStdSession extends FeatureLockImpl { + @Serial private static final long serialVersionUID = 1L; protected int nupdates = 0; @@ -424,6 +433,7 @@ public class FeatureLockImplTest { } public static class MyLock extends MyLockStdSession { + @Serial private static final long serialVersionUID = 1L; public MyLock() { @@ -441,6 +451,7 @@ public class FeatureLockImplTest { } public static class MyLockNoFeature extends MyLock { + @Serial private static final long serialVersionUID = 1L; public MyLockNoFeature() { diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/internal/LockManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/internal/LockManagerTest.java index 3617c445..74e1a9c1 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/internal/LockManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/internal/LockManagerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +21,10 @@ package org.onap.policy.drools.system.internal; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -31,10 +33,11 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.Serial; import java.util.concurrent.ScheduledExecutorService; -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.onap.policy.drools.core.lock.AlwaysFailLock; @@ -42,7 +45,7 @@ import org.onap.policy.drools.core.lock.Lock; import org.onap.policy.drools.core.lock.LockCallback; import org.onap.policy.drools.core.lock.LockState; -public class LockManagerTest { +class LockManagerTest { private static final String OWNER_KEY = "my key"; private static final String RESOURCE = "my resource"; private static final String RESOURCE2 = "my resource #2"; @@ -56,12 +59,14 @@ public class LockManagerTest { private MyManager mgr; + private AutoCloseable closeable; + /** * Resets fields and creates {@link #mgr}. */ - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.openMocks(this); + closeable = MockitoAnnotations.openMocks(this); doAnswer(args -> { args.getArgument(0, Runnable.class).run(); @@ -71,13 +76,13 @@ public class LockManagerTest { mgr = new MyManager(); } - @After - public void tearDown() { - + @AfterEach + public void tearDown() throws Exception { + closeable.close(); } @Test - public void testIsAlive() { + void testIsAlive() { assertFalse(mgr.isAlive()); assertFalse(mgr.isLocked()); @@ -90,7 +95,7 @@ public class LockManagerTest { } @Test - public void testStart() { + void testStart() { assertTrue(mgr.start()); assertTrue(mgr.isAlive()); @@ -103,7 +108,7 @@ public class LockManagerTest { } @Test - public void testStop() { + void testStop() { assertFalse(mgr.stop()); mgr.start(); @@ -112,7 +117,7 @@ public class LockManagerTest { } @Test - public void testShutdown() { + void testShutdown() { mgr.start(); mgr.shutdown(); assertFalse(mgr.isAlive()); @@ -122,7 +127,7 @@ public class LockManagerTest { } @Test - public void testIsLocked() { + void testIsLocked() { assertFalse(mgr.isLocked()); assertFalse(mgr.isAlive()); @@ -135,7 +140,7 @@ public class LockManagerTest { } @Test - public void testLock() { + void testLock() { assertTrue(mgr.lock()); assertTrue(mgr.isLocked()); @@ -148,7 +153,7 @@ public class LockManagerTest { } @Test - public void testUnlock() { + void testUnlock() { assertFalse(mgr.unlock()); mgr.lock(); @@ -157,7 +162,7 @@ public class LockManagerTest { } @Test - public void testCreateLock() { + void testCreateLock() { Lock lock = mgr.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); assertTrue(lock.isActive()); verify(callback).lockAvailable(lock); @@ -182,12 +187,12 @@ public class LockManagerTest { * Tests createLock() when the feature instance has changed. */ @Test - public void testCreateLockInstanceChanged() { + void testCreateLockInstanceChanged() { mgr = spy(mgr); when(mgr.hasInstanceChanged()).thenReturn(true); Lock lock = mgr.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); - assertTrue(lock instanceof AlwaysFailLock); + assertInstanceOf(AlwaysFailLock.class, lock); assertTrue(lock.isUnavailable()); verify(callback, never()).lockAvailable(lock); @@ -195,7 +200,7 @@ public class LockManagerTest { } @Test - public void testGetResource2lock() { + void testGetResource2lock() { assertNotNull(mgr.getResource2lock()); } @@ -220,6 +225,7 @@ public class LockManagerTest { } private class MyLock extends FeatureLockImpl { + @Serial private static final long serialVersionUID = 1L; public MyLock(LockState waiting, String resourceId, String ownerKey, int holdSec, LockCallback callback) { diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerExceptionTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerExceptionTest.java index 3e4e5762..fdf840b2 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerExceptionTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerExceptionTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +21,15 @@ package org.onap.policy.drools.system.internal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; -public class SimpleLockManagerExceptionTest extends ExceptionsTester { +class SimpleLockManagerExceptionTest extends ExceptionsTester { @Test - public void test() { + void test() { assertEquals(1, test(SimpleLockManagerException.class)); } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerTest.java index 4491a73b..3ee5583a 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/internal/SimpleLockManagerTest.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,12 @@ 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.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.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.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.ArgumentMatchers.anyLong; @@ -44,6 +44,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serial; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -53,15 +54,17 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -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.junit.jupiter.api.extension.ExtendWith; import org.kie.api.runtime.KieSession; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.utils.time.CurrentTime; import org.onap.policy.common.utils.time.TestTime; import org.onap.policy.drools.core.PolicySession; @@ -72,8 +75,8 @@ import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.drools.system.internal.SimpleLockManager.SimpleLock; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class SimpleLockManagerTest { +@ExtendWith(MockitoExtension.class) +class SimpleLockManagerTest { private static final String POLICY_ENGINE_EXECUTOR_FIELD = "executorService"; private static final String TIME_FIELD = "currentTime"; private static final String OWNER_KEY = "my key"; @@ -91,7 +94,6 @@ public class SimpleLockManagerTest { private static ScheduledExecutorService saveExec; private static ScheduledExecutorService realExec; - private PolicySession session; private TestTime testTime; private AtomicInteger nactive; private AtomicInteger nsuccesses; @@ -109,11 +111,13 @@ public class SimpleLockManagerTest { @Mock private LockCallback callback; + AutoCloseable closeable; + /** * Saves static fields and configures the location of the property files. */ - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { saveTime = (CurrentTime) ReflectionTestUtils.getField(SimpleLockManager.class, TIME_FIELD); saveExec = (ScheduledExecutorService) ReflectionTestUtils.getField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD); @@ -124,8 +128,8 @@ public class SimpleLockManagerTest { /** * Restores static fields. */ - @AfterClass - public static void tearDownAfterClass() { + @AfterAll + static void tearDownAfterClass() { ReflectionTestUtils.setField(SimpleLockManager.class, TIME_FIELD, saveTime); ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, saveExec); @@ -136,10 +140,11 @@ public class SimpleLockManagerTest { * Initializes the mocks and creates a feature that uses {@link #exsvc} to execute * tasks. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); // grant() and deny() calls will come through here and be immediately executed - session = new PolicySession(null, null, kieSess) { + PolicySession session = new PolicySession(null, null, kieSess) { @Override public void insertDrools(Object object) { ((Runnable) object).run(); @@ -160,11 +165,16 @@ public class SimpleLockManagerTest { feature.start(); } + @AfterEach + void closeMocks() throws Exception { + closeable.close(); + } + /** * Tests constructor() when properties are invalid. */ @Test - public void testSimpleLockManagerInvalidProperties() { + void testSimpleLockManagerInvalidProperties() { // use properties containing an invalid value Properties props = new Properties(); props.setProperty(SimpleLockProperties.EXPIRE_CHECK_SEC, "abc"); @@ -173,7 +183,7 @@ public class SimpleLockManagerTest { } @Test - public void testStart() { + void testStart() { assertTrue(feature.isAlive()); verify(exsvc).scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()); @@ -184,7 +194,7 @@ public class SimpleLockManagerTest { } @Test - public void testStop() { + void testStop() { assertTrue(feature.stop()); assertFalse(feature.isAlive()); verify(future).cancel(true); @@ -196,16 +206,16 @@ public class SimpleLockManagerTest { } @Test - public void testShutdown() { + void testShutdown() { feature.shutdown(); verify(future).cancel(true); } @Test - public void testCreateLock() { + void testCreateLock() { // this lock should be granted immediately - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); assertTrue(lock.isActive()); assertEquals(testTime.getMillis() + HOLD_MS, lock.getHoldUntilMs()); @@ -236,7 +246,7 @@ public class SimpleLockManagerTest { * Tests createLock() when the feature is not the latest instance. */ @Test - public void testCreateLockNotLatestInstance() { + void testCreateLockNotLatestInstance() { SimpleLockManager.setLatestInstance(null); Lock lock = feature.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); @@ -246,10 +256,10 @@ public class SimpleLockManagerTest { } @Test - public void testCheckExpired() throws InterruptedException { - final SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); - final SimpleLock lock2 = getLock(RESOURCE2, OWNER_KEY, HOLD_SEC, callback, false); - final SimpleLock lock3 = getLock(RESOURCE3, OWNER_KEY, HOLD_SEC2, callback, false); + void testCheckExpired() throws InterruptedException { + final SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); + final SimpleLock lock2 = getLock(RESOURCE2, HOLD_SEC, callback); + final SimpleLock lock3 = getLock(RESOURCE3, HOLD_SEC2, callback); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); verify(exsvc).scheduleWithFixedDelay(captor.capture(), anyLong(), anyLong(), any()); @@ -292,15 +302,15 @@ public class SimpleLockManagerTest { * Tests checkExpired(), where the lock is removed from the map between invoking * expired() and compute(). Should cause "null" to be returned by compute(). * - * @throws InterruptedException if the test is interrupted */ @Test - public void testCheckExpiredLockDeleted() throws InterruptedException { + void testCheckExpiredLockDeleted() { feature = new MyLockingFeature() { @Override protected SimpleLock makeLock(LockState waiting, String resourceId, String ownerKey, int holdSec, LockCallback callback) { return new SimpleLock(waiting, resourceId, ownerKey, holdSec, callback, feature) { + @Serial private static final long serialVersionUID = 1L; @Override @@ -343,7 +353,7 @@ public class SimpleLockManagerTest { * @throws InterruptedException if the test is interrupted */ @Test - public void testCheckExpiredLockReplaced() throws InterruptedException { + void testCheckExpiredLockReplaced() throws InterruptedException { feature = new MyLockingFeature() { private boolean madeLock = false; @@ -357,6 +367,7 @@ public class SimpleLockManagerTest { madeLock = true; return new SimpleLock(waiting, resourceId, ownerKey, holdSec, callback, feature) { + @Serial private static final long serialVersionUID = 1L; @Override @@ -388,7 +399,7 @@ public class SimpleLockManagerTest { } @Test - public void testGetThreadPool() { + void testGetThreadPool() { // use a real feature feature = new SimpleLockManager(null, new Properties()); @@ -403,7 +414,7 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockNoArgs() { + void testSimpleLockNoArgs() { SimpleLock lock = new SimpleLock(); assertNull(lock.getResourceId()); assertNull(lock.getOwnerKey()); @@ -414,8 +425,8 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockSimpleLock() { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockSimpleLock() { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); assertEquals(RESOURCE, lock.getResourceId()); assertEquals(OWNER_KEY, lock.getOwnerKey()); assertSame(callback, lock.getCallback()); @@ -427,8 +438,8 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockSerializable() throws Exception { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockSerializable() throws Exception { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); lock = roundTrip(lock); assertTrue(lock.isActive()); @@ -440,8 +451,8 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockExpired() { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockExpired() { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); lock.grant(); assertFalse(lock.expired(testTime.getMillis())); @@ -450,11 +461,11 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockFree() { - final SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockFree() { + final SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); // lock2 should be denied - SimpleLock lock2 = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + SimpleLock lock2 = getLock(RESOURCE, HOLD_SEC, callback); verify(callback, never()).lockAvailable(lock2); verify(callback).lockUnavailable(lock2); @@ -470,7 +481,7 @@ public class SimpleLockManagerTest { assertEquals(LockState.UNAVAILABLE, lock.getState()); // should be able to get the lock now - SimpleLock lock3 = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + SimpleLock lock3 = getLock(RESOURCE, HOLD_SEC, callback); assertTrue(lock3.isActive()); verify(callback).lockAvailable(lock3); @@ -483,8 +494,8 @@ public class SimpleLockManagerTest { * @throws Exception if an error occurs */ @Test - public void testSimpleLockFreeSerialized() throws Exception { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockFreeSerialized() throws Exception { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); feature = new MyLockingFeature(); feature.start(); @@ -495,11 +506,11 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockExtend() { - final SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockExtend() { + final SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); // lock2 should be denied - SimpleLock lock2 = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + SimpleLock lock2 = getLock(RESOURCE, HOLD_SEC, callback); verify(callback, never()).lockAvailable(lock2); verify(callback).lockUnavailable(lock2); @@ -529,8 +540,8 @@ public class SimpleLockManagerTest { * @throws Exception if an error occurs */ @Test - public void testSimpleLockExtendSerialized() throws Exception { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockExtendSerialized() throws Exception { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); feature = new MyLockingFeature(); feature.start(); @@ -551,8 +562,8 @@ public class SimpleLockManagerTest { * @throws Exception if an error occurs */ @Test - public void testSimpleLockExtendNoFeature() throws Exception { - SimpleLock lock = getLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + void testSimpleLockExtendNoFeature() throws Exception { + SimpleLock lock = getLock(RESOURCE, HOLD_SEC, callback); SimpleLockManager.setLatestInstance(null); @@ -567,7 +578,7 @@ public class SimpleLockManagerTest { } @Test - public void testSimpleLockToString() { + void testSimpleLockToString() { String text = feature.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false).toString(); assertNotNull(text); assertThat(text).contains("holdUntil").doesNotContain("ownerInfo").doesNotContain("callback"); @@ -580,7 +591,7 @@ public class SimpleLockManagerTest { * the background threads to complete */ @Test - public void testMultiThreaded() throws InterruptedException { + void testMultiThreaded() throws InterruptedException { ReflectionTestUtils.setField(SimpleLockManager.class, TIME_FIELD, testTime); ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, realExec); feature = new SimpleLockManager(null, new Properties()); @@ -607,9 +618,8 @@ public class SimpleLockManagerTest { assertTrue(nsuccesses.get() > 0); } - private SimpleLock getLock(String resource, String ownerKey, int holdSec, LockCallback callback, - boolean waitForLock) { - return (SimpleLock) feature.createLock(resource, ownerKey, holdSec, callback, waitForLock); + private SimpleLock getLock(String resource, int holdSec, LockCallback callback) { + return (SimpleLock) feature.createLock(resource, SimpleLockManagerTest.OWNER_KEY, holdSec, callback, false); } private SimpleLock roundTrip(SimpleLock lock) throws Exception { @@ -646,7 +656,7 @@ public class SimpleLockManagerTest { } /** - * Thread used with the multi-threaded test. It repeatedly attempts to get a lock, + * Thread used with the multithreaded test. It repeatedly attempts to get a lock, * extend it, and then unlock it. */ private class MyThread extends Thread { |