diff --git a/artemis-cdi-client/pom.xml b/artemis-cdi-client/pom.xml index 728d1d33a3..dddcc9c5a5 100644 --- a/artemis-cdi-client/pom.xml +++ b/artemis-cdi-client/pom.xml @@ -80,8 +80,9 @@ arquillian-junit-core - junit - junit + org.junit.vintage + junit-vintage-engine + test jakarta.jms diff --git a/artemis-cli/pom.xml b/artemis-cli/pom.xml index 6c8b4648bf..f8143850b6 100644 --- a/artemis-cli/pom.xml +++ b/artemis-cli/pom.xml @@ -150,8 +150,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-cli/src/test/java/org/apache/activemq/SecurityManagerHandlerTest.java b/artemis-cli/src/test/java/org/apache/activemq/SecurityManagerHandlerTest.java index ce216a2e38..1647d63c91 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/SecurityManagerHandlerTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/SecurityManagerHandlerTest.java @@ -19,7 +19,7 @@ package org.apache.activemq; import org.apache.activemq.artemis.cli.factory.security.SecurityManagerHandler; import org.apache.activemq.artemis.dto.SecurityManagerDTO; import org.apache.activemq.artemis.spi.core.security.ActiveMQBasicSecurityManager; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SecurityManagerHandlerTest { diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/CreateTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/CreateTest.java index 1991eb4212..7b980e6b4a 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/CreateTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/CreateTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.cli.commands; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import java.io.File; @@ -23,16 +25,16 @@ import java.io.IOException; import java.util.Arrays; import java.util.Collection; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.utils.XmlProvider; import org.apache.activemq.cli.test.CliTestBase; import org.apache.activemq.cli.test.TestActionContext; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.xml.sax.SAXException; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class CreateTest extends CliTestBase { private final String testName; @@ -45,7 +47,7 @@ public class CreateTest extends CliTestBase { this.relaxJolokia = relaxJolokia; } - @Parameterized.Parameters(name = "{0}") + @Parameters(name = "{0}") public static Collection testData() { return Arrays.asList(new Object[][]{ {"Happy path + relaxJolokia", "sampledomain.com", true}, @@ -61,10 +63,10 @@ public class CreateTest extends CliTestBase { }); } - @Test + @TestTemplate public void testWriteJolokiaAccessXmlCreatesValidXml() throws Exception { TestActionContext context = new TestActionContext(); - File testInstance = new File(temporaryFolder.getRoot(), "test-instance"); + File testInstance = new File(temporaryFolder, "test-instance"); Create c = new Create(); c.setNoAutoTune(true); @@ -73,7 +75,7 @@ public class CreateTest extends CliTestBase { c.setRelaxJolokia(relaxJolokia); c.execute(context); - Assert.assertTrue(isXmlValid(new File(testInstance, "etc/" + Create.ETC_JOLOKIA_ACCESS_XML))); + assertTrue(isXmlValid(new File(testInstance, "etc/" + Create.ETC_JOLOKIA_ACCESS_XML))); } /** diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ConnectionAbstractTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ConnectionAbstractTest.java index fbe060ad12..2d3e659ba5 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ConnectionAbstractTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ConnectionAbstractTest.java @@ -16,12 +16,13 @@ */ package org.apache.activemq.artemis.cli.commands.messages; +import static org.junit.jupiter.api.Assertions.assertEquals; + import javax.jms.JMSException; import org.apache.activemq.artemis.cli.commands.ActionAbstractAccessor; import org.apache.activemq.cli.test.TestActionContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; @@ -40,7 +41,7 @@ public class ConnectionAbstractTest { connectionAbstract.execute(new TestActionContext()); - Assert.assertEquals(ConnectionAbstract.DEFAULT_BROKER_URL, connectionAbstract.getBrokerURL()); + assertEquals(ConnectionAbstract.DEFAULT_BROKER_URL, connectionAbstract.getBrokerURL()); } finally { System.clearProperty("artemis.instance.etc"); } @@ -62,10 +63,10 @@ public class ConnectionAbstractTest { connectionAbstract.execute(new TestActionContext()); } catch (Exception e) { e.printStackTrace(); - Assert.assertEquals(JMSException.class, e.getClass()); + assertEquals(JMSException.class, e.getClass()); } - Assert.assertEquals("tcp://localhost:3344", connectionAbstract.getBrokerURL()); + assertEquals("tcp://localhost:3344", connectionAbstract.getBrokerURL()); } finally { System.clearProperty("artemis.instance.etc"); } @@ -86,7 +87,7 @@ public class ConnectionAbstractTest { connectionAbstract.execute(new TestActionContext()); - Assert.assertEquals("tcp://localhost:5672", connectionAbstract.getBrokerURL()); + assertEquals("tcp://localhost:5672", connectionAbstract.getBrokerURL()); } finally { System.clearProperty("artemis.instance.etc"); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ProducerThreadTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ProducerThreadTest.java index 1b1988f7d5..3936936269 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ProducerThreadTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/ProducerThreadTest.java @@ -16,25 +16,25 @@ */ package org.apache.activemq.artemis.cli.commands.messages; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.JMSException; import javax.jms.Message; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.cli.test.TestActionContext; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - public class ProducerThreadTest { ProducerThread producer; Message mockMessage; - @Before + @BeforeEach public void setUp() { producer = new ProducerThread(null, ActiveMQDestination.createQueue(RandomUtil.randomString()), 0, null); mockMessage = Mockito.mock(Message.class); diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/TransferTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/TransferTest.java index 99e0381e15..ca6b96d084 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/TransferTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/messages/TransferTest.java @@ -16,10 +16,11 @@ */ package org.apache.activemq.artemis.cli.commands.messages; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.cli.commands.ActionAbstractAccessor; import org.apache.activemq.cli.test.TestActionContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.jms.JMSException; import java.io.File; @@ -40,10 +41,10 @@ public class TransferTest { try { transfer.execute(new TestActionContext()); } catch (Exception e) { - Assert.assertEquals(JMSException.class, e.getClass()); + assertEquals(JMSException.class, e.getClass()); } - Assert.assertEquals(ConnectionAbstract.DEFAULT_BROKER_URL, transfer.getSourceURL()); + assertEquals(ConnectionAbstract.DEFAULT_BROKER_URL, transfer.getSourceURL()); } finally { System.clearProperty("artemis.instance.etc"); } @@ -67,10 +68,10 @@ public class TransferTest { transfer.execute(new TestActionContext()); } catch (Exception e) { e.printStackTrace(); - Assert.assertEquals(JMSException.class, e.getClass()); + assertEquals(JMSException.class, e.getClass()); } - Assert.assertEquals("tcp://localhost:3344", transfer.getSourceURL()); + assertEquals("tcp://localhost:3344", transfer.getSourceURL()); } finally { System.clearProperty("artemis.instance.etc"); } @@ -91,10 +92,10 @@ public class TransferTest { try { transfer.execute(new TestActionContext()); } catch (Exception e) { - Assert.assertEquals(JMSException.class, e.getClass()); + assertEquals(JMSException.class, e.getClass()); } - Assert.assertEquals("tcp://localhost:5672", transfer.getSourceURL()); + assertEquals("tcp://localhost:5672", transfer.getSourceURL()); } finally { System.clearProperty("artemis.instance.etc"); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporterTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporterTest.java index 8ae4f72152..6e6d43220a 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporterTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporterTest.java @@ -16,30 +16,30 @@ */ package org.apache.activemq.artemis.cli.commands.tools.xml; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.InputStream; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.management.ManagementContext; import org.apache.activemq.cli.test.CliTestBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class XmlDataImporterTest extends CliTestBase { ActiveMQServer server; - @Before + @BeforeEach @Override public void setup() throws Exception { super.setup(); server = ((Pair)startServer()).getB(); } - @After + @AfterEach @Override public void tearDown() throws Exception { stopServer(); diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/integration/bootstrap/BootstrapLogBundleTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/integration/bootstrap/BootstrapLogBundleTest.java index 44c26c7da4..136aafb5f9 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/integration/bootstrap/BootstrapLogBundleTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/integration/bootstrap/BootstrapLogBundleTest.java @@ -16,25 +16,25 @@ */ package org.apache.activemq.artemis.integration.bootstrap; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class BootstrapLogBundleTest { private static final String LOGGER_NAME = ActiveMQBootstrapLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.DEBUG); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/artemis/util/JVMArgumentTest.java b/artemis-cli/src/test/java/org/apache/activemq/artemis/util/JVMArgumentTest.java index 7c8fe75a6f..747aacae0c 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/artemis/util/JVMArgumentTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/artemis/util/JVMArgumentTest.java @@ -17,10 +17,13 @@ package org.apache.activemq.artemis.util; +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.HashMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JVMArgumentTest { @@ -34,9 +37,9 @@ public class JVMArgumentTest { HashMap usedArgs = new HashMap<>(); JVMArgumentParser.parseOriginalArgs(prefix, "\"", arguments, fixedArguments, usedArgs); - Assert.assertEquals(2, usedArgs.size()); - Assert.assertEquals("-Xmx77G", usedArgs.get("-Xmx")); - Assert.assertEquals("-Xms333M", usedArgs.get("-Xms")); + assertEquals(2, usedArgs.size()); + assertEquals("-Xmx77G", usedArgs.get("-Xmx")); + assertEquals("-Xms333M", usedArgs.get("-Xms")); String newLine = "IF \"%JAVA_ARGS%\"==\"\" (set JAVA_ARGS= -XX:AutoBoxCacheMax=20000 -XX:+PrintClassHistogram -XX:+UseG1GC -XX:+UseStringDeduplication -Xms512M -Xmx1G -Djava.security.auth.login.config=%ARTEMIS_ETC_DIR%\\login.config -Dhawtio.disableProxy=true -Dhawtio.offline=true -Dhawtio.realm=activemq -Dhawtio.role=amq -Dhawtio.rolePrincipalClasses=org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal -Djolokia.policyLocation=%ARTEMIS_INSTANCE_ETC_URI%\\jolokia-access.xml -Dartemis.instance=%ARTEMIS_INSTANCE%)"; @@ -44,11 +47,11 @@ public class JVMArgumentTest { System.out.println("output::" + resultLine); - Assert.assertFalse(resultLine.contains("-must-go")); - Assert.assertTrue(resultLine.contains("-Xmx77G")); - Assert.assertTrue(resultLine.contains("-Xms333M")); - Assert.assertFalse(resultLine.contains("-Xmx1G")); - Assert.assertFalse(resultLine.contains("-Xmx512M")); + assertFalse(resultLine.contains("-must-go")); + assertTrue(resultLine.contains("-Xmx77G")); + assertTrue(resultLine.contains("-Xms333M")); + assertFalse(resultLine.contains("-Xmx1G")); + assertFalse(resultLine.contains("-Xmx512M")); } @@ -62,9 +65,9 @@ public class JVMArgumentTest { HashMap usedArgs = new HashMap<>(); JVMArgumentParser.parseOriginalArgs(prefix, "\"", arguments, fixedArguments, usedArgs); - Assert.assertEquals(2, usedArgs.size()); - Assert.assertEquals("-Xmx77G", usedArgs.get("-Xmx")); - Assert.assertEquals("-Xms333M", usedArgs.get("-Xms")); + assertEquals(2, usedArgs.size()); + assertEquals("-Xmx77G", usedArgs.get("-Xmx")); + assertEquals("-Xms333M", usedArgs.get("-Xms")); String newLine = " JAVA_ARGS= -XX:AutoBoxCacheMax=20000 -XX:+PrintClassHistogram -XX:+UseG1GC -XX:+UseStringDeduplication -Xms512M -Xmx1G -Djava.security.auth.login.config=%ARTEMIS_ETC_DIR%\\login.config -Dhawtio.disableProxy=true -Dhawtio.offline=true -Dhawtio.realm=activemq -Dhawtio.role=amq -Dhawtio.rolePrincipalClasses=org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal -Djolokia.policyLocation=%ARTEMIS_INSTANCE_ETC_URI%\\jolokia-access.xml -Dartemis.instance=%ARTEMIS_INSTANCE%)"; @@ -72,13 +75,13 @@ public class JVMArgumentTest { System.out.println("output::" + resultLine); - Assert.assertFalse(resultLine.contains("-must-go")); - Assert.assertTrue(resultLine.contains("-Xmx77G")); - Assert.assertTrue(resultLine.contains("-Xms333M")); - Assert.assertFalse(resultLine.contains("-Xmx1G")); - Assert.assertFalse(resultLine.contains("-Xmx512M")); + assertFalse(resultLine.contains("-must-go")); + assertTrue(resultLine.contains("-Xmx77G")); + assertTrue(resultLine.contains("-Xms333M")); + assertFalse(resultLine.contains("-Xmx1G")); + assertFalse(resultLine.contains("-Xmx512M")); - Assert.assertTrue(resultLine.startsWith(" ")); + assertTrue(resultLine.startsWith(" ")); } } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java index 2172716399..f977bb6d1d 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ArtemisTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.cli.test; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Message; @@ -24,10 +31,6 @@ import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; - -import org.apache.activemq.artemis.api.core.QueueConfiguration; -import org.apache.activemq.artemis.json.JsonArray; -import org.apache.activemq.artemis.json.JsonObject; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; @@ -47,12 +50,16 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; +import org.apache.activemq.artemis.json.JsonArray; +import org.apache.activemq.artemis.json.JsonObject; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.Pair; +import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; @@ -97,10 +104,10 @@ import org.apache.activemq.artemis.utils.XmlProvider; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Configurations; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -110,11 +117,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - /** * Test to validate that the CLI doesn't throw improper exceptions when invoked. */ @@ -123,33 +125,35 @@ public class ArtemisTest extends CliTestBase { // some tests will set this, as some security methods will need to know the server the CLI started private ActiveMQServer server; + long timeBefore; - @Before + @BeforeEach @Override public void setup() throws Exception { setupAuth(); + setupScanTimeout(); + super.setup(); } - long timeBefore; - - @Before - public void setupScanTimeout() throws Exception { + private void setupScanTimeout() throws Exception { timeBefore = ActiveMQDefaultConfiguration.getDefaultAddressQueueScanPeriod(); org.apache.activemq.artemis.api.config.ActiveMQDefaultConfigurationTestAccessor.setDefaultAddressQueueScanPeriod(100); } - @After + @AfterEach public void resetScanTimeout() throws Exception { org.apache.activemq.artemis.api.config.ActiveMQDefaultConfigurationTestAccessor.setDefaultAddressQueueScanPeriod(timeBefore); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void invalidCliDoesntThrowException() { testCli("--silent", "create"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void invalidPathDoesntThrowException() { if (isWindows()) { testCli("create", "zzzzz:/rawr", "--silent"); @@ -158,18 +162,20 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSupportsLibaio() throws Exception { Create x = new Create(); x.setInstance(new File("/tmp/foo")); x.supportsLibaio(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSync() throws Exception { int writes = 2; int tries = 5; - long totalAvg = SyncCalculation.syncTest(temporaryFolder.getRoot(), 4096, writes, tries, true, true, true, "file.tmp", 1, JournalType.NIO, new TestActionContext()); + long totalAvg = SyncCalculation.syncTest(temporaryFolder, 4096, writes, tries, true, true, true, "file.tmp", 1, JournalType.NIO, new TestActionContext()); logger.debug("TotalAvg = {}", totalAvg); long nanoTime = SyncCalculation.toNanos(totalAvg, writes, false, null); logger.debug("nanoTime avg = {}", nanoTime); @@ -177,26 +183,29 @@ public class ArtemisTest extends CliTestBase { } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSimpleCreate() throws Exception { //instance1: default using http - File instance1 = new File(temporaryFolder.getRoot(), "instance1"); + File instance1 = new File(temporaryFolder, "instance1"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testCreateDB() throws Exception { - File instance1 = new File(temporaryFolder.getRoot(), "instance1"); + File instance1 = new File(temporaryFolder, "instance1"); Artemis.internalExecute("create", instance1.getAbsolutePath(), "--silent", "--jdbc"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSimpleCreateMapped() throws Throwable { try { //instance1: default using http - File instance1 = new File(temporaryFolder.getRoot(), "instance1"); + File instance1 = new File(temporaryFolder, "instance1"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--mapped", "--no-autotune"); } catch (Throwable e) { e.printStackTrace(); @@ -204,30 +213,32 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testOpenwireSupportAdvisoryDisabledByDefault() throws Exception { FileConfiguration configuration = createFileConfiguration("supportAdvisory", "--force", "--silent", "--no-web", "--no-autotune"); Map params = configuration.getAcceptorConfigurations() .stream().filter(tc -> tc.getName().equals("artemis")).findFirst().get().getExtraParams(); - Assert.assertFalse(Boolean.parseBoolean(params.get("supportAdvisory").toString())); - Assert.assertFalse(Boolean.parseBoolean(params.get("suppressInternalManagementObjects").toString())); + assertFalse(Boolean.parseBoolean(params.get("supportAdvisory").toString())); + assertFalse(Boolean.parseBoolean(params.get("suppressInternalManagementObjects").toString())); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testOpenwireEnabledSupportAdvisory() throws Exception { FileConfiguration configuration = createFileConfiguration("supportAdvisory", "--force", "--silent", "--no-web", "--no-autotune", "--support-advisory", "--suppress-internal-management-objects"); Map params = configuration.getAcceptorConfigurations() .stream().filter(tc -> tc.getName().equals("artemis")).findFirst().get().getExtraParams(); - Assert.assertTrue(Boolean.parseBoolean(params.get("supportAdvisory").toString())); - Assert.assertTrue(Boolean.parseBoolean(params.get("suppressInternalManagementObjects").toString())); + assertTrue(Boolean.parseBoolean(params.get("supportAdvisory").toString())); + assertTrue(Boolean.parseBoolean(params.get("suppressInternalManagementObjects").toString())); } private FileConfiguration createFileConfiguration(String folder, String... createAdditionalArg) throws Exception { - File instanceFolder = temporaryFolder.newFolder(folder); + File instanceFolder = newFolder(temporaryFolder, folder); setupAuth(instanceFolder); @@ -249,12 +260,13 @@ public class ArtemisTest extends CliTestBase { return fc; } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testWebConfig() throws Exception { setupAuth(); Run.setEmbedded(true); //instance1: default using http - File instance1 = new File(temporaryFolder.getRoot(), "instance1"); + File instance1 = new File(temporaryFolder, "instance1"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune"); File bootstrapFile = new File(new File(instance1, "etc"), "bootstrap.xml"); assertTrue(bootstrapFile.exists()); @@ -274,7 +286,7 @@ public class ArtemisTest extends CliTestBase { assertFalse(bindingElem.hasAttribute("trustStorePassword")); //instance2: https - File instance2 = new File(temporaryFolder.getRoot(), "instance2"); + File instance2 = new File(temporaryFolder, "instance2"); Artemis.main("create", instance2.getAbsolutePath(), "--silent", "--ssl-key", "etc/keystore", "--ssl-key-password", "password1", "--no-fsync", "--no-autotune"); bootstrapFile = new File(new File(instance2, "etc"), "bootstrap.xml"); assertTrue(bootstrapFile.exists()); @@ -296,7 +308,7 @@ public class ArtemisTest extends CliTestBase { assertFalse(bindingElem.hasAttribute("trustStorePassword")); //instance3: https with clientAuth - File instance3 = new File(temporaryFolder.getRoot(), "instance3"); + File instance3 = new File(temporaryFolder, "instance3"); Artemis.main("create", instance3.getAbsolutePath(), "--silent", "--ssl-key", "etc/keystore", "--ssl-key-password", "password1", "--use-client-auth", "--ssl-trust", "etc/truststore", "--ssl-trust-password", "password2", "--no-fsync", "--no-autotune"); bootstrapFile = new File(new File(instance3, "etc"), "bootstrap.xml"); assertTrue(bootstrapFile.exists()); @@ -326,11 +338,12 @@ public class ArtemisTest extends CliTestBase { assertEquals("password2", trustPass); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSecurityManagerConfiguration() throws Exception { setupAuth(); Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance1"); + File instance1 = new File(temporaryFolder, "instance1"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--no-stomp-acceptor", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-hornetq-acceptor"); File originalBootstrapFile = new File(new File(instance1, "etc"), "bootstrap.xml"); assertTrue(originalBootstrapFile.exists()); @@ -403,10 +416,11 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testStopManagementContext() throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -418,19 +432,21 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandJAAS() throws Exception { testUserCommand(false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandBasic() throws Exception { testUserCommand(true); } private void testUserCommand(boolean basic) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--require-login", "--security-manager", basic ? "basic" : "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -507,7 +523,7 @@ public class ArtemisTest extends CliTestBase { context = new TestActionContext(); addCmd.execute(context); result = context.getStderr(); - assertTrue("Unexpected output: '" + result + "'", result.contains("Failed to add user scott. Reason: AMQ229223: User scott already exists")); + assertTrue(result.contains("Failed to add user scott. Reason: AMQ229223: User scott already exists"), "Unexpected output: '" + result + "'"); //check existing users are intact context = new TestActionContext(); @@ -592,29 +608,33 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandViaManagementPlaintextJAAS() throws Exception { internalTestUserCommandViaManagement(true, false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandViaManagementHashedJAAS() throws Exception { internalTestUserCommandViaManagement(false, false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandViaManagementPlaintextBasic() throws Exception { internalTestUserCommandViaManagement(true, true); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandViaManagementHashedBasic() throws Exception { internalTestUserCommandViaManagement(false, true); } private void internalTestUserCommandViaManagement(boolean plaintext, boolean basic) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor", "--security-manager", basic ? "basic" : "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -713,11 +733,12 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testListUserWithMultipleRolesWithSpaces() throws Exception { try { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor", "--security-manager", "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -753,19 +774,21 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testProperReloadWhenAddingUserViaManagementJAAS() throws Exception { testProperReloadWhenAddingUserViaManagement(false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testProperReloadWhenAddingUserViaManagementBasic() throws Exception { testProperReloadWhenAddingUserViaManagement(true); } private void testProperReloadWhenAddingUserViaManagement(boolean basic) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor", "--require-login", "--security-manager", basic ? "basic" : "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -802,10 +825,11 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMissingUserFileViaManagement() throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -825,10 +849,11 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMissingRoleFileViaManagement() throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -848,19 +873,21 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandResetJAAS() throws Exception { testUserCommandReset(false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandResetBasic() throws Exception { testUserCommandReset(true); } private void testUserCommandReset(boolean basic) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--require-login", "--security-manager", basic ? "basic" : "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -979,19 +1006,21 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testConcurrentUserAdministrationJAAS() throws Exception { testConcurrentUserAdministration(false); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testConcurrentUserAdministrationBasic() throws Exception { testConcurrentUserAdministration(true); } private void testConcurrentUserAdministration(boolean basic) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--require-login", "--security-manager", basic ? "basic" : "jaas"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -1091,11 +1120,12 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testRoleWithSpaces() throws Exception { String roleWithSpaces = "amq with spaces"; Run.setEmbedded(true); - File instanceRole = new File(temporaryFolder.getRoot(), "instance_role"); + File instanceRole = new File(temporaryFolder, "instance_role"); System.setProperty("java.security.auth.login.config", instanceRole.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instanceRole.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--require-login", "--role", roleWithSpaces); System.setProperty("artemis.instance", instanceRole.getAbsolutePath()); @@ -1121,19 +1151,21 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandResetViaManagementPlaintext() throws Exception { internalTestUserCommandResetViaManagement(true); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testUserCommandResetViaManagementHashed() throws Exception { internalTestUserCommandResetViaManagement(false); } private void internalTestUserCommandResetViaManagement(boolean plaintext) throws Exception { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -1200,7 +1232,8 @@ public class ArtemisTest extends CliTestBase { stopServer(); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaskCommand() throws Exception { String password1 = "password"; @@ -1224,8 +1257,8 @@ public class ArtemisTest extends CliTestBase { result = (String) mask.execute(context); logger.debug(context.getStdout()); SensitiveDataCodec codec = mask.getCodec(); - Assert.assertEquals(DefaultSensitiveStringCodec.class, codec.getClass()); - Assert.assertTrue(((DefaultSensitiveStringCodec)codec).verify(password1.toCharArray(), result)); + assertEquals(DefaultSensitiveStringCodec.class, codec.getClass()); + assertTrue(((DefaultSensitiveStringCodec)codec).verify(password1.toCharArray(), result)); context = new TestActionContext(); mask = new Mask(); @@ -1236,9 +1269,10 @@ public class ArtemisTest extends CliTestBase { assertEquals(encrypt2, result); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaskCommandWithPasswordCodec() throws Exception { - File instanceWithPasswordCodec = new File(temporaryFolder.getRoot(), "instance_with_password_codec"); + File instanceWithPasswordCodec = new File(temporaryFolder, "instance_with_password_codec"); Files.createDirectories(Paths.get(instanceWithPasswordCodec.getAbsolutePath(), "etc")); Files.copy(Paths.get(ArtemisTest.class.getClassLoader().getResource("broker-with-password-codec.xml").toURI()), Paths.get(instanceWithPasswordCodec.getAbsolutePath(), "etc", "broker.xml")); @@ -1265,14 +1299,16 @@ public class ArtemisTest extends CliTestBase { assertEquals(password, result); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSimpleRun() throws Exception { testSimpleRun("server"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testProducerRetry() throws Exception { - File instanceFolder = temporaryFolder.newFolder("server"); + File instanceFolder = newFolder(temporaryFolder, "server"); setupAuth(instanceFolder); Run.setEmbedded(true); Artemis.main("create", instanceFolder.getAbsolutePath(), "--verbose", "--force", "--disable-persistence", "--silent", "--no-web", "--queues", "q1", "--no-autotune", "--require-login", "--default-port", "61616"); @@ -1301,26 +1337,30 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testWeirdCharacter() throws Exception { testSimpleRun("test%26%26x86_6"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSpaces() throws Exception { testSimpleRun("with space"); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testCustomPort() throws Exception { testSimpleRun("server", 61696); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testPerfJournal() throws Exception { - File instanceFolder = temporaryFolder.newFolder("server1"); + File instanceFolder = newFolder(temporaryFolder, "server1"); setupAuth(instanceFolder); Run.setEmbedded(true); @@ -1337,7 +1377,7 @@ public class ArtemisTest extends CliTestBase { } public void testSimpleRun(String folderName, int acceptorPort) throws Exception { - File instanceFolder = temporaryFolder.newFolder(folderName); + File instanceFolder = newFolder(temporaryFolder, folderName); setupAuth(instanceFolder); String queues = "q1,q2:multicast"; @@ -1361,21 +1401,21 @@ public class ArtemisTest extends CliTestBase { String[] seg = str.split(":"); RoutingType routingType = RoutingType.valueOf((seg.length == 2 ? seg[1] : "anycast").toUpperCase()); ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(seg[0])); - assertTrue("Couldn't find queue " + seg[0], queryResult.isExists()); + assertTrue(queryResult.isExists(), "Couldn't find queue " + seg[0]); assertEquals(routingType, queryResult.getRoutingType()); } for (String str : addresses.split(",")) { String[] seg = str.split(":"); RoutingType routingType = RoutingType.valueOf((seg.length == 2 ? seg[1] : "multicast").toUpperCase()); ClientSession.AddressQuery queryResult = coreSession.addressQuery(SimpleString.toSimpleString(seg[0])); - assertTrue("Couldn't find address " + str, queryResult.isExists()); + assertTrue(queryResult.isExists(), "Couldn't find address " + str); assertTrue(routingType == RoutingType.ANYCAST ? queryResult.isSupportsAnycast() : queryResult.isSupportsMulticast()); } } try { Artemis.internalExecute("data", "print"); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (CLIException expected) { } Artemis.internalExecute("data", "print", "--f"); @@ -1446,19 +1486,21 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testAutoDeleteTrue() throws Exception { testAutoDelete(true); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testAutoDeleteFalse() throws Exception { testAutoDelete(false); } private void testAutoDelete(boolean autoDelete) throws Exception { - File instanceFolder = temporaryFolder.newFolder("autocreate" + autoDelete); + File instanceFolder = newFolder(temporaryFolder, "autocreate" + autoDelete); setupAuth(instanceFolder); // This is usually set when run from the command line via artemis.profile @@ -1487,7 +1529,7 @@ public class ArtemisTest extends CliTestBase { Wait.assertTrue(() -> run.getB().locateQueue(queueName) != null); connection.start(); MessageConsumer consumer = session.createConsumer(queue); - Assert.assertNotNull(consumer.receive(5000)); + assertNotNull(consumer.receive(5000)); } if (autoDelete) { @@ -1495,7 +1537,7 @@ public class ArtemisTest extends CliTestBase { } else { // Things are async, allowing some time to make sure it would eventually fail Thread.sleep(500); - Assert.assertNotNull(run.getB().locateQueue(queueName)); + assertNotNull(run.getB().locateQueue(queueName)); } } finally { stopServer(); @@ -1503,10 +1545,10 @@ public class ArtemisTest extends CliTestBase { } - - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testPing() throws Exception { - File instanceFolder = temporaryFolder.newFolder("pingTest"); + File instanceFolder = newFolder(temporaryFolder, "pingTest"); setupAuth(instanceFolder); String queues = "q1,t2"; @@ -1522,13 +1564,14 @@ public class ArtemisTest extends CliTestBase { deploymentManager.addDeployable(fc); deploymentManager.readConfiguration(); - Assert.assertEquals("127.0.0.1", fc.getNetworkCheckList()); + assertEquals("127.0.0.1", fc.getNetworkCheckList()); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testAutoTune() throws Exception { - File instanceFolder = temporaryFolder.newFolder("autoTuneTest"); + File instanceFolder = newFolder(temporaryFolder, "autoTuneTest"); setupAuth(instanceFolder); @@ -1544,13 +1587,14 @@ public class ArtemisTest extends CliTestBase { fc.setPageSyncTimeout(-1); deploymentManager.readConfiguration(); - Assert.assertNotEquals(-1, fc.getPageSyncTimeout()); + assertNotEquals(-1, fc.getPageSyncTimeout()); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testQstat() throws Exception { - File instanceQstat = new File(temporaryFolder.getRoot(), "instanceQStat"); + File instanceQstat = new File(temporaryFolder, "instanceQStat"); setupAuth(instanceQstat); Run.setEmbedded(true); Artemis.main("create", instanceQstat.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -1583,7 +1627,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); ArrayList lines = getOutputLines(context, false); // Header line + 3 queues - Assert.assertEquals("rows returned using queueName=Test1", 5, lines.size()); + assertEquals(5, lines.size(), "rows returned using queueName=Test1"); //check all queues are displayed when no Filter set context = new TestActionContext(); @@ -1593,7 +1637,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 4 queues (at least - possibly other infra queues as well) - Assert.assertTrue("rows returned filtering no name ", 5 <= lines.size()); + assertTrue(5 <= lines.size(), "rows returned filtering no name "); //check all queues containing "Test1" are displayed using Filter field NAME context = new TestActionContext(); @@ -1606,7 +1650,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 3 queues - Assert.assertEquals("rows returned filtering by NAME ", 5, lines.size()); + assertEquals(5, lines.size(), "rows returned filtering by NAME "); //check all queues NOT containing "management" are displayed using Filter field NAME context = new TestActionContext(); @@ -1619,7 +1663,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 6 queues (Test1/11/12/20+DLQ+ExpiryQueue, but not activemq.management.d6dbba78-d76f-43d6-a2c9-fc0575ed6f5d) - Assert.assertEquals("rows returned filtering by NAME operation NOT_CONTAINS", 8, lines.size()); + assertEquals(8, lines.size(), "rows returned filtering by NAME operation NOT_CONTAINS"); //check only queue named "Test1" is displayed using Filter field NAME and operation EQUALS context = new TestActionContext(); @@ -1632,19 +1676,19 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); //Header line + 1 queue only - Assert.assertEquals("rows returned filtering by NAME operation EQUALS", 3, lines.size()); + assertEquals(3, lines.size(), "rows returned filtering by NAME operation EQUALS"); //verify contents of queue stat line is correct String queueTest1 = lines.get(2); String[] parts = queueTest1.split("\\|"); - Assert.assertEquals("queue name", "Test1", parts[1].trim()); - Assert.assertEquals("address name", "Test1", parts[2].trim()); - Assert.assertEquals("Consumer count", "2", parts[3].trim()); - Assert.assertEquals("Message count", "10", parts[4].trim()); - Assert.assertEquals("Added count", "15", parts[5].trim()); - Assert.assertEquals("Delivering count", "10", parts[6].trim()); - Assert.assertEquals("Acked count", "5", parts[7].trim()); - Assert.assertEquals("Scheduled count", "0", parts[8].trim()); - Assert.assertEquals("Routing type", "ANYCAST", parts[9].trim()); + assertEquals("Test1", parts[1].trim(), "queue name"); + assertEquals("Test1", parts[2].trim(), "address name"); + assertEquals("2", parts[3].trim(), "Consumer count"); + assertEquals("10", parts[4].trim(), "Message count"); + assertEquals("15", parts[5].trim(), "Added count"); + assertEquals("10", parts[6].trim(), "Delivering count"); + assertEquals("5", parts[7].trim(), "Acked count"); + assertEquals("0", parts[8].trim(), "Scheduled count"); + assertEquals("ANYCAST", parts[9].trim(), "Routing type"); //check all queues containing address "Test1" are displayed using Filter field ADDRESS context = new TestActionContext(); @@ -1657,7 +1701,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 3 queues - Assert.assertEquals("rows returned filtering by ADDRESS", 5, lines.size()); + assertEquals(5, lines.size(), "rows returned filtering by ADDRESS"); //check all queues containing address "Test1" are displayed using Filter field MESSAGE_COUNT context = new TestActionContext(); @@ -1671,7 +1715,7 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); // Header line + 0 queues - Assert.assertEquals("rows returned filtering by MESSAGE_COUNT", 2, lines.size()); + assertEquals(2, lines.size(), "rows returned filtering by MESSAGE_COUNT"); //check all queues containing address "Test1" are displayed using Filter field MESSAGE_ADDED context = new TestActionContext(); @@ -1684,7 +1728,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queues - Assert.assertEquals("rows returned filtering by MESSAGES_ADDED", 2, lines.size()); + assertEquals(2, lines.size(), "rows returned filtering by MESSAGES_ADDED"); //check queues with greater_than 19 MESSAGE_ADDED displayed context = new TestActionContext(); @@ -1698,9 +1742,9 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); // Header line + 1 queues - Assert.assertEquals("rows returned filtering by MESSAGES_ADDED", 3, lines.size()); + assertEquals(3, lines.size(), "rows returned filtering by MESSAGES_ADDED"); String[] columns = lines.get(2).split("\\|"); - Assert.assertEquals("queue name filtered by MESSAGES_ADDED GREATER_THAN ", "Test20", columns[2].trim()); + assertEquals("Test20", columns[2].trim(), "queue name filtered by MESSAGES_ADDED GREATER_THAN "); //check queues with less_than 2 MESSAGE_ADDED displayed context = new TestActionContext(); @@ -1714,13 +1758,13 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); // Header line + "at least" 2 queues - Assert.assertTrue("rows returned filtering by MESSAGES_ADDED LESS_THAN", 2 <= lines.size()); + assertTrue(2 <= lines.size(), "rows returned filtering by MESSAGES_ADDED LESS_THAN"); //walk the result returned and the specific destinations are not part of the output for (String line : lines) { columns = line.split("\\|"); - Assert.assertNotEquals("ensure Test20 is not part of returned result", "Test20", columns[2].trim()); - Assert.assertNotEquals("ensure Test1 is not part of returned result", "Test1", columns[2].trim()); + assertNotEquals("Test20", columns[2].trim(), "ensure Test20 is not part of returned result"); + assertNotEquals("Test1", columns[2].trim(), "ensure Test1 is not part of returned result"); } //check all queues containing address "Test1" are displayed using Filter field DELIVERING_COUNT @@ -1735,8 +1779,8 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); columns = lines.get(2).split("\\|"); // Header line + 1 queues - Assert.assertEquals("rows returned filtering by DELIVERING_COUNT", 3, lines.size()); - Assert.assertEquals("queue name filtered by DELIVERING_COUNT ", "Test1", columns[2].trim()); + assertEquals(3, lines.size(), "rows returned filtering by DELIVERING_COUNT"); + assertEquals("Test1", columns[2].trim(), "queue name filtered by DELIVERING_COUNT "); //check all queues containing address "Test1" are displayed using Filter field CONSUMER_COUNT context = new TestActionContext(); @@ -1750,8 +1794,8 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); columns = lines.get(2).split("\\|"); // Header line + 1 queues - Assert.assertEquals("rows returned filtering by CONSUMER_COUNT ", 3, lines.size()); - Assert.assertEquals("queue name filtered by CONSUMER_COUNT ", "Test1", columns[2].trim()); + assertEquals(3, lines.size(), "rows returned filtering by CONSUMER_COUNT "); + assertEquals("Test1", columns[2].trim(), "queue name filtered by CONSUMER_COUNT "); //check all queues containing address "Test1" are displayed using Filter field MESSAGE_ACKED context = new TestActionContext(); @@ -1765,8 +1809,8 @@ public class ArtemisTest extends CliTestBase { lines = getOutputLines(context, false); columns = lines.get(2).split("\\|"); // Header line + 1 queues - Assert.assertEquals("rows returned filtering by MESSAGE_ACKED ", 3, lines.size()); - Assert.assertEquals("queue name filtered by MESSAGE_ACKED", "Test1", columns[2].trim()); + assertEquals(3, lines.size(), "rows returned filtering by MESSAGE_ACKED "); + assertEquals("Test1", columns[2].trim(), "queue name filtered by MESSAGE_ACKED"); //check no queues are displayed when name does not match context = new TestActionContext(); @@ -1777,7 +1821,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queues - Assert.assertEquals("rows returned by queueName for no Matching queue ", 2, lines.size()); + assertEquals(2, lines.size(), "rows returned by queueName for no Matching queue "); //check maxrows is taking effect" context = new TestActionContext(); @@ -1789,7 +1833,7 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 1 queue only + warning line - Assert.assertEquals("rows returned by maxRows=1", 4, lines.size()); + assertEquals(4, lines.size(), "rows returned by maxRows=1"); } finally { stopServer(); @@ -1797,10 +1841,11 @@ public class ArtemisTest extends CliTestBase { } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testHugeQstat() throws Exception { - File instanceQstat = new File(temporaryFolder.getRoot(), "instanceQStat"); + File instanceQstat = new File(temporaryFolder, "instanceQStat"); setupAuth(instanceQstat); Run.setEmbedded(true); Artemis.main("create", instanceQstat.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -1824,10 +1869,11 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testQstatColumnWidth() throws Exception { - File instanceQstat = new File(temporaryFolder.getRoot(), "instanceQStat"); + File instanceQstat = new File(temporaryFolder, "instanceQStat"); setupAuth(instanceQstat); Run.setEmbedded(true); Artemis.main("create", instanceQstat.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -1850,9 +1896,9 @@ public class ArtemisTest extends CliTestBase { statQueue.setQueueName(NAME); statQueue.execute(context); ArrayList lines = getOutputLines(context, false); - Assert.assertEquals("rows returned", 4, lines.size()); + assertEquals(4, lines.size(), "rows returned"); String[] split = lines.get(1).split("\\|"); - Assert.assertEquals(StatQueue.DEFAULT_MAX_COLUMN_SIZE, split[1].length()); + assertEquals(StatQueue.DEFAULT_MAX_COLUMN_SIZE, split[1].length()); context = new TestActionContext(); statQueue = new StatQueue(); @@ -1862,9 +1908,9 @@ public class ArtemisTest extends CliTestBase { statQueue.setMaxColumnSize(15); statQueue.execute(context); lines = getOutputLines(context, false); - Assert.assertEquals("rows returned", 5, lines.size()); + assertEquals(5, lines.size(), "rows returned"); split = lines.get(1).split("\\|"); - Assert.assertEquals(15, split[1].length()); + assertEquals(15, split[1].length()); context = new TestActionContext(); statQueue = new StatQueue(); @@ -1874,9 +1920,9 @@ public class ArtemisTest extends CliTestBase { statQueue.setMaxColumnSize(50); statQueue.execute(context); lines = getOutputLines(context, false); - Assert.assertEquals("rows returned", 3, lines.size()); + assertEquals(3, lines.size(), "rows returned"); split = lines.get(1).split("\\|"); - Assert.assertEquals(NAME.length(), split[1].length()); + assertEquals(NAME.length(), split[1].length()); context = new TestActionContext(); statQueue = new StatQueue(); @@ -1889,17 +1935,18 @@ public class ArtemisTest extends CliTestBase { for (String line : lines) { System.out.println(line); } - Assert.assertEquals("rows returned", 3, lines.size()); + assertEquals(3, lines.size(), "rows returned"); } finally { stopServer(); } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testQstatErrors() throws Exception { - File instanceQstat = new File(temporaryFolder.getRoot(), "instanceQStatErrors"); + File instanceQstat = new File(temporaryFolder, "instanceQStatErrors"); setupAuth(instanceQstat); Run.setEmbedded(true); Artemis.main("create", instanceQstat.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -1918,12 +1965,12 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); ArrayList lines = getOutputLines(context, false); // Header line + 0 queue - Assert.assertEquals("No stdout for wrong FIELD", 0, lines.size()); + assertEquals(0, lines.size(), "No stdout for wrong FIELD"); lines = getOutputLines(context, true); // 1 error line - Assert.assertEquals("stderr for wrong FIELD", 1, lines.size()); - Assert.assertTrue("'FIELD incorrect' error messsage", lines.get(0).contains("'--field' must be set to one of the following")); + assertEquals(1, lines.size(), "stderr for wrong FIELD"); + assertTrue(lines.get(0).contains("'--field' must be set to one of the following"), "'FIELD incorrect' error messsage"); //Test err when OPERATION wrong context = new TestActionContext(); @@ -1936,11 +1983,11 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queue - Assert.assertEquals("No stdout for wrong OPERATION", 0, lines.size()); + assertEquals(0, lines.size(), "No stdout for wrong OPERATION"); lines = getOutputLines(context, true); // 1 error line - Assert.assertEquals("stderr for wrong OPERATION", 1, lines.size()); - Assert.assertTrue("'OPERATION incorrect' error message", lines.get(0).contains("'--operation' must be set to one of the following")); + assertEquals(1, lines.size(), "stderr for wrong OPERATION"); + assertTrue(lines.get(0).contains("'--operation' must be set to one of the following"), "'OPERATION incorrect' error message"); //Test err when queueName and field set together context = new TestActionContext(); @@ -1954,12 +2001,12 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queue - Assert.assertEquals("No stdout for --field and --queueName both set", 0, lines.size()); + assertEquals(0, lines.size(), "No stdout for --field and --queueName both set"); lines = getOutputLines(context, true); // 1 error line - Assert.assertEquals("stderr for --field and --queueName both set", 1, lines.size()); - Assert.assertTrue("field and queueName error message", lines.get(0).contains("'--field' and '--queueName' cannot be specified together")); + assertEquals(1, lines.size(), "stderr for --field and --queueName both set"); + assertTrue(lines.get(0).contains("'--field' and '--queueName' cannot be specified together"), "field and queueName error message"); //Test err when field set but no value context = new TestActionContext(); @@ -1971,11 +2018,11 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queue - Assert.assertEquals("No stdout for --field set BUT no --value", 0, lines.size()); + assertEquals(0, lines.size(), "No stdout for --field set BUT no --value"); lines = getOutputLines(context, true); // 1 error line - Assert.assertEquals("stderr for --field set BUT no --value", 1, lines.size()); - Assert.assertTrue("NO VALUE error message", lines.get(0).contains("'--value' needs to be set when '--field' is specified")); + assertEquals(1, lines.size(), "stderr for --field set BUT no --value"); + assertTrue(lines.get(0).contains("'--value' needs to be set when '--field' is specified"), "NO VALUE error message"); //Test err when field set but no operation context = new TestActionContext(); @@ -1987,11 +2034,11 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + 0 queue - Assert.assertEquals("No stdout for --field set BUT no --operation", 0, lines.size()); + assertEquals(0, lines.size(), "No stdout for --field set BUT no --operation"); lines = getOutputLines(context, true); // 1 error line - Assert.assertEquals("stderr for --field set BUT no --operation", 1, lines.size()); - Assert.assertTrue("OPERATION incorrect error message", lines.get(0).contains("'--operation' must be set when '--field' is specified ")); + assertEquals(1, lines.size(), "stderr for --field set BUT no --operation"); + assertTrue(lines.get(0).contains("'--operation' must be set when '--field' is specified "), "OPERATION incorrect error message"); } finally { stopServer(); @@ -1999,10 +2046,11 @@ public class ArtemisTest extends CliTestBase { } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testQstatWarnings() throws Exception { - File instanceQstat = new File(temporaryFolder.getRoot(), "instanceQStat"); + File instanceQstat = new File(temporaryFolder, "instanceQStat"); setupAuth(instanceQstat); Run.setEmbedded(true); Artemis.main("create", instanceQstat.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -2032,8 +2080,8 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + DEFAULT_MAX_ROWS queues + warning line - Assert.assertEquals("rows returned using queueName=Test", 2 + StatQueue.DEFAULT_MAX_ROWS, lines.size()); - Assert.assertFalse(lines.get(lines.size() - 1).startsWith("WARNING")); + assertEquals(2 + StatQueue.DEFAULT_MAX_ROWS, lines.size(), "rows returned using queueName=Test"); + assertFalse(lines.get(lines.size() - 1).startsWith("WARNING")); //check all queues containing "Test" are displayed context = new TestActionContext(); @@ -2045,8 +2093,8 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + DEFAULT_MAX_ROWS queues - Assert.assertEquals("rows returned using queueName=Test", 2 + StatQueue.DEFAULT_MAX_ROWS, lines.size()); - Assert.assertFalse(lines.get(lines.size() - 1).startsWith("WARNING")); + assertEquals(2 + StatQueue.DEFAULT_MAX_ROWS, lines.size(), "rows returned using queueName=Test"); + assertFalse(lines.get(lines.size() - 1).startsWith("WARNING")); sendMessages(session, "Test" + StatQueue.DEFAULT_MAX_ROWS, 1); @@ -2059,8 +2107,8 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + DEFAULT_MAX_ROWS queues + warning line - Assert.assertEquals("rows returned using queueName=Test", 2 + StatQueue.DEFAULT_MAX_ROWS + 1, lines.size()); - Assert.assertTrue(lines.get(lines.size() - 1).startsWith("WARNING")); + assertEquals(2 + StatQueue.DEFAULT_MAX_ROWS + 1, lines.size(), "rows returned using queueName=Test"); + assertTrue(lines.get(lines.size() - 1).startsWith("WARNING")); //check all queues containing "Test" are displayed context = new TestActionContext(); @@ -2072,8 +2120,8 @@ public class ArtemisTest extends CliTestBase { statQueue.execute(context); lines = getOutputLines(context, false); // Header line + DEFAULT_MAX_ROWS queues + warning line - Assert.assertEquals("rows returned using queueName=Test", 2 + StatQueue.DEFAULT_MAX_ROWS + 1, lines.size()); - Assert.assertTrue(lines.get(lines.size() - 1).startsWith("WARNING")); + assertEquals(2 + StatQueue.DEFAULT_MAX_ROWS + 1, lines.size(), "rows returned using queueName=Test"); + assertTrue(lines.get(lines.size() - 1).startsWith("WARNING")); } finally { stopServer(); @@ -2081,9 +2129,10 @@ public class ArtemisTest extends CliTestBase { } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testRunPropertiesArgumentSetsAcceptorPort() throws Exception { - File instanceFile = new File(temporaryFolder.getRoot(), "testRunPropertiesArgumentSetsAcceptorPort"); + File instanceFile = new File(temporaryFolder, "testRunPropertiesArgumentSetsAcceptorPort"); setupAuth(instanceFile); Run.setEmbedded(true); Artemis.main("create", instanceFile.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -2102,9 +2151,10 @@ public class ArtemisTest extends CliTestBase { } } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testRunPropertiesDudArgument() throws Exception { - File instanceFile = new File(temporaryFolder.getRoot(), "testRunPropertiesDudArgument"); + File instanceFile = new File(temporaryFolder, "testRunPropertiesDudArgument"); setupAuth(instanceFile); Run.setEmbedded(true); Artemis.main("create", instanceFile.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login"); @@ -2115,7 +2165,8 @@ public class ArtemisTest extends CliTestBase { assertTrue(ret instanceof FileNotFoundException); } - @Test(timeout = 60_000) + @Test + @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testVersionCommand() throws Exception { TestActionContext context = new TestActionContext(); PrintVersion printVersion = new PrintVersion(); @@ -2245,11 +2296,11 @@ public class ArtemisTest extends CliTestBase { } } if (contains) { - assertTrue("user " + username + " not found", userFound); - assertTrue("role " + role + " not found", roleFound); + assertTrue(userFound, "user " + username + " not found"); + assertTrue(roleFound, "role " + role + " not found"); } else { - assertFalse("user " + username + " found", userFound); - assertFalse("role " + role + " found", roleFound); + assertFalse(userFound, "user " + username + " found"); + assertFalse(roleFound, "role " + role + " found"); } } @@ -2287,4 +2338,12 @@ public class ArtemisTest extends CliTestBase { } } + private static File newFolder(File root, String subFolder) throws IOException { + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliPerfClientTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliPerfClientTest.java index c8c536daef..cb6e68979c 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliPerfClientTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliPerfClientTest.java @@ -16,12 +16,13 @@ */ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.activemq.artemis.cli.commands.messages.perf.PerfClientCommand; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; -import org.junit.After; -import org.junit.Assert; -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 javax.jms.Connection; @@ -29,7 +30,7 @@ public class CliPerfClientTest extends CliTestBase { private Connection connection; private ActiveMQConnectionFactory cf; - @Before + @BeforeEach @Override public void setup() throws Exception { setupAuth(); @@ -39,7 +40,7 @@ public class CliPerfClientTest extends CliTestBase { connection = cf.createConnection("admin", "admin"); } - @After + @AfterEach @Override public void tearDown() throws Exception { closeConnection(cf, connection); @@ -60,7 +61,7 @@ public class CliPerfClientTest extends CliTestBase { public void testDurableNoClientIDSet() throws Exception { try { new PerfClientCommand().setDurableSubscription(true).setMessageCount(1).setUser("admin").setPassword("admin").execute(new TestActionContext()); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (IllegalArgumentException cliExpected) { } } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliProducerTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliProducerTest.java index a3d8429bc0..657f0eac2d 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliProducerTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliProducerTest.java @@ -16,14 +16,17 @@ */ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.cli.commands.messages.Producer; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.CompositeAddress; import org.apache.activemq.artemis.utils.RandomUtil; -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 javax.jms.Connection; import javax.jms.Message; @@ -31,15 +34,12 @@ import javax.jms.Session; import javax.jms.TextMessage; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class CliProducerTest extends CliTestBase { private Connection connection; private ActiveMQConnectionFactory cf; private static final int TEST_MESSAGE_COUNT = 10; - @Before + @BeforeEach @Override public void setup() throws Exception { setupAuth(); @@ -49,7 +49,7 @@ public class CliProducerTest extends CliTestBase { connection = cf.createConnection("admin", "admin"); } - @After + @AfterEach @Override public void tearDown() throws Exception { closeConnection(cf, connection); diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliTestBase.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliTestBase.java index 6a6b2d3dfc..d3b6e22e6e 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliTestBase.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/CliTestBase.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.cli.test; +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 org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.cli.Artemis; @@ -26,11 +30,11 @@ import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.spi.core.security.jaas.PropertiesLoader; -import org.apache.activemq.artemis.utils.ThreadLeakCheckRule; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; import javax.jms.Connection; import javax.jms.Destination; @@ -44,33 +48,21 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +public class CliTestBase extends ArtemisTestCase { -public class CliTestBase { - - @Rule - public TemporaryFolder temporaryFolder; - - @Rule - public ThreadLeakCheckRule leakCheckRule = new ThreadLeakCheckRule(); + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File temporaryFolder; private String original = System.getProperty("java.security.auth.login.config"); - public CliTestBase() { - File parent = new File("./target/tmp"); - parent.mkdirs(); - temporaryFolder = new TemporaryFolder(parent); - } - - @Before + @BeforeEach public void setup() throws Exception { Run.setEmbedded(true); PropertiesLoader.resetUsersAndGroupsCache(); } - @After + @AfterEach public void tearDown() throws Exception { ActiveMQClient.clearThreadPools(); System.clearProperty("artemis.instance"); @@ -87,7 +79,7 @@ public class CliTestBase { } protected Object startServer() throws Exception { - File rootDirectory = new File(temporaryFolder.getRoot(), "broker"); + File rootDirectory = new File(temporaryFolder, "broker"); setupAuth(rootDirectory); Run.setEmbedded(true); Artemis.main("create", rootDirectory.getAbsolutePath(), "--silent", "--no-fsync", "--no-autotune", "--no-web", "--require-login", "--disable-persistence"); @@ -96,7 +88,7 @@ public class CliTestBase { } void setupAuth() { - setupAuth(temporaryFolder.getRoot()); + setupAuth(temporaryFolder); } void setupAuth(File folder) { diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ClusterVerifyTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ClusterVerifyTest.java index bfe598cbdd..febe83ae88 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/ClusterVerifyTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/ClusterVerifyTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; @@ -25,8 +28,7 @@ import org.apache.activemq.artemis.cli.commands.ActionContext; import org.apache.activemq.artemis.cli.commands.check.ClusterNodeVerifier; import org.apache.activemq.artemis.json.JsonArray; import org.apache.commons.lang3.NotImplementedException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ClusterVerifyTest { @@ -103,9 +105,9 @@ public class ClusterVerifyTest { }; if (fail) { - Assert.assertFalse(fakeVerifier.verify(new ActionContext())); + assertFalse(fakeVerifier.verify(new ActionContext())); } else { - Assert.assertTrue(fakeVerifier.verify(new ActionContext())); + assertTrue(fakeVerifier.verify(new ActionContext())); } } @@ -152,7 +154,7 @@ public class ClusterVerifyTest { } }; - Assert.assertTrue(fakeVerifier.verify(new ActionContext())); + assertTrue(fakeVerifier.verify(new ActionContext())); } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java index a6e8186359..cc68936644 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/FileBrokerTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -37,10 +43,7 @@ import org.apache.activemq.artemis.integration.FileBroker; import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager; import org.apache.activemq.artemis.spi.core.security.jaas.InVMLoginModule; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; public class FileBrokerTest { @@ -52,11 +55,11 @@ public class FileBrokerTest { try { broker.start(); JMSServerManagerImpl jmsServerManager = (JMSServerManagerImpl) broker.getComponents().get("jms"); - Assert.assertNull(jmsServerManager); + assertNull(jmsServerManager); ActiveMQServerImpl activeMQServer = (ActiveMQServerImpl) broker.getComponents().get("core"); - Assert.assertNotNull(activeMQServer); - Assert.assertTrue(activeMQServer.isStarted()); - Assert.assertTrue(broker.isStarted()); + assertNotNull(activeMQServer); + assertTrue(activeMQServer.isStarted()); + assertTrue(broker.isStarted()); } finally { broker.stop(); } @@ -72,7 +75,7 @@ public class FileBrokerTest { FileBroker broker2 = new FileBroker(serverDTO2, new ActiveMQJAASSecurityManager(), null); try { broker1.start(); - Assert.assertTrue(broker1.isStarted()); + assertTrue(broker1.isStarted()); Thread thread = new Thread(() -> { try { @@ -83,13 +86,13 @@ public class FileBrokerTest { }); thread.start(); - Assert.assertFalse(broker2.isStarted()); + assertFalse(broker2.isStarted()); //only if broker1 is stopped can broker2 be fully started broker1.stop(); broker1 = null; thread.join(5000); - Assert.assertTrue(broker2.isStarted()); + assertTrue(broker2.isStarted()); broker2.stop(); } finally { @@ -116,12 +119,12 @@ public class FileBrokerTest { broker = new FileBroker(serverDTO, securityManager, null); broker.start(); ActiveMQServerImpl activeMQServer = (ActiveMQServerImpl) broker.getComponents().get("core"); - Assert.assertNotNull(activeMQServer); - Assert.assertTrue(activeMQServer.isStarted()); - Assert.assertTrue(broker.isStarted()); + assertNotNull(activeMQServer); + assertTrue(activeMQServer.isStarted()); + assertTrue(broker.isStarted()); File file = new File(activeMQServer.getConfiguration().getConfigurationUrl().toURI()); path = file.getPath(); - Assert.assertNotNull(activeMQServer.getConfiguration().getConfigurationUrl()); + assertNotNull(activeMQServer.getConfiguration().getConfigurationUrl()); Thread.sleep(activeMQServer.getConfiguration().getConfigurationFileRefreshPeriod() * 2); @@ -164,12 +167,12 @@ public class FileBrokerTest { broker = new FileBroker(serverDTO, securityManager, null); broker.start(); ActiveMQServerImpl activeMQServer = (ActiveMQServerImpl) broker.getComponents().get("core"); - Assert.assertNotNull(activeMQServer); - Assert.assertTrue(activeMQServer.isStarted()); - Assert.assertTrue(broker.isStarted()); + assertNotNull(activeMQServer); + assertTrue(activeMQServer.isStarted()); + assertTrue(broker.isStarted()); File file = new File(activeMQServer.getConfiguration().getConfigurationUrl().toURI()); path = file.getPath(); - Assert.assertNotNull(activeMQServer.getConfiguration().getConfigurationUrl()); + assertNotNull(activeMQServer.getConfiguration().getConfigurationUrl()); Thread.sleep(1000); diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/HashUtilTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/HashUtilTest.java index 7bd93dab72..9ef75b5de5 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/HashUtilTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/HashUtilTest.java @@ -16,16 +16,16 @@ */ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.cli.commands.util.HashUtil; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class HashUtilTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/MessageSerializerTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/MessageSerializerTest.java index 293df4d2a6..63fa4bde66 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/MessageSerializerTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/MessageSerializerTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.cli.test; +import static org.apache.activemq.cli.test.ArtemisTest.getOutputLines; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.Destination; import javax.jms.MapMessage; @@ -44,14 +49,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.utils.CompositeAddress; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.apache.activemq.cli.test.ArtemisTest.getOutputLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test to validate that the CLI doesn't throw improper exceptions when invoked. @@ -62,7 +62,7 @@ public class MessageSerializerTest extends CliTestBase { private ActiveMQConnectionFactory cf; private static final int TEST_MESSAGE_COUNT = 10; - @Before + @BeforeEach @Override public void setup() throws Exception { setupAuth(); @@ -72,7 +72,7 @@ public class MessageSerializerTest extends CliTestBase { connection = cf.createConnection("admin", "admin"); } - @After + @AfterEach @Override public void tearDown() throws Exception { closeConnection(cf, connection); @@ -80,7 +80,7 @@ public class MessageSerializerTest extends CliTestBase { } private File createMessageFile() throws IOException { - return temporaryFolder.newFile("messages.xml"); + return File.createTempFile("messages.xml", null, temporaryFolder); } private List generateTextMessages(Session session, Destination destination) throws Exception { diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/RetryCLIClientIDTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/RetryCLIClientIDTest.java index 5043b93612..c3ccb75846 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/RetryCLIClientIDTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/RetryCLIClientIDTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import org.apache.activemq.artemis.api.core.Pair; @@ -27,8 +29,7 @@ import org.apache.activemq.artemis.cli.commands.messages.ConnectionAbstract; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.management.ManagementContext; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RetryCLIClientIDTest extends CliTestBase { @@ -36,7 +37,7 @@ public class RetryCLIClientIDTest extends CliTestBase { public void testWrongUserAndPass() throws Exception { try { Run.setEmbedded(true); - File instance1 = new File(temporaryFolder.getRoot(), "instance_user"); + File instance1 = new File(temporaryFolder, "instance_user"); System.setProperty("java.security.auth.login.config", instance1.getAbsolutePath() + "/etc/login.config"); Artemis.main("create", instance1.getAbsolutePath(), "--silent", "--no-autotune", "--no-web", "--no-amqp-acceptor", "--no-mqtt-acceptor", "--no-stomp-acceptor", "--no-hornetq-acceptor", "--user", "dumb", "--password", "dumber", "--require-login"); System.setProperty("artemis.instance", instance1.getAbsolutePath()); @@ -48,7 +49,7 @@ public class RetryCLIClientIDTest extends CliTestBase { test.setSilentInput(true); test.setClientID("someClientID"); ActiveMQConnectionFactory cf = test.newCF(); - Assert.assertEquals("someClientID", cf.getClientID()); + assertEquals("someClientID", cf.getClientID()); } finally { stopServer(); diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java index 9b1f3a1f1a..1dc2cdb0ee 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/StreamClassPathTest.java @@ -17,12 +17,13 @@ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.InputStream; import org.apache.activemq.artemis.cli.commands.Create; import org.apache.activemq.artemis.cli.commands.messages.Producer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class StreamClassPathTest { @@ -70,7 +71,7 @@ public class StreamClassPathTest { private void testStream(Class clazz, String source) throws Exception { InputStream in = clazz.getResourceAsStream(source); - Assert.assertNotNull(source + " not found", in); + assertNotNull(in, source + " not found"); in.close(); } } diff --git a/artemis-cli/src/test/java/org/apache/activemq/cli/test/TransferTest.java b/artemis-cli/src/test/java/org/apache/activemq/cli/test/TransferTest.java index 18f58da428..262f648002 100644 --- a/artemis-cli/src/test/java/org/apache/activemq/cli/test/TransferTest.java +++ b/artemis-cli/src/test/java/org/apache/activemq/cli/test/TransferTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.cli.test; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; @@ -25,10 +27,9 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.management.ManagementContext; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Assert; -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 javax.jms.Connection; import javax.jms.Session; @@ -39,7 +40,7 @@ public class TransferTest extends CliTestBase { private ActiveMQServer server; private static final int TEST_MESSAGE_COUNT = 10; - @Before + @BeforeEach @Override public void setup() throws Exception { setupAuth(); @@ -49,7 +50,7 @@ public class TransferTest extends CliTestBase { connection = cf.createConnection("admin", "admin"); } - @After + @AfterEach @Override public void tearDown() throws Exception { closeConnection(cf, connection); @@ -92,13 +93,13 @@ public class TransferTest extends CliTestBase { if (limit > 0) { transfer.setMessageCount(limit); - Assert.assertEquals(limit, transfer.execute(new TestActionContext())); + assertEquals(limit, transfer.execute(new TestActionContext())); Queue targetQueue = server.locateQueue(targetQueueName); Wait.assertEquals(messages - limit, sourceQueue::getMessageCount); Wait.assertEquals(limit, targetQueue::getMessageCount); } else { - Assert.assertEquals(messages, transfer.execute(new TestActionContext())); + assertEquals(messages, transfer.execute(new TestActionContext())); Queue targetQueue = server.locateQueue(targetQueueName); Wait.assertEquals(0, sourceQueue::getMessageCount); diff --git a/artemis-commons/pom.xml b/artemis-commons/pom.xml index 0e2beeba6a..e008e880be 100644 --- a/artemis-commons/pom.xml +++ b/artemis-commons/pom.xml @@ -67,7 +67,6 @@ log4j-slf4j2-impl test - io.netty netty-buffer @@ -81,8 +80,13 @@ commons-beanutils - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/api/core/QueueConfigurationTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/api/core/QueueConfigurationTest.java index 7119565444..b90f60d9c2 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/api/core/QueueConfigurationTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/api/core/QueueConfigurationTest.java @@ -16,10 +16,15 @@ */ package org.apache.activemq.artemis.api.core; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.utils.CompositeAddress; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class QueueConfigurationTest { @@ -27,19 +32,23 @@ public class QueueConfigurationTest { public void testSetGroupRebalancePauseDispatch() { QueueConfiguration queueConfiguration = new QueueConfiguration("TEST"); - Assert.assertEquals(null, queueConfiguration.isGroupRebalancePauseDispatch()); + assertNull(queueConfiguration.isGroupRebalancePauseDispatch()); queueConfiguration.setGroupRebalancePauseDispatch(true); - Assert.assertEquals(true, queueConfiguration.isGroupRebalancePauseDispatch()); + assertNotNull(queueConfiguration.isGroupRebalancePauseDispatch()); + assertTrue(queueConfiguration.isGroupRebalancePauseDispatch()); queueConfiguration.setGroupRebalancePauseDispatch(false); - Assert.assertEquals(false, queueConfiguration.isGroupRebalancePauseDispatch()); + assertNotNull(queueConfiguration.isGroupRebalancePauseDispatch()); + assertFalse(queueConfiguration.isGroupRebalancePauseDispatch()); queueConfiguration.set(QueueConfiguration.GROUP_REBALANCE_PAUSE_DISPATCH, Boolean.toString(true)); - Assert.assertEquals(true, queueConfiguration.isGroupRebalancePauseDispatch()); + assertNotNull(queueConfiguration.isGroupRebalancePauseDispatch()); + assertTrue(queueConfiguration.isGroupRebalancePauseDispatch()); queueConfiguration.set(QueueConfiguration.GROUP_REBALANCE_PAUSE_DISPATCH, Boolean.toString(false)); - Assert.assertEquals(false, queueConfiguration.isGroupRebalancePauseDispatch()); + assertNotNull(queueConfiguration.isGroupRebalancePauseDispatch()); + assertFalse(queueConfiguration.isGroupRebalancePauseDispatch()); } @Test @@ -47,9 +56,9 @@ public class QueueConfigurationTest { final SimpleString ADDRESS = RandomUtil.randomSimpleString(); final SimpleString QUEUE = RandomUtil.randomSimpleString(); QueueConfiguration queueConfiguration = new QueueConfiguration(CompositeAddress.toFullyQualified(ADDRESS, QUEUE)); - Assert.assertEquals(ADDRESS, queueConfiguration.getAddress()); - Assert.assertEquals(QUEUE, queueConfiguration.getName()); - Assert.assertTrue(queueConfiguration.isFqqn()); + assertEquals(ADDRESS, queueConfiguration.getAddress()); + assertEquals(QUEUE, queueConfiguration.getName()); + assertTrue(queueConfiguration.isFqqn()); } @Test @@ -57,9 +66,9 @@ public class QueueConfigurationTest { final SimpleString ADDRESS = RandomUtil.randomSimpleString(); final SimpleString QUEUE = RandomUtil.randomSimpleString(); QueueConfiguration queueConfiguration = new QueueConfiguration(QUEUE).setAddress(ADDRESS); - Assert.assertEquals(ADDRESS, queueConfiguration.getAddress()); - Assert.assertEquals(QUEUE, queueConfiguration.getName()); - Assert.assertFalse(queueConfiguration.isFqqn()); + assertEquals(ADDRESS, queueConfiguration.getAddress()); + assertEquals(QUEUE, queueConfiguration.getName()); + assertFalse(queueConfiguration.isFqqn()); } @Test @@ -67,8 +76,8 @@ public class QueueConfigurationTest { final SimpleString ADDRESS = RandomUtil.randomSimpleString(); final SimpleString QUEUE = RandomUtil.randomSimpleString(); QueueConfiguration queueConfiguration = new QueueConfiguration(RandomUtil.randomSimpleString()).setAddress(CompositeAddress.toFullyQualified(ADDRESS, QUEUE)); - Assert.assertEquals(ADDRESS, queueConfiguration.getAddress()); - Assert.assertEquals(QUEUE, queueConfiguration.getName()); - Assert.assertTrue(queueConfiguration.isFqqn()); + assertEquals(ADDRESS, queueConfiguration.getAddress()); + assertEquals(QUEUE, queueConfiguration.getName()); + assertTrue(queueConfiguration.isFqqn()); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/logs/CommonsLogBundlesTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/logs/CommonsLogBundlesTest.java index e55c9fa0b2..8ce2a7cdbb 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/logs/CommonsLogBundlesTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/logs/CommonsLogBundlesTest.java @@ -16,14 +16,14 @@ */ package org.apache.activemq.artemis.logs; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class CommonsLogBundlesTest { @@ -32,13 +32,13 @@ public class CommonsLogBundlesTest { private static LogLevel origAuditLoggersLevel; private static LogLevel origUtilLoggersLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origAuditLoggersLevel = AssertionLoggerHandler.setLevel(AUDIT_LOGGERS, LogLevel.INFO); origUtilLoggersLevel = AssertionLoggerHandler.setLevel(UTIL_LOGGER, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(AUDIT_LOGGERS, origAuditLoggersLevel); AssertionLoggerHandler.setLevel(UTIL_LOGGER, origUtilLoggersLevel); @@ -59,8 +59,8 @@ public class CommonsLogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ209000")); - assertTrue("unexpected message: " + message, message.contains("breadcrumb")); + assertTrue(message.startsWith("AMQ209000"), "unexpected message: " + message); + assertTrue(message.contains("breadcrumb"), "unexpected message: " + message); } @Test diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ActiveMQScheduledComponentTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ActiveMQScheduledComponentTest.java index 0f0417f01b..4811503e78 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ActiveMQScheduledComponentTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ActiveMQScheduledComponentTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.utils; +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.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -25,27 +29,23 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.server.ActiveMQScheduledComponent; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ActiveMQScheduledComponentTest { - - @Rule - public ThreadLeakCheckRule rule = new ThreadLeakCheckRule(); +public class ActiveMQScheduledComponentTest extends ArtemisTestCase { ScheduledExecutorService scheduledExecutorService; ExecutorService executorService; - @Before + @BeforeEach public void before() { scheduledExecutorService = new ScheduledThreadPoolExecutor(5); executorService = Executors.newSingleThreadExecutor(); } - @After + @AfterEach public void after() { executorService.shutdown(); scheduledExecutorService.shutdown(); @@ -74,7 +74,7 @@ public class ActiveMQScheduledComponentTest { local.stop(); - Assert.assertTrue("just because one took a lot of time, it doesn't mean we can accumulate many, we got " + count + " executions", count.get() < 5); + assertTrue(count.get() < 5, "just because one took a lot of time, it doesn't mean we can accumulate many, we got " + count + " executions"); } @Test @@ -89,7 +89,7 @@ public class ActiveMQScheduledComponentTest { } }; local.start(); - Assert.assertTrue(triggered.await(10, TimeUnit.SECONDS)); + assertTrue(triggered.await(10, TimeUnit.SECONDS)); local.stop(); } @@ -106,12 +106,12 @@ public class ActiveMQScheduledComponentTest { local.start(); final long newInitialDelay = 1000; //the parameters are valid? - Assert.assertTrue(initialDelay != newInitialDelay); - Assert.assertTrue(newInitialDelay != period); + assertTrue(initialDelay != newInitialDelay); + assertTrue(newInitialDelay != period); local.setInitialDelay(newInitialDelay); local.stop(); - Assert.assertEquals("the initial dalay can't change", newInitialDelay, local.getInitialDelay()); + assertEquals(newInitialDelay, local.getInitialDelay(), "the initial dalay can't change"); } @Test @@ -137,7 +137,7 @@ public class ActiveMQScheduledComponentTest { local.stop(); - Assert.assertTrue("just because one took a lot of time, it doesn't mean we can accumulate many, we got " + count + " executions", count.get() <= 5 && count.get() > 0); + assertTrue(count.get() <= 5 && count.get() > 0, "just because one took a lot of time, it doesn't mean we can accumulate many, we got " + count + " executions"); } @Test @@ -155,7 +155,7 @@ public class ActiveMQScheduledComponentTest { local.start(); // should be ok to call start again try { - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); // re-scheduling the executor at a big interval.. // just to make sure it won't hung @@ -183,13 +183,13 @@ public class ActiveMQScheduledComponentTest { try { - Assert.assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); local.delay(); - Assert.assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); latch.setCount(1); - Assert.assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); // re-scheduling the executor at a big interval.. // just to make sure it won't hung @@ -216,31 +216,31 @@ public class ActiveMQScheduledComponentTest { local.start(); try { - Assert.assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); latch.setCount(1); local.delay(); - Assert.assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); latch.setCount(1); - Assert.assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); local.setPeriod(TimeUnit.HOURS.toMillis(1), TimeUnit.MILLISECONDS); latch.setCount(1); local.delay(); - Assert.assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(20, TimeUnit.MILLISECONDS)); local.setPeriod(1); local.delay(); - Assert.assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(20, TimeUnit.MILLISECONDS)); local.setPeriod(1, TimeUnit.SECONDS); latch.setCount(1); local.delay(); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } finally { local.stop(); local.stop(); // calling stop again should not be an issue. @@ -263,8 +263,8 @@ public class ActiveMQScheduledComponentTest { try { final boolean triggeredBeforePeriod = latch.await(local.getPeriod(), local.getTimeUnit()); final long timeToFirstTrigger = TimeUnit.NANOSECONDS.convert(System.nanoTime() - start, local.getTimeUnit()); - Assert.assertTrue("Takes too long to start", triggeredBeforePeriod); - Assert.assertTrue("Started too early", timeToFirstTrigger >= local.getInitialDelay()); + assertTrue(triggeredBeforePeriod, "Takes too long to start"); + assertTrue(timeToFirstTrigger >= local.getInitialDelay(), "Started too early"); } finally { local.stop(); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java index 5b74c6a432..9358327d4f 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ByteUtilTest.java @@ -16,6 +16,15 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ReadOnlyBufferException; @@ -27,17 +36,10 @@ import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.internal.PlatformDependent; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; public class ByteUtilTest { @@ -67,7 +69,7 @@ public class ByteUtilTest { void testEquals(String string1, String string2) { if (!string1.equals(string2)) { - Assert.fail("String are not the same:=" + string1 + "!=" + string2); + fail("String are not the same:=" + string1 + "!=" + string2); } } @@ -95,8 +97,8 @@ public class ByteUtilTest { @Test public void testUnsafeUnalignedByteArrayHashCode() { - Assume.assumeTrue(PlatformDependent.hasUnsafe()); - Assume.assumeTrue(PlatformDependent.isUnaligned()); + assumeTrue(PlatformDependent.hasUnsafe()); + assumeTrue(PlatformDependent.isUnaligned()); Map map = new LinkedHashMap<>(); map.put(new byte[0], 1); map.put(new byte[]{1}, 32); @@ -113,14 +115,14 @@ public class ByteUtilTest { map.put(new byte[]{-1, -1, -1, (byte) 0xE1}, -503316450); } for (Map.Entry e : map.entrySet()) { - assertEquals("input = " + Arrays.toString(e.getKey()), e.getValue().intValue(), ByteUtil.hashCode(e.getKey())); + assertEquals(e.getValue().intValue(), ByteUtil.hashCode(e.getKey()), "input = " + Arrays.toString(e.getKey())); } } @Test public void testNoUnsafeAlignedByteArrayHashCode() { - Assume.assumeFalse(PlatformDependent.hasUnsafe()); - Assume.assumeFalse(PlatformDependent.isUnaligned()); + assumeFalse(PlatformDependent.hasUnsafe()); + assumeFalse(PlatformDependent.isUnaligned()); ArrayList inputs = new ArrayList<>(); inputs.add(new byte[0]); inputs.add(new byte[]{1}); @@ -130,7 +132,7 @@ public class ByteUtilTest { inputs.add(new byte[]{0, 1, 2, 3, 4, 5}); inputs.add(new byte[]{6, 7, 8, 9, 0, 1}); inputs.add(new byte[]{-1, -1, -1, (byte) 0xE1}); - inputs.forEach(input -> assertEquals("input = " + Arrays.toString(input), Arrays.hashCode(input), ByteUtil.hashCode(input))); + inputs.forEach(input -> assertEquals(Arrays.hashCode(input), ByteUtil.hashCode(input), "input = " + Arrays.toString(input))); } @Test @@ -175,26 +177,26 @@ public class ByteUtilTest { final int position = buffer.position(); final int limit = buffer.limit(); ByteUtil.zeros(buffer, offset, bytes); - Assert.assertEquals(position, buffer.position()); - Assert.assertEquals(limit, buffer.limit()); + assertEquals(position, buffer.position()); + assertEquals(limit, buffer.limit()); final byte[] zeros = new byte[bytes]; final byte[] content = new byte[bytes]; final ByteBuffer duplicate = buffer.duplicate(); duplicate.clear().position(offset); duplicate.get(content, 0, bytes); - Assert.assertArrayEquals(zeros, content); + assertArrayEquals(zeros, content); if (originalRemaining != null) { final byte[] remaining = new byte[duplicate.remaining()]; //duplicate position has been moved of bytes duplicate.get(remaining); - Assert.assertArrayEquals(originalRemaining, remaining); + assertArrayEquals(originalRemaining, remaining); } if (originalBefore != null) { final byte[] before = new byte[offset]; //duplicate position has been moved of bytes: need to reset it duplicate.position(0); duplicate.get(before); - Assert.assertArrayEquals(originalBefore, before); + assertArrayEquals(originalBefore, before); } } @@ -263,96 +265,106 @@ public class ByteUtilTest { shouldZeroesByteBuffer(buffer, offset, bytes); } - @Test(expected = ReadOnlyBufferException.class) + @Test public void shouldFailWithReadOnlyHeapByteBuffer() { - final byte one = (byte) 1; - final int capacity = 64; - final int bytes = 32; - final int offset = 1; - ByteBuffer buffer = ByteBuffer.allocate(capacity); - fill(buffer, 0, capacity, one); - buffer = buffer.asReadOnlyBuffer(); - shouldZeroesByteBuffer(buffer, offset, bytes); + assertThrows(ReadOnlyBufferException.class, () -> { + final byte one = (byte) 1; + final int capacity = 64; + final int bytes = 32; + final int offset = 1; + ByteBuffer buffer = ByteBuffer.allocate(capacity); + fill(buffer, 0, capacity, one); + buffer = buffer.asReadOnlyBuffer(); + shouldZeroesByteBuffer(buffer, offset, bytes); + }); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void shouldFailIfOffsetIsGreaterOrEqualHeapByteBufferCapacity() { - final byte one = (byte) 1; - final int capacity = 64; - final int bytes = 0; - final int offset = 64; - ByteBuffer buffer = ByteBuffer.allocate(capacity); - fill(buffer, 0, capacity, one); - try { - shouldZeroesByteBuffer(buffer, offset, bytes); - } catch (IndexOutOfBoundsException expectedEx) { - //verify that the buffer hasn't changed - final byte[] originalContent = duplicateRemaining(buffer, 0, 0); - final byte[] expectedContent = new byte[capacity]; - Arrays.fill(expectedContent, one); - Assert.assertArrayEquals(expectedContent, originalContent); - throw expectedEx; - } + assertThrows(IndexOutOfBoundsException.class, () -> { + final byte one = (byte) 1; + final int capacity = 64; + final int bytes = 0; + final int offset = 64; + ByteBuffer buffer = ByteBuffer.allocate(capacity); + fill(buffer, 0, capacity, one); + try { + shouldZeroesByteBuffer(buffer, offset, bytes); + } catch (IndexOutOfBoundsException expectedEx) { + //verify that the buffer hasn't changed + final byte[] originalContent = duplicateRemaining(buffer, 0, 0); + final byte[] expectedContent = new byte[capacity]; + Arrays.fill(expectedContent, one); + assertArrayEquals(expectedContent, originalContent); + throw expectedEx; + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailIfOffsetIsNegative() { - final byte one = (byte) 1; - final int capacity = 64; - final int bytes = 1; - final int offset = -1; - ByteBuffer buffer = ByteBuffer.allocate(capacity); - fill(buffer, 0, capacity, one); - try { - shouldZeroesByteBuffer(buffer, offset, bytes); - } catch (IndexOutOfBoundsException expectedEx) { - //verify that the buffer hasn't changed - final byte[] originalContent = duplicateRemaining(buffer, 0, 0); - final byte[] expectedContent = new byte[capacity]; - Arrays.fill(expectedContent, one); - Assert.assertArrayEquals(expectedContent, originalContent); - throw expectedEx; - } + assertThrows(IllegalArgumentException.class, () -> { + final byte one = (byte) 1; + final int capacity = 64; + final int bytes = 1; + final int offset = -1; + ByteBuffer buffer = ByteBuffer.allocate(capacity); + fill(buffer, 0, capacity, one); + try { + shouldZeroesByteBuffer(buffer, offset, bytes); + } catch (IndexOutOfBoundsException expectedEx) { + //verify that the buffer hasn't changed + final byte[] originalContent = duplicateRemaining(buffer, 0, 0); + final byte[] expectedContent = new byte[capacity]; + Arrays.fill(expectedContent, one); + assertArrayEquals(expectedContent, originalContent); + throw expectedEx; + } + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailIfBytesIsNegative() { - final byte one = (byte) 1; - final int capacity = 64; - final int bytes = -1; - final int offset = 0; - ByteBuffer buffer = ByteBuffer.allocate(capacity); - fill(buffer, 0, capacity, one); - try { - shouldZeroesByteBuffer(buffer, offset, bytes); - } catch (IndexOutOfBoundsException expectedEx) { - //verify that the buffer hasn't changed - final byte[] originalContent = duplicateRemaining(buffer, 0, 0); - final byte[] expectedContent = new byte[capacity]; - Arrays.fill(expectedContent, one); - Assert.assertArrayEquals(expectedContent, originalContent); - throw expectedEx; - } + assertThrows(IllegalArgumentException.class, () -> { + final byte one = (byte) 1; + final int capacity = 64; + final int bytes = -1; + final int offset = 0; + ByteBuffer buffer = ByteBuffer.allocate(capacity); + fill(buffer, 0, capacity, one); + try { + shouldZeroesByteBuffer(buffer, offset, bytes); + } catch (IndexOutOfBoundsException expectedEx) { + //verify that the buffer hasn't changed + final byte[] originalContent = duplicateRemaining(buffer, 0, 0); + final byte[] expectedContent = new byte[capacity]; + Arrays.fill(expectedContent, one); + assertArrayEquals(expectedContent, originalContent); + throw expectedEx; + } + }); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void shouldFailIfExceedingHeapByteBufferCapacity() { - final byte one = (byte) 1; - final int capacity = 64; - final int bytes = 65; - final int offset = 1; - ByteBuffer buffer = ByteBuffer.allocate(capacity); - fill(buffer, 0, capacity, one); - try { - shouldZeroesByteBuffer(buffer, offset, bytes); - } catch (IndexOutOfBoundsException expectedEx) { - //verify that the buffer hasn't changed - final byte[] originalContent = duplicateRemaining(buffer, 0, 0); - final byte[] expectedContent = new byte[capacity]; - Arrays.fill(expectedContent, one); - Assert.assertArrayEquals(expectedContent, originalContent); - throw expectedEx; - } + assertThrows(IndexOutOfBoundsException.class, () -> { + final byte one = (byte) 1; + final int capacity = 64; + final int bytes = 65; + final int offset = 1; + ByteBuffer buffer = ByteBuffer.allocate(capacity); + fill(buffer, 0, capacity, one); + try { + shouldZeroesByteBuffer(buffer, offset, bytes); + } catch (IndexOutOfBoundsException expectedEx) { + //verify that the buffer hasn't changed + final byte[] originalContent = duplicateRemaining(buffer, 0, 0); + final byte[] expectedContent = new byte[capacity]; + Arrays.fill(expectedContent, one); + assertArrayEquals(expectedContent, originalContent); + throw expectedEx; + } + }); } @Test @@ -368,7 +380,7 @@ public class ByteUtilTest { byte[] expected = ByteBuffer.allocate(4).putInt(intValue).array(); byte[] actual = ByteUtil.intToBytes(intValue); if (manualExpect != null) { - Assert.assertEquals(4, manualExpect.length); + assertEquals(4, manualExpect.length); assertArrayEquals(manualExpect, actual); } assertArrayEquals(expected, actual); @@ -390,7 +402,7 @@ public class ByteUtilTest { byte[] expected = ByteBuffer.allocate(8).putLong(longValue).array(); byte[] actual = ByteUtil.longToBytes(longValue); if (manualExpected != null) { - Assert.assertEquals(8, manualExpected.length); + assertEquals(8, manualExpected.length); assertArrayEquals(manualExpected, actual); } assertArrayEquals(expected, actual); @@ -413,12 +425,14 @@ public class ByteUtilTest { assertArrayEquals(assertContent, convertedContent); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldEnsureExactWritableFailToEnlargeWrappedByteBuf() { - byte[] wrapped = new byte[32]; - ByteBuf buffer = Unpooled.wrappedBuffer(wrapped); - buffer.writerIndex(wrapped.length); - ByteUtil.ensureExactWritable(buffer, 1); + assertThrows(IllegalArgumentException.class, () -> { + byte[] wrapped = new byte[32]; + ByteBuf buffer = Unpooled.wrappedBuffer(wrapped); + buffer.writerIndex(wrapped.length); + ByteUtil.ensureExactWritable(buffer, 1); + }); } @Test @@ -427,7 +441,7 @@ public class ByteUtilTest { ByteBuf buffer = Unpooled.wrappedBuffer(wrapped); buffer.writerIndex(wrapped.length - 1); ByteUtil.ensureExactWritable(buffer, 1); - Assert.assertSame(wrapped, buffer.array()); + assertSame(wrapped, buffer.array()); } @Test @@ -435,7 +449,7 @@ public class ByteUtilTest { ByteBuf buffer = Unpooled.buffer(32); buffer.writerIndex(32); ByteUtil.ensureExactWritable(buffer, 1); - Assert.assertEquals(33, buffer.capacity()); + assertEquals(33, buffer.capacity()); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ConcurrentHashSetTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ConcurrentHashSetTest.java index b2bdc6099c..e9cac72155 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ConcurrentHashSetTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ConcurrentHashSetTest.java @@ -16,15 +16,18 @@ */ package org.apache.activemq.artemis.utils; +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.Iterator; import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet; import org.apache.activemq.artemis.utils.collections.ConcurrentSet; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ConcurrentHashSetTest extends Assert { +public class ConcurrentHashSetTest { private ConcurrentSet set; @@ -34,64 +37,64 @@ public class ConcurrentHashSetTest extends Assert { @Test public void testAdd() throws Exception { - Assert.assertTrue(set.add(element)); - Assert.assertFalse(set.add(element)); + assertTrue(set.add(element)); + assertFalse(set.add(element)); } @Test public void testAddIfAbsent() throws Exception { - Assert.assertTrue(set.addIfAbsent(element)); - Assert.assertFalse(set.addIfAbsent(element)); + assertTrue(set.addIfAbsent(element)); + assertFalse(set.addIfAbsent(element)); } @Test public void testRemove() throws Exception { - Assert.assertTrue(set.add(element)); + assertTrue(set.add(element)); - Assert.assertTrue(set.remove(element)); - Assert.assertFalse(set.remove(element)); + assertTrue(set.remove(element)); + assertFalse(set.remove(element)); } @Test public void testContains() throws Exception { - Assert.assertFalse(set.contains(element)); + assertFalse(set.contains(element)); - Assert.assertTrue(set.add(element)); - Assert.assertTrue(set.contains(element)); + assertTrue(set.add(element)); + assertTrue(set.contains(element)); - Assert.assertTrue(set.remove(element)); - Assert.assertFalse(set.contains(element)); + assertTrue(set.remove(element)); + assertFalse(set.contains(element)); } @Test public void testSize() throws Exception { - Assert.assertEquals(0, set.size()); + assertEquals(0, set.size()); - Assert.assertTrue(set.add(element)); - Assert.assertEquals(1, set.size()); + assertTrue(set.add(element)); + assertEquals(1, set.size()); - Assert.assertTrue(set.remove(element)); - Assert.assertEquals(0, set.size()); + assertTrue(set.remove(element)); + assertEquals(0, set.size()); } @Test public void testClear() throws Exception { - Assert.assertTrue(set.add(element)); + assertTrue(set.add(element)); - Assert.assertTrue(set.contains(element)); + assertTrue(set.contains(element)); set.clear(); - Assert.assertFalse(set.contains(element)); + assertFalse(set.contains(element)); } @Test public void testIsEmpty() throws Exception { - Assert.assertTrue(set.isEmpty()); + assertTrue(set.isEmpty()); - Assert.assertTrue(set.add(element)); - Assert.assertFalse(set.isEmpty()); + assertTrue(set.add(element)); + assertFalse(set.isEmpty()); set.clear(); - Assert.assertTrue(set.isEmpty()); + assertTrue(set.isEmpty()); } @Test @@ -101,11 +104,11 @@ public class ConcurrentHashSetTest extends Assert { Iterator iterator = set.iterator(); while (iterator.hasNext()) { String e = iterator.next(); - Assert.assertEquals(element, e); + assertEquals(element, e); } } - @Before + @BeforeEach public void setUp() throws Exception { set = new ConcurrentHashSet<>(); element = RandomUtil.randomString(); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodecTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodecTest.java index 8c65351fff..080db1e529 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodecTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/DefaultSensitiveStringCodecTest.java @@ -16,20 +16,20 @@ */ package org.apache.activemq.artemis.utils; +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 static org.junit.jupiter.api.Assertions.fail; + +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -import org.junit.Test; import java.util.HashMap; import java.util.Map; -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.Assert.fail; - public class DefaultSensitiveStringCodecTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -68,7 +68,7 @@ public class DefaultSensitiveStringCodecTest { String decoded = codec.decode(maskedText); logger.debug("encoded value: {}", maskedText); - assertEquals("decoded result not match: " + decoded, decoded, plainText); + assertEquals(decoded, plainText, "decoded result not match: " + decoded); } assertTrue(codec.verify(plainText.toCharArray(), maskedText)); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HashProcessorTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HashProcessorTest.java index 83199b5159..128ed776d9 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HashProcessorTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HashProcessorTest.java @@ -16,16 +16,17 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; -import static org.junit.Assert.assertEquals; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class HashProcessorTest { private static final String USER1_PASSWORD = "password"; @@ -36,7 +37,7 @@ public class HashProcessorTest { private static final String USER3_PASSWORD = "artemis000"; - @Parameterized.Parameters(name = "{index}: testing password {0}") + @Parameters(name = "{index}: testing password {0}") public static Collection data() { return Arrays.asList(new Object[][] { {USER1_PASSWORD, USER1_HASHED_PASSWORD, true}, @@ -57,7 +58,7 @@ public class HashProcessorTest { this.match = match; } - @Test + @TestTemplate public void testPasswordVerification() throws Exception { HashProcessor processor = PasswordMaskingUtil.getHashProcessor(storedPassword); boolean result = processor.compare(password.toCharArray(), storedPassword); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HumanReadableByteCountTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HumanReadableByteCountTest.java index 270ad06a01..dea558b3e0 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HumanReadableByteCountTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/HumanReadableByteCountTest.java @@ -16,13 +16,13 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; public class HumanReadableByteCountTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/IPv6UtilTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/IPv6UtilTest.java index 3709731d72..717d7e072e 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/IPv6UtilTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/IPv6UtilTest.java @@ -16,9 +16,9 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; public class IPv6UtilTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/MaskPasswordResolvingTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/MaskPasswordResolvingTest.java index ba688fcf54..d30b225011 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/MaskPasswordResolvingTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/MaskPasswordResolvingTest.java @@ -16,19 +16,21 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; - -@RunWith(Parameterized.class) -public class MaskPasswordResolvingTest { +@ExtendWith(ParameterizedTestExtension.class) +public class MaskPasswordResolvingTest extends ArtemisTestCase { private static final String plainPassword = "password"; private static final String defaultMaskPassword = "defaultmasked"; @@ -37,7 +39,7 @@ public class MaskPasswordResolvingTest { private static final String oldCustomizedCodecPassword = "secret"; private static final String oldExplicitPlainPassword = "PASSWORD"; - @Parameterized.Parameters(name = "mask({0})password({1})codec({2})") + @Parameters(name = "mask({0})password({1})codec({2})") public static Collection params() { return Arrays.asList(new Object[][]{{null, plainPassword, null}, {null, "ENC(3bdfd94fe8cdf710e7fefa72f809ea90)", null}, @@ -58,7 +60,7 @@ public class MaskPasswordResolvingTest { this.codec = codec; } - @Test + @TestTemplate public void testPasswordResolving() throws Exception { String resolved = PasswordMaskingUtil.resolveMask(maskPassword, password, codec); checkResult(resolved); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/NetworkHealthTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/NetworkHealthTest.java index 28a0ec2316..dcd315a840 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/NetworkHealthTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/NetworkHealthTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.IOException; import java.io.OutputStream; import java.net.Inet6Address; @@ -32,12 +38,10 @@ import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.NetworkHealthCheck; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assume.assumeTrue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class NetworkHealthTest { @@ -87,13 +91,13 @@ public class NetworkHealthTest { } }; - @Before + @BeforeEach public void before() throws Exception { latch.setCount(1); } private void startHTTPServer() throws IOException { - Assert.assertNull(httpServer); + assertNull(httpServer); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8787); httpServer = HttpServer.create(address, 100); httpServer.start(); @@ -119,7 +123,7 @@ public class NetworkHealthTest { } } - @After + @AfterEach public void after() { stopHTTPServer(); for (NetworkHealthCheck check : this.list) { @@ -135,11 +139,11 @@ public class NetworkHealthTest { InetAddress address = InetAddress.getByName(IPV6_LOCAL); - Assert.assertTrue(address instanceof Inet6Address); + assertTrue(address instanceof Inet6Address); - Assert.assertTrue(check.purePing(address)); + assertTrue(check.purePing(address)); - Assert.assertTrue(check.check(address)); + assertTrue(check.check(address)); } @Test @@ -159,9 +163,9 @@ public class NetworkHealthTest { component.stop(); latch.setCount(1); - Assert.assertTrue(latch.await(1, TimeUnit.MINUTES)); + assertTrue(latch.await(1, TimeUnit.MINUTES)); - Assert.assertFalse("NetworkHealthCheck should have no business on restarting the component, the network was never down, hence no check needed!", component.isStarted()); + assertFalse(component.isStarted(), "NetworkHealthCheck should have no business on restarting the component, the network was never down, hence no check needed!"); } @@ -171,7 +175,7 @@ public class NetworkHealthTest { // using two addresses for URI and localhost check.parseAddressList("localhost, , 127.0.0.2"); - Assert.assertEquals(2, check.getAddresses().size()); + assertEquals(2, check.getAddresses().size()); } @Test @@ -180,8 +184,8 @@ public class NetworkHealthTest { // using two addresses for URI and localhost check.parseAddressList("localhost, , 127.0.0.2"); - Assert.assertEquals(2, check.getAddresses().size()); - Assert.assertEquals(0, check.getUrls().size()); + assertEquals(2, check.getAddresses().size()); + assertEquals(0, check.getUrls().size()); } @Test @@ -197,11 +201,11 @@ public class NetworkHealthTest { // Any external IP, to make sure we would use a PING InetAddress address = InetAddress.getByName(localaddress); - Assert.assertTrue(check.check(address)); + assertTrue(check.check(address)); - Assert.assertTrue(check.purePing(address)); + assertTrue(check.purePing(address)); - Assert.assertFalse(check.purePing(INVALID_ADDRESS)); + assertFalse(check.purePing(INVALID_ADDRESS)); } @@ -222,7 +226,7 @@ public class NetworkHealthTest { @Test public void testCheckNoNodes() throws Exception { NetworkHealthCheck check = addCheck(new NetworkHealthCheck()); - Assert.assertTrue(check.check()); + assertTrue(check.check()); } @Test @@ -232,38 +236,38 @@ public class NetworkHealthTest { NetworkHealthCheck check = addCheck(new NetworkHealthCheck(null, 100, 1000)); - Assert.assertTrue(check.check(new URL("http://localhost:8787"))); + assertTrue(check.check(new URL("http://localhost:8787"))); stopHTTPServer(); - Assert.assertFalse(check.check(new URL("http://localhost:8787"))); + assertFalse(check.check(new URL("http://localhost:8787"))); check.addComponent(component); URL url = new URL("http://localhost:8787"); - Assert.assertFalse(check.check(url)); + assertFalse(check.check(url)); startHTTPServer(); - Assert.assertTrue(check.check(url)); + assertTrue(check.check(url)); check.addURL(url); - Assert.assertFalse(latch.await(500, TimeUnit.MILLISECONDS)); - Assert.assertTrue(component.isStarted()); + assertFalse(latch.await(500, TimeUnit.MILLISECONDS)); + assertTrue(component.isStarted()); // stopping the web server should stop the component stopHTTPServer(); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); - Assert.assertFalse(component.isStarted()); + assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertFalse(component.isStarted()); latch.setCount(1); startHTTPServer(); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(component.isStarted()); + assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(component.isStarted()); } @@ -292,8 +296,8 @@ public class NetworkHealthTest { myCheck.check(InetAddress.getByName("127.0.0.1")); - Assert.assertEquals(0, isReacheable.get()); - Assert.assertEquals(1, purePing.get()); + assertEquals(0, isReacheable.get()); + assertEquals(1, purePing.get()); } @Test @@ -320,18 +324,19 @@ public class NetworkHealthTest { myCheck.check(InetAddress.getByName("127.0.0.1")); - Assert.assertEquals(1, isReacheable.get()); - Assert.assertEquals(0, purePing.get()); + assertEquals(1, isReacheable.get()); + assertEquals(0, purePing.get()); } - @Test(timeout = 30_000) + @Test + @Timeout(value = 30_000, unit = TimeUnit.MILLISECONDS) public void testPurePingTimeout() throws Exception { NetworkHealthCheck check = new NetworkHealthCheck(null, 100, 2000); long time = System.currentTimeMillis(); //[RFC1166] reserves the address block 192.0.2.0/24 for test. - Assert.assertFalse(check.purePing(InetAddress.getByName("192.0.2.0"))); - Assert.assertTrue(System.currentTimeMillis() - time >= 2000); + assertFalse(check.purePing(InetAddress.getByName("192.0.2.0"))); + assertTrue(System.currentTimeMillis() - time >= 2000); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java index 6f896a4488..7b523961e2 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PairTest.java @@ -16,11 +16,12 @@ */ package org.apache.activemq.artemis.utils; -import org.apache.activemq.artemis.api.core.Pair; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class PairTest extends Assert { +import org.apache.activemq.artemis.api.core.Pair; +import org.junit.jupiter.api.Test; + +public class PairTest { @Test public void testPair() { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PasswordMaskingUtilTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PasswordMaskingUtilTest.java index f16ab0902a..20d40035f1 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PasswordMaskingUtilTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PasswordMaskingUtilTest.java @@ -16,9 +16,10 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class PasswordMaskingUtilTest { @@ -28,8 +29,10 @@ public class PasswordMaskingUtilTest { assertTrue(codec instanceof DefaultSensitiveStringCodec); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGetCodecUsingInvalidCodec() throws Exception { - PasswordMaskingUtil.getCodec("codec doesn't exist"); + assertThrows(IllegalArgumentException.class, () -> { + PasswordMaskingUtil.getCodec("codec doesn't exist"); + }); } } \ No newline at end of file diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PowerOf2UtilTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PowerOf2UtilTest.java index a74ae8a315..5f1c5443e8 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PowerOf2UtilTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/PowerOf2UtilTest.java @@ -16,27 +16,27 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Assert; -import org.junit.Test; - import static org.apache.activemq.artemis.utils.PowerOf2Util.align; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; public class PowerOf2UtilTest { @Test public void shouldAlignToNextMultipleOfAlignment() { final int alignment = 512; - Assert.assertEquals(0, align(0, alignment)); - Assert.assertEquals(alignment, align(1, alignment)); - Assert.assertEquals(alignment, align(alignment, alignment)); - Assert.assertEquals(alignment * 2, align(alignment + 1, alignment)); + assertEquals(0, align(0, alignment)); + assertEquals(alignment, align(1, alignment)); + assertEquals(alignment, align(alignment, alignment)); + assertEquals(alignment * 2, align(alignment + 1, alignment)); final int remainder = Integer.MAX_VALUE % alignment; final int alignedMax = Integer.MAX_VALUE - remainder; - Assert.assertEquals(alignedMax, align(alignedMax, alignment)); + assertEquals(alignedMax, align(alignedMax, alignment)); //given that Integer.MAX_VALUE is the max value that can be represented with int //the aligned value would be > 2^32, but (int)(2^32) = Integer.MIN_VALUE due to the sign bit - Assert.assertEquals(Integer.MIN_VALUE, align(Integer.MAX_VALUE, alignment)); + assertEquals(Integer.MIN_VALUE, align(Integer.MAX_VALUE, alignment)); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java index 0089686886..80583ae463 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/ReferenceCounterTest.java @@ -16,16 +16,19 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ReferenceCounterTest extends Assert { +public class ReferenceCounterTest { class LatchRunner implements Runnable { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleFutureTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleFutureTest.java index a5ce89ef8d..717acb58bf 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleFutureTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleFutureTest.java @@ -16,14 +16,13 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SimpleFutureTest { +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; +import org.junit.jupiter.api.Test; - @Rule - public ThreadLeakCheckRule threadLeakCheckRule = new ThreadLeakCheckRule(); +public class SimpleFutureTest extends ArtemisTestCase { @Test public void testFuture() throws Exception { @@ -37,7 +36,7 @@ public class SimpleFutureTest { }; t.start(); - Assert.assertEquals(randomStart, simpleFuture.get().longValue()); + assertEquals(randomStart, simpleFuture.get().longValue()); } @@ -60,7 +59,7 @@ public class SimpleFutureTest { } - Assert.assertTrue(failed); + assertTrue(failed); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleStringTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleStringTest.java index 85e579498f..848e4695e9 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleStringTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SimpleStringTest.java @@ -16,12 +16,12 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertTrue; + import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import org.apache.activemq.artemis.api.core.SimpleString; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class SimpleStringTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SizeAwareMetricTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SizeAwareMetricTest.java index 4046075b5c..7846795b90 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SizeAwareMetricTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/SizeAwareMetricTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.utils; +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.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; @@ -24,9 +28,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class SizeAwareMetricTest { @@ -38,11 +41,11 @@ public class SizeAwareMetricTest { } } - @After + @AfterEach public void shutdownExecutor() throws Exception { if (executor != null) { executor.shutdownNow(); - Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); executor = null; } } @@ -66,53 +69,53 @@ public class SizeAwareMetricTest { child.addSize(1, true); } - Assert.assertEquals(4, child.getSize()); - Assert.assertEquals(4, parent.getSize()); - Assert.assertEquals(0, child.getElements()); - Assert.assertEquals(0, parent.getElements()); - Assert.assertFalse(childBoolean.get()); - Assert.assertFalse(parentBoolean.get()); + assertEquals(4, child.getSize()); + assertEquals(4, parent.getSize()); + assertEquals(0, child.getElements()); + assertEquals(0, parent.getElements()); + assertFalse(childBoolean.get()); + assertFalse(parentBoolean.get()); child.addSize(1, true); - Assert.assertEquals(5, child.getSize()); - Assert.assertTrue(childBoolean.get()); - Assert.assertFalse(parentBoolean.get()); - Assert.assertEquals(0, child.getElements()); - Assert.assertEquals(0, parent.getElements()); + assertEquals(5, child.getSize()); + assertTrue(childBoolean.get()); + assertFalse(parentBoolean.get()); + assertEquals(0, child.getElements()); + assertEquals(0, parent.getElements()); child.addSize(-5, true); - Assert.assertEquals(0, child.getSize()); - Assert.assertEquals(0, parent.getSize()); + assertEquals(0, child.getSize()); + assertEquals(0, parent.getSize()); for (int i = 0; i < 5; i++) { child.addSize(1, false); } - Assert.assertEquals(5, child.getSize()); - Assert.assertEquals(5, parent.getSize()); - Assert.assertEquals(5, child.getElements()); - Assert.assertEquals(5, parent.getElements()); - Assert.assertTrue(childBoolean.get()); - Assert.assertFalse(parentBoolean.get()); - Assert.assertTrue(child.isOverElements()); + assertEquals(5, child.getSize()); + assertEquals(5, parent.getSize()); + assertEquals(5, child.getElements()); + assertEquals(5, parent.getElements()); + assertTrue(childBoolean.get()); + assertFalse(parentBoolean.get()); + assertTrue(child.isOverElements()); for (int i = 0; i < 5; i++) { child.addSize(1, false); } - Assert.assertEquals(10, child.getSize()); - Assert.assertEquals(10, parent.getSize()); - Assert.assertEquals(10, child.getElements()); - Assert.assertEquals(10, parent.getElements()); + assertEquals(10, child.getSize()); + assertEquals(10, parent.getSize()); + assertEquals(10, child.getElements()); + assertEquals(10, parent.getElements()); - Assert.assertTrue(childBoolean.get()); - Assert.assertTrue(parentBoolean.get()); - Assert.assertTrue(child.isOverElements()); - Assert.assertFalse(parent.isOverElements()); - Assert.assertTrue(parent.isOverSize()); + assertTrue(childBoolean.get()); + assertTrue(parentBoolean.get()); + assertTrue(child.isOverElements()); + assertFalse(parent.isOverElements()); + assertTrue(parent.isOverSize()); } @@ -174,27 +177,27 @@ public class SizeAwareMetricTest { } flagStart.await(10, TimeUnit.SECONDS); - Assert.assertTrue(latchDone.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(metricOver.get()); - Assert.assertTrue(metric.isOver()); - Assert.assertTrue(metric.isOverSize()); - Assert.assertFalse(metric.isOverElements()); + assertTrue(metricOver.get()); + assertTrue(metric.isOver()); + assertTrue(metric.isOverSize()); + assertFalse(metric.isOverElements()); - Assert.assertTrue(globalMetricOver.get()); - Assert.assertTrue(globalMetric.isOver()); + assertTrue(globalMetricOver.get()); + assertTrue(globalMetric.isOver()); - Assert.assertEquals(1, metricOverCalls.get()); - Assert.assertEquals(1, globalMetricOverCalls.get()); - Assert.assertEquals(0, metricUnderCalls.get()); - Assert.assertEquals(0, globalMetricUnderCalls.get()); + assertEquals(1, metricOverCalls.get()); + assertEquals(1, globalMetricOverCalls.get()); + assertEquals(0, metricUnderCalls.get()); + assertEquals(0, globalMetricUnderCalls.get()); - Assert.assertEquals(ELEMENTS * THREADS, metric.getSize()); - Assert.assertEquals(ELEMENTS * THREADS, metric.getElements()); - Assert.assertEquals(ELEMENTS * THREADS, globalMetric.getSize()); - Assert.assertEquals(ELEMENTS * THREADS, globalMetric.getElements()); + assertEquals(ELEMENTS * THREADS, metric.getSize()); + assertEquals(ELEMENTS * THREADS, metric.getElements()); + assertEquals(ELEMENTS * THREADS, globalMetric.getSize()); + assertEquals(ELEMENTS * THREADS, globalMetric.getElements()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); latchDone.setCount(10); @@ -215,14 +218,14 @@ public class SizeAwareMetricTest { } flagStart.await(10, TimeUnit.SECONDS); - Assert.assertTrue(latchDone.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, globalMetric.getSize()); - Assert.assertEquals(0, globalMetric.getElements()); - Assert.assertEquals(0, metric.getSize()); - Assert.assertEquals(0, metric.getElements()); - Assert.assertFalse(globalMetricOver.get()); - Assert.assertFalse(globalMetric.isOver()); + assertEquals(0, globalMetric.getSize()); + assertEquals(0, globalMetric.getElements()); + assertEquals(0, metric.getSize()); + assertEquals(0, metric.getElements()); + assertFalse(globalMetricOver.get()); + assertFalse(globalMetric.isOver()); } @@ -238,16 +241,16 @@ public class SizeAwareMetricTest { metric.addSize(10, false); } - Assert.assertTrue(over.get()); - Assert.assertEquals(110, metric.getSize()); - Assert.assertEquals(11, metric.getElements()); + assertTrue(over.get()); + assertEquals(110, metric.getSize()); + assertEquals(11, metric.getElements()); metric.addSize(1000, false); for (int i = 0; i < 12; i++) { metric.addSize(-10, false); } - Assert.assertFalse(over.get()); + assertFalse(over.get()); } @Test @@ -266,35 +269,35 @@ public class SizeAwareMetricTest { } metric.addSize(1000, true); - Assert.assertEquals(1110L, metricMain.getSize()); - Assert.assertEquals(11, metricMain.getElements()); - Assert.assertEquals(1110L, metric.getSize()); - Assert.assertEquals(11, metric.getElements()); - Assert.assertTrue(metricMain.isOverElements()); - Assert.assertFalse(metricMain.isOverSize()); - Assert.assertFalse(metric.isOverElements()); - Assert.assertFalse(metric.isOverSize()); - Assert.assertTrue(over.get()); + assertEquals(1110L, metricMain.getSize()); + assertEquals(11, metricMain.getElements()); + assertEquals(1110L, metric.getSize()); + assertEquals(11, metric.getElements()); + assertTrue(metricMain.isOverElements()); + assertFalse(metricMain.isOverSize()); + assertFalse(metric.isOverElements()); + assertFalse(metric.isOverSize()); + assertTrue(over.get()); metric.addSize(-1000, true); - Assert.assertEquals(110L, metricMain.getSize()); - Assert.assertEquals(11, metricMain.getElements()); - Assert.assertTrue(metricMain.isOverElements()); - Assert.assertFalse(metricMain.isOverSize()); - Assert.assertTrue(over.get()); + assertEquals(110L, metricMain.getSize()); + assertEquals(11, metricMain.getElements()); + assertTrue(metricMain.isOverElements()); + assertFalse(metricMain.isOverSize()); + assertTrue(over.get()); for (int i = 0; i < 11; i++) { metric.addSize(-10); } - Assert.assertEquals(0L, metricMain.getSize()); - Assert.assertEquals(0L, metricMain.getElements()); - Assert.assertFalse(metricMain.isOver()); - Assert.assertEquals(0L, metric.getSize()); - Assert.assertEquals(0L, metric.getElements()); - Assert.assertFalse(metric.isOver()); - Assert.assertFalse(over.get()); + assertEquals(0L, metricMain.getSize()); + assertEquals(0L, metricMain.getElements()); + assertFalse(metricMain.isOver()); + assertEquals(0L, metric.getSize()); + assertEquals(0L, metric.getElements()); + assertFalse(metric.isOver()); + assertFalse(over.get()); } @@ -311,28 +314,28 @@ public class SizeAwareMetricTest { } metric.addSize(1000, true); - Assert.assertEquals(1110L, metric.getSize()); - Assert.assertEquals(11, metric.getElements()); - Assert.assertTrue(metric.isOverElements()); - Assert.assertFalse(metric.isOverSize()); - Assert.assertTrue(over.get()); + assertEquals(1110L, metric.getSize()); + assertEquals(11, metric.getElements()); + assertTrue(metric.isOverElements()); + assertFalse(metric.isOverSize()); + assertTrue(over.get()); metric.addSize(-1000, true); - Assert.assertEquals(110L, metric.getSize()); - Assert.assertEquals(11, metric.getElements()); - Assert.assertTrue(metric.isOverElements()); - Assert.assertFalse(metric.isOverSize()); - Assert.assertTrue(over.get()); + assertEquals(110L, metric.getSize()); + assertEquals(11, metric.getElements()); + assertTrue(metric.isOverElements()); + assertFalse(metric.isOverSize()); + assertTrue(over.get()); for (int i = 0; i < 11; i++) { metric.addSize(-10); } - Assert.assertEquals(0L, metric.getSize()); - Assert.assertEquals(0L, metric.getElements()); - Assert.assertFalse(metric.isOver()); - Assert.assertFalse(over.get()); + assertEquals(0L, metric.getSize()); + assertEquals(0L, metric.getElements()); + assertFalse(metric.isOver()); + assertFalse(over.get()); } @Test @@ -397,30 +400,30 @@ public class SizeAwareMetricTest { } flagStart.await(10, TimeUnit.SECONDS); - Assert.assertTrue(latchDone.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone.await(10, TimeUnit.SECONDS)); for (SizeAwareMetric theMetric : metric) { - Assert.assertTrue(theMetric.isOver()); - Assert.assertEquals(ELEMENTS, theMetric.getSize()); - Assert.assertEquals(ELEMENTS, theMetric.getElements()); + assertTrue(theMetric.isOver()); + assertEquals(ELEMENTS, theMetric.getSize()); + assertEquals(ELEMENTS, theMetric.getElements()); } for (AtomicBoolean theBool : metricOverArray) { - Assert.assertTrue(theBool.get()); + assertTrue(theBool.get()); } - Assert.assertTrue(globalMetricOver.get()); - Assert.assertTrue(globalMetric.isOver()); + assertTrue(globalMetricOver.get()); + assertTrue(globalMetric.isOver()); - Assert.assertEquals(10, metricOverCalls.get()); - Assert.assertEquals(1, globalMetricOverCalls.get()); - Assert.assertEquals(0, metricUnderCalls.get()); - Assert.assertEquals(0, globalMetricUnderCalls.get()); + assertEquals(10, metricOverCalls.get()); + assertEquals(1, globalMetricOverCalls.get()); + assertEquals(0, metricUnderCalls.get()); + assertEquals(0, globalMetricUnderCalls.get()); - Assert.assertEquals(ELEMENTS * THREADS, globalMetric.getSize()); - Assert.assertEquals(ELEMENTS * THREADS, globalMetric.getElements()); + assertEquals(ELEMENTS * THREADS, globalMetric.getSize()); + assertEquals(ELEMENTS * THREADS, globalMetric.getElements()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); latchDone.setCount(10); @@ -442,23 +445,23 @@ public class SizeAwareMetricTest { } flagStart.await(10, TimeUnit.SECONDS); - Assert.assertTrue(latchDone.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, globalMetric.getSize()); - Assert.assertEquals(0, globalMetric.getElements()); + assertEquals(0, globalMetric.getSize()); + assertEquals(0, globalMetric.getElements()); for (SizeAwareMetric theMetric : metric) { - Assert.assertEquals(0, theMetric.getSize()); - Assert.assertEquals(0, theMetric.getElements()); + assertEquals(0, theMetric.getSize()); + assertEquals(0, theMetric.getElements()); } - Assert.assertEquals(10, metricOverCalls.get()); - Assert.assertEquals(1, globalMetricOverCalls.get()); - Assert.assertEquals(10, metricUnderCalls.get()); - Assert.assertEquals(1, globalMetricUnderCalls.get()); - Assert.assertFalse(globalMetricOver.get()); - Assert.assertFalse(globalMetric.isOver()); + assertEquals(10, metricOverCalls.get()); + assertEquals(1, globalMetricOverCalls.get()); + assertEquals(10, metricUnderCalls.get()); + assertEquals(1, globalMetricUnderCalls.get()); + assertFalse(globalMetricOver.get()); + assertFalse(globalMetric.isOver()); for (AtomicBoolean theBool : metricOverArray) { - Assert.assertFalse(theBool.get()); + assertFalse(theBool.get()); } } @@ -470,13 +473,13 @@ public class SizeAwareMetricTest { metric.setUnderCallback(() -> over.set(false)); metric.addSize(900); - Assert.assertFalse(over.get()); + assertFalse(over.get()); metric.setMax(800, 700, -1, -1); - Assert.assertTrue(over.get()); + assertTrue(over.get()); metric.addSize(-201); - Assert.assertFalse(over.get()); + assertFalse(over.get()); } @Test @@ -486,9 +489,9 @@ public class SizeAwareMetricTest { metric.setOverCallback(() -> over.set(true)); metric.addSize(100); - Assert.assertEquals(100, metric.getSize()); - Assert.assertEquals(1, metric.getElements()); - Assert.assertFalse(over.get()); + assertEquals(100, metric.getSize()); + assertEquals(1, metric.getElements()); + assertFalse(over.get()); } @Test @@ -503,21 +506,21 @@ public class SizeAwareMetricTest { metric.addSize(10, true); } - Assert.assertEquals(100, metricMain.getSize()); - Assert.assertEquals(100, metric.getSize()); - Assert.assertEquals(0, metricMain.getElements()); - Assert.assertEquals(0, metric.getElements()); + assertEquals(100, metricMain.getSize()); + assertEquals(100, metric.getSize()); + assertEquals(0, metricMain.getElements()); + assertEquals(0, metric.getElements()); for (int i = 0; i < 10; i++) { metric.addSize(10, false); } - Assert.assertEquals(200, metricMain.getSize()); - Assert.assertEquals(200, metric.getSize()); - Assert.assertEquals(10, metricMain.getElements()); - Assert.assertEquals(10, metric.getElements()); + assertEquals(200, metricMain.getSize()); + assertEquals(200, metric.getSize()); + assertEquals(10, metricMain.getElements()); + assertEquals(10, metric.getElements()); - Assert.assertFalse(over.get()); + assertFalse(over.get()); } @Test @@ -528,8 +531,8 @@ public class SizeAwareMetricTest { metric.setOverCallback(() -> over.set(true)); metric.setMax(0, 0, 0, 0); - Assert.assertFalse(over.get()); - Assert.assertFalse(metric.isOver()); + assertFalse(over.get()); + assertFalse(metric.isOver()); } @Test @@ -542,36 +545,36 @@ public class SizeAwareMetricTest { metric.addSize(2500, true); - Assert.assertTrue(over.get()); + assertTrue(over.get()); metric.addSize(1000); - Assert.assertTrue(metric.isOverSize()); + assertTrue(metric.isOverSize()); metric.addSize(-2500, true); // Even though we are free from maxSize, we are still bound by maxElements, it should still be over - Assert.assertTrue(over.get()); - Assert.assertTrue("Switch did not work", metric.isOverElements()); + assertTrue(over.get()); + assertTrue(metric.isOverElements(), "Switch did not work"); - Assert.assertEquals(1, metric.getElements()); - Assert.assertEquals(1000, metric.getSize()); + assertEquals(1, metric.getElements()); + assertEquals(1000, metric.getSize()); metric.addSize(5000, true); - Assert.assertTrue(metric.isOverElements()); - Assert.assertEquals(6000, metric.getSize()); + assertTrue(metric.isOverElements()); + assertEquals(6000, metric.getSize()); metric.addSize(-1000); - Assert.assertTrue(metric.isOverSize()); - Assert.assertEquals(0, metric.getElements()); - Assert.assertEquals(5000, metric.getSize()); + assertTrue(metric.isOverSize()); + assertEquals(0, metric.getElements()); + assertEquals(5000, metric.getSize()); metric.addSize(-5000, true); - Assert.assertFalse(metric.isOver()); - Assert.assertEquals(0, metric.getSize()); - Assert.assertEquals(0, metric.getElements()); + assertFalse(metric.isOver()); + assertEquals(0, metric.getSize()); + assertEquals(0, metric.getElements()); } @@ -630,20 +633,20 @@ public class SizeAwareMetricTest { }); } - Assert.assertTrue(done.await(10, TimeUnit.SECONDS)); + assertTrue(done.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, metric.getSize()); - Assert.assertEquals(0, metric.getElements()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, metric.getSize()); + assertEquals(0, metric.getElements()); + assertEquals(0, errors.get()); } @Test public void testConsistency() { SizeAwareMetric metric = new SizeAwareMetric(-1, -1, -1, -1); - Assert.assertFalse(metric.isSizeEnabled()); - Assert.assertFalse(metric.isElementsEnabled()); + assertFalse(metric.isSizeEnabled()); + assertFalse(metric.isElementsEnabled()); metric.setMax(1, 1, 1, 1); - Assert.assertTrue(metric.isSizeEnabled()); - Assert.assertTrue(metric.isElementsEnabled()); + assertTrue(metric.isSizeEnabled()); + assertTrue(metric.isElementsEnabled()); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TableOutTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TableOutTest.java index 01dafa2c36..c8bd830b86 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TableOutTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TableOutTest.java @@ -19,8 +19,8 @@ package org.apache.activemq.artemis.utils; import java.util.ArrayList; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TableOutTest { @@ -29,10 +29,10 @@ public class TableOutTest { String bigCell = "1234554321321"; TableOut tableOut = new TableOut("|", 0, new int[] {10, 3, 3}); ArrayList lines = tableOut.splitLine(bigCell, 5); - Assert.assertEquals(3, lines.size()); - Assert.assertEquals("12345", lines.get(0)); - Assert.assertEquals("54321", lines.get(1)); - Assert.assertEquals("321", lines.get(2)); + Assertions.assertEquals(3, lines.size()); + Assertions.assertEquals("12345", lines.get(0)); + Assertions.assertEquals("54321", lines.get(1)); + Assertions.assertEquals("321", lines.get(2)); } @Test @@ -40,10 +40,10 @@ public class TableOutTest { String bigCell = "1234532132"; TableOut tableOut = new TableOut("|", 2, new int[] {10, 3, 3}); ArrayList lines = tableOut.splitLine(bigCell, 5); - Assert.assertEquals(3, lines.size()); - Assert.assertEquals("12345", lines.get(0)); - Assert.assertEquals(" 321", lines.get(1)); - Assert.assertEquals(" 32", lines.get(2)); + Assertions.assertEquals(3, lines.size()); + Assertions.assertEquals("12345", lines.get(0)); + Assertions.assertEquals(" 321", lines.get(1)); + Assertions.assertEquals(" 32", lines.get(2)); } @Test diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TimeUnitsTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TimeUnitsTest.java index 32913c7e11..cffef8104a 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TimeUnitsTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TimeUnitsTest.java @@ -16,24 +16,25 @@ */ package org.apache.activemq.artemis.utils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class TimeUnitsTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File folder; @Test public void testWaitOnBoolean() throws IOException { - File tmpFile = folder.newFile("myfile.txt"); + File tmpFile = File.createTempFile("myfile", ".txt", folder); assertTrue(tmpFile.exists()); long begin = System.currentTimeMillis(); boolean result = TimeUtils.waitOnBoolean(false, 100, tmpFile::exists); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConcurrencyTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConcurrencyTest.java index ceeb733d6b..72980898b1 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConcurrencyTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConcurrencyTest.java @@ -16,8 +16,9 @@ */ package org.apache.activemq.artemis.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ConcurrentModificationException; import java.util.concurrent.CountDownLatch; @@ -27,8 +28,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.collections.TypedProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TypedPropertiesConcurrencyTest { @@ -77,7 +77,7 @@ public class TypedPropertiesConcurrencyTest { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdown(); - Assert.assertFalse(hasError.get()); + assertFalse(hasError.get()); } @Test @@ -127,7 +127,7 @@ public class TypedPropertiesConcurrencyTest { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdown(); - Assert.assertFalse(hasError.get()); + assertFalse(hasError.get()); } @Test diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConversionTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConversionTest.java index 5eee3e98e4..520ddf18dc 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConversionTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesConversionTest.java @@ -16,12 +16,18 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.collections.TypedProperties; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TypedPropertiesConversionTest { @@ -32,7 +38,7 @@ public class TypedPropertiesConversionTest { private final SimpleString unknownKey = new SimpleString("this.key.is.never.used"); - @Before + @BeforeEach public void setUp() throws Exception { key = RandomUtil.randomSimpleString(); props = new TypedProperties(); @@ -43,20 +49,20 @@ public class TypedPropertiesConversionTest { Boolean val = RandomUtil.randomBoolean(); props.putBooleanProperty(key, val); - Assert.assertEquals(val, props.getBooleanProperty(key)); - Assert.assertEquals(new SimpleString(Boolean.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getBooleanProperty(key)); + assertEquals(new SimpleString(Boolean.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Boolean.toString(val))); - Assert.assertEquals(val, props.getBooleanProperty(key)); + assertEquals(val, props.getBooleanProperty(key)); try { props.putByteProperty(key, RandomUtil.randomByte()); props.getBooleanProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } - Assert.assertFalse(props.getBooleanProperty(unknownKey)); + assertFalse(props.getBooleanProperty(unknownKey)); } @Test @@ -64,19 +70,19 @@ public class TypedPropertiesConversionTest { Character val = RandomUtil.randomChar(); props.putCharProperty(key, val); - Assert.assertEquals(val, props.getCharProperty(key)); - Assert.assertEquals(new SimpleString(Character.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getCharProperty(key)); + assertEquals(new SimpleString(Character.toString(val)), props.getSimpleStringProperty(key)); try { props.putByteProperty(key, RandomUtil.randomByte()); props.getCharProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getCharProperty(unknownKey); - Assert.fail(); + fail(); } catch (NullPointerException e) { } } @@ -86,36 +92,36 @@ public class TypedPropertiesConversionTest { Byte val = RandomUtil.randomByte(); props.putByteProperty(key, val); - Assert.assertEquals(val, props.getByteProperty(key)); - Assert.assertEquals(new SimpleString(Byte.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getByteProperty(key)); + assertEquals(new SimpleString(Byte.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Byte.toString(val))); - Assert.assertEquals(val, props.getByteProperty(key)); + assertEquals(val, props.getByteProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getByteProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getByteProperty(unknownKey); - Assert.fail(); + fail(); } catch (NumberFormatException e) { } } @Test public void testNoByteProperty() { - Assert.assertEquals(0, props.size()); - Assert.assertNull(props.getByteProperty(key, () -> null)); + assertEquals(0, props.size()); + assertNull(props.getByteProperty(key, () -> null)); props.putByteProperty(key.concat('0'), RandomUtil.randomByte()); - Assert.assertEquals(1, props.size()); - Assert.assertNull(props.getByteProperty(key, () -> null)); + assertEquals(1, props.size()); + assertNull(props.getByteProperty(key, () -> null)); props.putNullValue(key); - Assert.assertTrue(props.containsProperty(key)); - Assert.assertNull(props.getByteProperty(key, () -> null)); + assertTrue(props.containsProperty(key)); + assertNull(props.getByteProperty(key, () -> null)); } @Test @@ -123,26 +129,26 @@ public class TypedPropertiesConversionTest { Integer val = RandomUtil.randomInt(); props.putIntProperty(key, val); - Assert.assertEquals(val, props.getIntProperty(key)); - Assert.assertEquals(new SimpleString(Integer.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getIntProperty(key)); + assertEquals(new SimpleString(Integer.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Integer.toString(val))); - Assert.assertEquals(val, props.getIntProperty(key)); + assertEquals(val, props.getIntProperty(key)); Byte byteVal = RandomUtil.randomByte(); props.putByteProperty(key, byteVal); - Assert.assertEquals(Integer.valueOf(byteVal), props.getIntProperty(key)); + assertEquals(Integer.valueOf(byteVal), props.getIntProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getIntProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getIntProperty(unknownKey); - Assert.fail(); + fail(); } catch (NumberFormatException e) { } } @@ -152,34 +158,34 @@ public class TypedPropertiesConversionTest { Long val = RandomUtil.randomLong(); props.putLongProperty(key, val); - Assert.assertEquals(val, props.getLongProperty(key)); - Assert.assertEquals(new SimpleString(Long.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getLongProperty(key)); + assertEquals(new SimpleString(Long.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Long.toString(val))); - Assert.assertEquals(val, props.getLongProperty(key)); + assertEquals(val, props.getLongProperty(key)); Byte byteVal = RandomUtil.randomByte(); props.putByteProperty(key, byteVal); - Assert.assertEquals(Long.valueOf(byteVal), props.getLongProperty(key)); + assertEquals(Long.valueOf(byteVal), props.getLongProperty(key)); Short shortVal = RandomUtil.randomShort(); props.putShortProperty(key, shortVal); - Assert.assertEquals(Long.valueOf(shortVal), props.getLongProperty(key)); + assertEquals(Long.valueOf(shortVal), props.getLongProperty(key)); Integer intVal = RandomUtil.randomInt(); props.putIntProperty(key, intVal); - Assert.assertEquals(Long.valueOf(intVal), props.getLongProperty(key)); + assertEquals(Long.valueOf(intVal), props.getLongProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getLongProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getLongProperty(unknownKey); - Assert.fail(); + fail(); } catch (NumberFormatException e) { } } @@ -189,22 +195,22 @@ public class TypedPropertiesConversionTest { Double val = RandomUtil.randomDouble(); props.putDoubleProperty(key, val); - Assert.assertEquals(val, props.getDoubleProperty(key)); - Assert.assertEquals(new SimpleString(Double.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getDoubleProperty(key)); + assertEquals(new SimpleString(Double.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Double.toString(val))); - Assert.assertEquals(val, props.getDoubleProperty(key)); + assertEquals(val, props.getDoubleProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getDoubleProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getDoubleProperty(unknownKey); - Assert.fail(); + fail(); } catch (Exception e) { } } @@ -214,23 +220,23 @@ public class TypedPropertiesConversionTest { Float val = RandomUtil.randomFloat(); props.putFloatProperty(key, val); - Assert.assertEquals(val, props.getFloatProperty(key)); - Assert.assertEquals(Double.valueOf(val), props.getDoubleProperty(key)); - Assert.assertEquals(new SimpleString(Float.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getFloatProperty(key)); + assertEquals(Double.valueOf(val), props.getDoubleProperty(key)); + assertEquals(new SimpleString(Float.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Float.toString(val))); - Assert.assertEquals(val, props.getFloatProperty(key)); + assertEquals(val, props.getFloatProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getFloatProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getFloatProperty(unknownKey); - Assert.fail(); + fail(); } catch (Exception e) { } } @@ -240,27 +246,27 @@ public class TypedPropertiesConversionTest { Short val = RandomUtil.randomShort(); props.putShortProperty(key, val); - Assert.assertEquals(val, props.getShortProperty(key)); - Assert.assertEquals(Integer.valueOf(val), props.getIntProperty(key)); - Assert.assertEquals(new SimpleString(Short.toString(val)), props.getSimpleStringProperty(key)); + assertEquals(val, props.getShortProperty(key)); + assertEquals(Integer.valueOf(val), props.getIntProperty(key)); + assertEquals(new SimpleString(Short.toString(val)), props.getSimpleStringProperty(key)); props.putSimpleStringProperty(key, new SimpleString(Short.toString(val))); - Assert.assertEquals(val, props.getShortProperty(key)); + assertEquals(val, props.getShortProperty(key)); Byte byteVal = RandomUtil.randomByte(); props.putByteProperty(key, byteVal); - Assert.assertEquals(Short.valueOf(byteVal), props.getShortProperty(key)); + assertEquals(Short.valueOf(byteVal), props.getShortProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getShortProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } try { props.getShortProperty(unknownKey); - Assert.fail(); + fail(); } catch (NumberFormatException e) { } } @@ -269,7 +275,7 @@ public class TypedPropertiesConversionTest { public void testSimpleStringProperty() throws Exception { SimpleString strVal = RandomUtil.randomSimpleString(); props.putSimpleStringProperty(key, strVal); - Assert.assertEquals(strVal, props.getSimpleStringProperty(key)); + assertEquals(strVal, props.getSimpleStringProperty(key)); } @Test @@ -277,16 +283,16 @@ public class TypedPropertiesConversionTest { byte[] val = RandomUtil.randomBytes(); props.putBytesProperty(key, val); - Assert.assertArrayEquals(val, props.getBytesProperty(key)); + assertArrayEquals(val, props.getBytesProperty(key)); try { props.putBooleanProperty(key, RandomUtil.randomBoolean()); props.getBytesProperty(key); - Assert.fail(); + fail(); } catch (ActiveMQPropertyConversionException e) { } - Assert.assertNull(props.getBytesProperty(unknownKey)); + assertNull(props.getBytesProperty(unknownKey)); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesTest.java index 2d5a5ffe7b..3b24cd41ee 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/TypedPropertiesTest.java @@ -16,6 +16,17 @@ */ package org.apache.activemq.artemis.utils; +import static org.apache.activemq.artemis.utils.collections.TypedProperties.searchProperty; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @@ -26,19 +37,16 @@ import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.collections.TypedProperties; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.apache.activemq.artemis.utils.collections.TypedProperties.searchProperty; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TypedPropertiesTest { private static void assertEqualsTypeProperties(final TypedProperties expected, final TypedProperties actual) { - Assert.assertNotNull(expected); - Assert.assertNotNull(actual); - Assert.assertEquals(expected.getEncodeSize(), actual.getEncodeSize()); - Assert.assertEquals(expected.getPropertyNames(), actual.getPropertyNames()); + assertNotNull(expected); + assertNotNull(actual); + assertEquals(expected.getEncodeSize(), actual.getEncodeSize()); + assertEquals(expected.getPropertyNames(), actual.getPropertyNames()); Iterator iterator = actual.getPropertyNames().iterator(); while (iterator.hasNext()) { SimpleString key = iterator.next(); @@ -47,9 +55,9 @@ public class TypedPropertiesTest { if (expectedValue instanceof byte[] && actualValue instanceof byte[]) { byte[] expectedBytes = (byte[]) expectedValue; byte[] actualBytes = (byte[]) actualValue; - Assert.assertArrayEquals(expectedBytes, actualBytes); + assertArrayEquals(expectedBytes, actualBytes); } else { - Assert.assertEquals(expectedValue, actualValue); + assertEquals(expectedValue, actualValue); } } } @@ -66,80 +74,81 @@ public class TypedPropertiesTest { TypedProperties copy = new TypedProperties(props); - Assert.assertEquals(props.getEncodeSize(), copy.getEncodeSize()); - Assert.assertEquals(props.getPropertyNames(), copy.getPropertyNames()); + assertEquals(props.getEncodeSize(), copy.getEncodeSize()); + assertEquals(props.getPropertyNames(), copy.getPropertyNames()); - Assert.assertTrue(copy.containsProperty(key)); - Assert.assertEquals(props.getProperty(key), copy.getProperty(key)); + assertTrue(copy.containsProperty(key)); + assertEquals(props.getProperty(key), copy.getProperty(key)); } @Test public void testRemove() throws Exception { props.putSimpleStringProperty(key, RandomUtil.randomSimpleString()); - Assert.assertTrue(props.containsProperty(key)); - Assert.assertNotNull(props.getProperty(key)); + assertTrue(props.containsProperty(key)); + assertNotNull(props.getProperty(key)); props.removeProperty(key); - Assert.assertFalse(props.containsProperty(key)); - Assert.assertNull(props.getProperty(key)); + assertFalse(props.containsProperty(key)); + assertNull(props.getProperty(key)); } @Test public void testClear() throws Exception { props.putSimpleStringProperty(key, RandomUtil.randomSimpleString()); - Assert.assertTrue(props.containsProperty(key)); - Assert.assertNotNull(props.getProperty(key)); + assertTrue(props.containsProperty(key)); + assertNotNull(props.getProperty(key)); - Assert.assertTrue("encodeSize <= " + 0, props.getEncodeSize() > 0); + assertTrue(props.getEncodeSize() > 0, "encodeSize <= " + 0); props.clear(); - Assert.assertEquals(1, props.getEncodeSize()); + assertEquals(1, props.getEncodeSize()); - Assert.assertFalse(props.containsProperty(key)); - Assert.assertNull(props.getProperty(key)); + assertFalse(props.containsProperty(key)); + assertNull(props.getProperty(key)); } @Test public void testKey() throws Exception { props.putBooleanProperty(key, true); - boolean bool = (Boolean) props.getProperty(key); - Assert.assertEquals(true, bool); + Boolean bool = (Boolean) props.getProperty(key); + assertNotNull(bool); + assertTrue(bool); props.putCharProperty(key, 'a'); char c = (Character) props.getProperty(key); - Assert.assertEquals('a', c); + assertEquals('a', c); } @Test public void testGetPropertyOnEmptyProperties() throws Exception { - Assert.assertFalse(props.containsProperty(key)); - Assert.assertNull(props.getProperty(key)); + assertFalse(props.containsProperty(key)); + assertNull(props.getProperty(key)); } @Test public void testRemovePropertyOnEmptyProperties() throws Exception { - Assert.assertFalse(props.containsProperty(key)); - Assert.assertNull(props.removeProperty(key)); + assertFalse(props.containsProperty(key)); + assertNull(props.removeProperty(key)); } @Test public void testNullProperty() throws Exception { props.putSimpleStringProperty(key, null); - Assert.assertTrue(props.containsProperty(key)); - Assert.assertNull(props.getProperty(key)); + assertTrue(props.containsProperty(key)); + assertNull(props.getProperty(key)); } @Test public void testBytesPropertyWithNull() throws Exception { props.putBytesProperty(key, null); - Assert.assertTrue(props.containsProperty(key)); + assertTrue(props.containsProperty(key)); byte[] bb = (byte[]) props.getProperty(key); - Assert.assertNull(bb); + assertNull(bb); } @Test @@ -155,27 +164,27 @@ public class TypedPropertiesTest { props.putTypedProperties(otherProps); long ll = props.getLongProperty(longKey); - Assert.assertEquals(longValue, ll); + assertEquals(longValue, ll); SimpleString ss = props.getSimpleStringProperty(simpleStringKey); - Assert.assertEquals(simpleStringValue, ss); + assertEquals(simpleStringValue, ss); } @Test public void testEmptyTypedProperties() throws Exception { - Assert.assertEquals(0, props.getPropertyNames().size()); + assertEquals(0, props.getPropertyNames().size()); props.putTypedProperties(new TypedProperties()); - Assert.assertEquals(0, props.getPropertyNames().size()); + assertEquals(0, props.getPropertyNames().size()); } @Test public void testNullTypedProperties() throws Exception { - Assert.assertEquals(0, props.getPropertyNames().size()); + assertEquals(0, props.getPropertyNames().size()); props.putTypedProperties(null); - Assert.assertEquals(0, props.getPropertyNames().size()); + assertEquals(0, props.getPropertyNames().size()); } @Test @@ -198,7 +207,7 @@ public class TypedPropertiesTest { ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024); props.encode(buffer.byteBuf()); - Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex()); + assertEquals(props.getEncodeSize(), buffer.writerIndex()); TypedProperties decodedProps = new TypedProperties(); decodedProps.decode(buffer.byteBuf()); @@ -211,7 +220,7 @@ public class TypedPropertiesTest { props.removeProperty(keyToRemove); props.encode(buffer.byteBuf()); - Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex()); + assertEquals(props.getEncodeSize(), buffer.writerIndex()); } @Test @@ -221,7 +230,7 @@ public class TypedPropertiesTest { ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024); emptyProps.encode(buffer.byteBuf()); - Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex()); + assertEquals(props.getEncodeSize(), buffer.writerIndex()); TypedProperties decodedProps = new TypedProperties(); decodedProps.decode(buffer.byteBuf()); @@ -234,23 +243,23 @@ public class TypedPropertiesTest { @Test public void testCannotClearInternalPropertiesIfEmpty() { TypedProperties properties = new TypedProperties(); - Assert.assertFalse(properties.clearInternalProperties()); + assertFalse(properties.clearInternalProperties()); } @Test public void testClearInternalPropertiesIfAny() { TypedProperties properties = new TypedProperties(PROP_NAME::equals); properties.putBooleanProperty(PROP_NAME, RandomUtil.randomBoolean()); - Assert.assertTrue(properties.clearInternalProperties()); - Assert.assertFalse(properties.containsProperty(PROP_NAME)); + assertTrue(properties.clearInternalProperties()); + assertFalse(properties.containsProperty(PROP_NAME)); } @Test public void testCannotClearInternalPropertiesTwiceIfAny() { TypedProperties properties = new TypedProperties(PROP_NAME::equals); properties.putBooleanProperty(PROP_NAME, RandomUtil.randomBoolean()); - Assert.assertTrue(properties.clearInternalProperties()); - Assert.assertFalse(properties.clearInternalProperties()); + assertTrue(properties.clearInternalProperties()); + assertFalse(properties.clearInternalProperties()); } @Test @@ -259,7 +268,7 @@ public class TypedPropertiesTest { ByteBuf buf = Unpooled.buffer(Byte.BYTES, Byte.BYTES); props.encode(buf); buf.resetReaderIndex(); - Assert.assertFalse("There is no property", searchProperty(SimpleString.toSimpleString(""), buf, 0)); + assertFalse(searchProperty(SimpleString.toSimpleString(""), buf, 0), "There is no property"); } @Test @@ -282,50 +291,56 @@ public class TypedPropertiesTest { ByteBuf buf = Unpooled.buffer(); props.encode(buf); buf.resetReaderIndex(); - Assert.assertFalse(searchProperty(value, buf, 0)); + assertFalse(searchProperty(value, buf, 0)); props.forEachKey(key -> { - Assert.assertTrue(searchProperty(key, buf, 0)); - Assert.assertTrue(searchProperty(SimpleString.toSimpleString(key.toString()), buf, 0)); + assertTrue(searchProperty(key, buf, 0)); + assertTrue(searchProperty(SimpleString.toSimpleString(key.toString()), buf, 0)); // concat a string just to check if the search won't perform an eager search to find the string pattern - Assert.assertFalse(searchProperty(key.concat(" "), buf, 0)); + assertFalse(searchProperty(key.concat(" "), buf, 0)); }); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testSearchPartiallyEncodedBuffer() { - final int expectedLength = Integer.BYTES + Byte.BYTES; - ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength); - buf.writeByte(DataConstants.NOT_NULL); - buf.writeInt(1); - buf.resetReaderIndex(); - searchProperty(SimpleString.toSimpleString(" "), buf, 0); + assertThrows(IndexOutOfBoundsException.class, () -> { + final int expectedLength = Integer.BYTES + Byte.BYTES; + ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength); + buf.writeByte(DataConstants.NOT_NULL); + buf.writeInt(1); + buf.resetReaderIndex(); + searchProperty(SimpleString.toSimpleString(" "), buf, 0); + }); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testSearchPartiallyEncodedString() { - final int expectedLength = Integer.BYTES + Byte.BYTES + Integer.BYTES; - ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength); - buf.writeByte(DataConstants.NOT_NULL); - buf.writeInt(1); - //SimpleString::data length - buf.writeInt(2); - buf.resetReaderIndex(); - searchProperty(SimpleString.toSimpleString("a"), buf, 0); + assertThrows(IndexOutOfBoundsException.class, () -> { + final int expectedLength = Integer.BYTES + Byte.BYTES + Integer.BYTES; + ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength); + buf.writeByte(DataConstants.NOT_NULL); + buf.writeInt(1); + //SimpleString::data length + buf.writeInt(2); + buf.resetReaderIndex(); + searchProperty(SimpleString.toSimpleString("a"), buf, 0); + }); } - @Test(expected = IllegalStateException.class) + @Test public void testSearchWithInvalidTypeBeforeEnd() { - ByteBuf buf = Unpooled.buffer(); - buf.writeByte(DataConstants.NOT_NULL); - // fake 2 properties - buf.writeInt(2); - // 1 key with length 2 - buf.writeInt(2); - buf.writeShort(3); - // invalid type - buf.writeByte(Byte.MIN_VALUE); - buf.resetReaderIndex(); - searchProperty(SimpleString.toSimpleString(""), buf, 0); + assertThrows(IllegalStateException.class, () -> { + ByteBuf buf = Unpooled.buffer(); + buf.writeByte(DataConstants.NOT_NULL); + // fake 2 properties + buf.writeInt(2); + // 1 key with length 2 + buf.writeInt(2); + buf.writeShort(3); + // invalid type + buf.writeByte(Byte.MIN_VALUE); + buf.resetReaderIndex(); + searchProperty(SimpleString.toSimpleString(""), buf, 0); + }); } @Test @@ -340,10 +355,10 @@ public class TypedPropertiesTest { // invalid type buf.writeByte(Byte.MIN_VALUE); buf.resetReaderIndex(); - Assert.assertFalse(searchProperty(SimpleString.toSimpleString(""), buf, 0)); + assertFalse(searchProperty(SimpleString.toSimpleString(""), buf, 0)); } - @Before + @BeforeEach public void setUp() throws Exception { props = new TypedProperties(); key = RandomUtil.randomSimpleString(); @@ -363,7 +378,7 @@ public class TypedPropertiesTest { bb.resetReaderIndex(); final TypedProperties.StringValue expectedPooled = pool.getOrCreate(bb); bb.resetReaderIndex(); - Assert.assertSame(expectedPooled, pool.getOrCreate(bb)); + assertSame(expectedPooled, pool.getOrCreate(bb)); bb.resetReaderIndex(); } } @@ -374,7 +389,7 @@ public class TypedPropertiesTest { final ByteBuf bb = Unpooled.buffer(tooLong.sizeof(), tooLong.sizeof()); SimpleString.writeSimpleString(bb, tooLong); final TypedProperties.StringValue.ByteBufStringValuePool pool = new TypedProperties.StringValue.ByteBufStringValuePool(1, tooLong.length() - 1); - Assert.assertNotSame(pool.getOrCreate(bb), pool.getOrCreate(bb.resetReaderIndex())); + assertNotSame(pool.getOrCreate(bb), pool.getOrCreate(bb.resetReaderIndex())); } @Test @@ -406,6 +421,6 @@ public class TypedPropertiesTest { t.join(); - Assert.assertFalse(error.get()); + assertFalse(error.get()); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java index 4316c9ed44..5248f5ba48 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/URIParserTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.URI; import java.util.HashMap; import java.util.Map; @@ -25,8 +28,7 @@ import org.apache.activemq.artemis.utils.uri.BeanSupport; import org.apache.activemq.artemis.utils.uri.URIFactory; import org.apache.activemq.artemis.utils.uri.URISchema; import org.apache.activemq.artemis.utils.uri.URISupport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class URIParserTest { @@ -40,12 +42,12 @@ public class URIParserTest { FruitParser parser = new FruitParser(); Fruit fruit = (Fruit) parser.newObject(new URI("fruit://some:guy@fair-market:3030?color=green&fluentName=something"), null); - Assert.assertEquals("fruit", fruit.getName()); - Assert.assertEquals(3030, fruit.getPort()); - Assert.assertEquals("fair-market", fruit.getHost()); - Assert.assertEquals("some:guy", fruit.getUserInfo()); - Assert.assertEquals("green", fruit.getColor()); - Assert.assertEquals("something", fruit.getFluentName()); + assertEquals("fruit", fruit.getName()); + assertEquals(3030, fruit.getPort()); + assertEquals("fair-market", fruit.getHost()); + assertEquals("some:guy", fruit.getUserInfo()); + assertEquals("green", fruit.getColor()); + assertEquals("something", fruit.getFluentName()); } @@ -65,8 +67,8 @@ public class URIParserTest { Fruit newFruit = (Fruit) parser.newObject(uri, "something"); - Assert.assertEquals(myFruit.getHost(), newFruit.getHost()); - Assert.assertEquals(myFruit.getFluentName(), newFruit.getFluentName()); + assertEquals(myFruit.getHost(), newFruit.getHost()); + assertEquals(myFruit.getFluentName(), newFruit.getFluentName()); } @@ -79,9 +81,9 @@ public class URIParserTest { public void testSchemaNoHosProperty() throws Throwable { FruitParser parser = new FruitParser(); FruitBase fruit = parser.newObject(new URI("base://some:guy@fair-market:3030?color=green&fluentName=something"), null); - Assert.assertEquals("base", fruit.getName()); - Assert.assertEquals("green", fruit.getColor()); - Assert.assertEquals("something", fruit.getFluentName()); + assertEquals("base", fruit.getName()); + assertEquals("green", fruit.getColor()); + assertEquals("something", fruit.getFluentName()); } /** @@ -94,28 +96,28 @@ public class URIParserTest { FruitParser parser = new FruitParser(); Fruit fruit = (Fruit) parser.newObject(new URI("fruit://some:guy@port?color=green&fluentName=something"), null); - Assert.assertEquals("fruit", fruit.getName()); - Assert.assertEquals("green", fruit.getColor()); - Assert.assertEquals("something", fruit.getFluentName()); + assertEquals("fruit", fruit.getName()); + assertEquals("green", fruit.getColor()); + assertEquals("something", fruit.getFluentName()); } @Test public void testQueryConversion() throws Exception { Map query = new HashMap<>(); String queryString = URISupport.createQueryString(query); - Assert.assertTrue(queryString.isEmpty()); + assertTrue(queryString.isEmpty()); query.put("key1", "value1"); queryString = URISupport.createQueryString(query); - Assert.assertEquals("key1=value1", queryString); + assertEquals("key1=value1", queryString); query.put("key3", "value3"); queryString = URISupport.createQueryString(query); - Assert.assertEquals("key1=value1&key3=value3", queryString); + assertEquals("key1=value1&key3=value3", queryString); query.put("key2", "value2"); queryString = URISupport.createQueryString(query); - Assert.assertEquals("key1=value1&key2=value2&key3=value3", queryString); + assertEquals("key1=value1&key2=value2&key3=value3", queryString); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/WaitTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/WaitTest.java index aa49d1ce4b..f0d73c9ee5 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/WaitTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/WaitTest.java @@ -16,10 +16,12 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class WaitTest { @@ -27,9 +29,9 @@ public class WaitTest { public void testWait() { AtomicInteger intValue = new AtomicInteger(0); - Assert.assertFalse(Wait.waitFor(() -> intValue.get() == 1, 100, 10)); + assertFalse(Wait.waitFor(() -> intValue.get() == 1, 100, 10)); intValue.set(1); - Assert.assertTrue(Wait.waitFor(() -> intValue.get() == 1, 100, 10)); + assertTrue(Wait.waitFor(() -> intValue.get() == 1, 100, 10)); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/XmlProviderTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/XmlProviderTest.java index 86ce633949..931081add6 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/XmlProviderTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/XmlProviderTest.java @@ -16,10 +16,15 @@ */ package org.apache.activemq.artemis.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Validator; + import java.io.File; import java.lang.invoke.MethodHandles; import java.util.Arrays; @@ -27,20 +32,20 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.util.ArtemisTestCase; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class XmlProviderTest extends ArtemisTestCase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -49,12 +54,12 @@ public class XmlProviderTest extends ArtemisTestCase { protected boolean xxeEnabled; - @Parameterized.Parameters(name = "xxeEnabled={0}") + @Parameters(name = "xxeEnabled={0}") public static Collection getParameters() { return Arrays.asList(new Boolean[]{true, false}); } - @BeforeClass + @BeforeAll public static void beforeAll() { if (origXxeEnabled == null) { origXxeEnabled = XmlProvider.isXxeEnabled(); @@ -63,7 +68,7 @@ public class XmlProviderTest extends ArtemisTestCase { logger.trace("BeforeAll - origXxeEnabled={}, isXxeEnabled={}", origXxeEnabled, XmlProvider.isXxeEnabled()); } - @AfterClass + @AfterAll public static void afterAll() { logger.trace("AfterAll - origXxeEnabled={}, isXxeEnabled={} ", origXxeEnabled, XmlProvider.isXxeEnabled()); if (origXxeEnabled != null) { @@ -72,7 +77,7 @@ public class XmlProviderTest extends ArtemisTestCase { } } - @Before + @BeforeEach public void setUp() { logger.trace("Running setUp - xxeEnabled={}", xxeEnabled); XmlProvider.setXxeEnabled(xxeEnabled); @@ -82,17 +87,17 @@ public class XmlProviderTest extends ArtemisTestCase { this.xxeEnabled = xxeEnabled; } - @Test + @TestTemplate public void testDocument() throws Exception { DocumentBuilder documentBuilder = XmlProvider.newDocumentBuilder(); Document document = documentBuilder.parse(new File(getClass().getResource("/document.xml").toURI())); Element documentElement = document.getDocumentElement(); - Assert.assertEquals("t:book", documentElement.getTagName()); - Assert.assertEquals(1, documentElement.getElementsByTagName("title").getLength()); + assertEquals("t:book", documentElement.getTagName()); + assertEquals(1, documentElement.getElementsByTagName("title").getLength()); } - @Test + @TestTemplate public void testDocumentWithXmlInclude() throws Exception { Map properties = new HashMap<>(); properties.put(XmlProvider.XINCLUDE_AWARE_PROPERTY, true); @@ -101,22 +106,22 @@ public class XmlProviderTest extends ArtemisTestCase { Document document = documentBuilder.parse(new File(XmlProviderTest.class.getResource("/document-with-xinclude.xml").toURI())); Element documentElement = document.getDocumentElement(); - Assert.assertEquals("t:book", documentElement.getTagName()); + assertEquals("t:book", documentElement.getTagName()); if (XmlProvider.isXxeEnabled()) { - Assert.assertEquals(1, documentElement.getElementsByTagName("title").getLength()); + assertEquals(1, documentElement.getElementsByTagName("title").getLength()); } else { - Assert.assertEquals(0, documentElement.getElementsByTagName("title").getLength()); + assertEquals(0, documentElement.getElementsByTagName("title").getLength()); } } - @Test + @TestTemplate public void testSchema() throws Exception { StreamSource streamSource = new StreamSource(XmlProviderTest.class.getResourceAsStream("/schema.xsd")); XmlProvider.newSchema(streamSource, null); } - @Test + @TestTemplate public void testSchemaWithImport() { StreamSource streamSource = new StreamSource(XmlProviderTest.class.getResourceAsStream("/schema-with-import.xsd")); @@ -128,13 +133,13 @@ public class XmlProviderTest extends ArtemisTestCase { } if (XmlProvider.isXxeEnabled()) { - Assert.assertNull(newSchemaException); + assertNull(newSchemaException); } else { - Assert.assertNotNull(newSchemaException); + assertNotNull(newSchemaException); } } - @Test + @TestTemplate public void testValidator() throws Exception { Map properties = new HashMap<>(); properties.put(XmlProvider.NAMESPACE_AWARE_PROPERTY, true); @@ -146,7 +151,7 @@ public class XmlProviderTest extends ArtemisTestCase { validator.validate(new DOMSource(documentElement)); } - @Test + @TestTemplate public void testValidatorWithImport() throws Exception { Map properties = new HashMap<>(); properties.put(XmlProvider.NAMESPACE_AWARE_PROPERTY, true); @@ -163,9 +168,9 @@ public class XmlProviderTest extends ArtemisTestCase { } if (XmlProvider.isXxeEnabled()) { - Assert.assertNull(validateException); + assertNull(validateException); } else { - Assert.assertNotNull(validateException); + assertNotNull(validateException); } } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/OrderedExecutorSanityTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/OrderedExecutorSanityTest.java index dcf083e8cf..094ce8c8a6 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/OrderedExecutorSanityTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/OrderedExecutorSanityTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.utils.actors; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -24,12 +29,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; - +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import java.lang.invoke.MethodHandles; -import org.junit.Assert; -import org.junit.Test; public class OrderedExecutorSanityTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -54,8 +58,8 @@ public class OrderedExecutorSanityTest { }); expectedResults.add(value); } - Assert.assertTrue("The tasks must be executed in " + timeoutMillis + " ms", executed.await(timeoutMillis, TimeUnit.MILLISECONDS)); - Assert.assertArrayEquals("The processing of tasks must be ordered", expectedResults.toArray(), results.toArray()); + assertTrue(executed.await(timeoutMillis, TimeUnit.MILLISECONDS), "The tasks must be executed in " + timeoutMillis + " ms"); + assertArrayEquals(expectedResults.toArray(), results.toArray(), "The processing of tasks must be ordered"); } finally { executorService.shutdown(); } @@ -69,13 +73,13 @@ public class OrderedExecutorSanityTest { final OrderedExecutor executor = new OrderedExecutor(executorService); final CountDownLatch executed = new CountDownLatch(1); executor.execute(executed::countDown); - Assert.assertTrue("The task must be executed in " + timeoutMillis + " ms", executed.await(timeoutMillis, TimeUnit.MILLISECONDS)); + assertTrue(executed.await(timeoutMillis, TimeUnit.MILLISECONDS), "The task must be executed in " + timeoutMillis + " ms"); executor.shutdownNow(); - Assert.assertEquals("There are no remaining tasks to be executed", 0, executor.remaining()); + assertEquals(0, executor.remaining(), "There are no remaining tasks to be executed"); //from now on new tasks won't be executed executor.execute(() -> System.out.println("this will never happen")); //to avoid memory leaks the executor must take care of the new submitted tasks immediatly - Assert.assertEquals("Any new task submitted after death must be collected", 0, executor.remaining()); + assertEquals(0, executor.remaining(), "Any new task submitted after death must be collected"); } finally { executorService.shutdown(); } @@ -109,10 +113,10 @@ public class OrderedExecutorSanityTest { latch.await(); ran.await(1, TimeUnit.SECONDS); - Assert.assertEquals(100, numberOfTasks.get()); + assertEquals(100, numberOfTasks.get()); - Assert.assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status()); - Assert.assertEquals(0, executor.remaining()); + assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status()); + assertEquals(0, executor.remaining()); } finally { executorService.shutdown(); } @@ -144,13 +148,13 @@ public class OrderedExecutorSanityTest { latch.await(); try { - Assert.assertEquals(100, executor.shutdownNow()); + assertEquals(100, executor.shutdownNow()); } finally { secondlatch.await(); } - Assert.assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status()); - Assert.assertEquals(0, executor.remaining()); + assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status()); + assertEquals(0, executor.remaining()); } finally { executorService.shutdown(); } @@ -173,7 +177,7 @@ public class OrderedExecutorSanityTest { for (int l = 0; l < MAX_LOOP; l++) { executor.execute(executed::countDown); } - Assert.assertTrue(executed.await(1, TimeUnit.MINUTES)); + assertTrue(executed.await(1, TimeUnit.MINUTES)); long end = System.nanoTime(); long elapsed = (end - start); @@ -210,7 +214,7 @@ public class OrderedExecutorSanityTest { } }); - Assert.assertTrue(latchDone1.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone1.await(10, TimeUnit.SECONDS)); executor.execute(() -> { try { @@ -235,11 +239,11 @@ public class OrderedExecutorSanityTest { }); latchBlock1.countDown(); - Assert.assertTrue(latchDone3.await(10, TimeUnit.SECONDS)); - Assert.assertFalse(latchDone2.await(1, TimeUnit.MILLISECONDS)); + assertTrue(latchDone3.await(10, TimeUnit.SECONDS)); + assertFalse(latchDone2.await(1, TimeUnit.MILLISECONDS)); latchBlock3.countDown(); - Assert.assertTrue(latchDone2.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, errors.get()); + assertTrue(latchDone2.await(10, TimeUnit.SECONDS)); + assertEquals(0, errors.get()); } finally { executorService.shutdownNow(); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/ThresholdActorTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/ThresholdActorTest.java index 5d7fe27c13..4a5d8d3588 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/ThresholdActorTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/actors/ThresholdActorTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.utils.actors; +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.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -25,8 +29,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ThresholdActorTest { @@ -55,27 +58,27 @@ public class ThresholdActorTest { for (int i = 0; i < 10; i++) { actor.act(i); } - Assert.assertTrue(open.get()); - Assert.assertEquals(0, timesClose.get()); + assertTrue(open.get()); + assertEquals(0, timesClose.get()); actor.act(99); - Assert.assertEquals(1, timesClose.get()); - Assert.assertEquals(0, timesOpen.get()); + assertEquals(1, timesClose.get()); + assertEquals(0, timesOpen.get()); - Assert.assertFalse(open.get()); + assertFalse(open.get()); actor.act(1000); actor.flush(); // a flush here shuld not change anything, as it was already called once on the previous overflow - Assert.assertEquals(1, timesClose.get()); - Assert.assertEquals(0, timesOpen.get()); - Assert.assertFalse(open.get()); + assertEquals(1, timesClose.get()); + assertEquals(0, timesOpen.get()); + assertFalse(open.get()); semaphore.release(); Wait.assertTrue(open::get); - Assert.assertEquals(1, timesClose.get()); - Assert.assertEquals(1, timesOpen.get()); + assertEquals(1, timesClose.get()); + assertEquals(1, timesOpen.get()); Wait.assertEquals(1000, lastProcessed::get, 5000, 1); actor.flush(); @@ -174,10 +177,10 @@ public class ThresholdActorTest { latchDone.countDown(); }); - Assert.assertTrue(latchDone.await(10, TimeUnit.SECONDS)); + assertTrue(latchDone.await(10, TimeUnit.SECONDS)); Wait.assertEquals(LAST_ELEMENT, lastProcessed::get); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } finally { executorService.shutdown(); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/bean/MetaBeanTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/bean/MetaBeanTest.java index 7f57c5b6b4..50f0076d90 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/bean/MetaBeanTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/bean/MetaBeanTest.java @@ -17,14 +17,19 @@ package org.apache.activemq.artemis.utils.bean; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.invoke.MethodHandles; import java.util.Objects; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.json.JsonObject; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,27 +54,27 @@ public class MetaBeanTest { JsonObject jsonObject = MYClass.metaBean.toJSON(sourceObject, false); - Assert.assertFalse(jsonObject.containsKey("gated")); + assertFalse(jsonObject.containsKey("gated")); logger.debug("Result::" + jsonObject.toString()); MYClass result = new MYClass(); MYClass.metaBean.fromJSON(result, jsonObject.toString()); - Assert.assertEquals(sourceObject, result); + assertEquals(sourceObject, result); - Assert.assertEquals(null, result.getD()); - Assert.assertNotNull(result.getIdCacheSize()); - Assert.assertEquals(333, result.getIdCacheSize().intValue()); - Assert.assertEquals(33.33f, result.getFloatValue().floatValue(), 0); - Assert.assertEquals(11.11, result.getDoubleValue().doubleValue(), 0); - Assert.assertEquals(MyEnum.TWO, result.getMyEnum()); - Assert.assertTrue(result.getBoolValue()); + assertNull(result.getD()); + assertNotNull(result.getIdCacheSize()); + assertEquals(333, result.getIdCacheSize().intValue()); + assertEquals(33.33f, result.getFloatValue().floatValue(), 0); + assertEquals(11.11, result.getDoubleValue().doubleValue(), 0); + assertEquals(MyEnum.TWO, result.getMyEnum()); + assertTrue(result.getBoolValue()); sourceObject.setGated(SimpleString.toSimpleString("gated-now-has-value")); jsonObject = MYClass.metaBean.toJSON(sourceObject, false); - Assert.assertTrue(jsonObject.containsKey("gated")); - Assert.assertEquals("gated-now-has-value", jsonObject.getString("gated")); + assertTrue(jsonObject.containsKey("gated")); + assertEquals("gated-now-has-value", jsonObject.getString("gated")); } @Test @@ -79,10 +84,10 @@ public class MetaBeanTest { String json = MYClass.metaBean.toJSON(randomObject, false).toString(); MYClass target = new MYClass(); MYClass.metaBean.fromJSON(target, json); - Assert.assertEquals(randomObject, target); + assertEquals(randomObject, target); MYClass copy = new MYClass(); MYClass.metaBean.copy(randomObject, copy); - Assert.assertEquals(randomObject, copy); + assertEquals(randomObject, copy); } public enum MyEnum { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentAppendOnlyChunkedListTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentAppendOnlyChunkedListTest.java index dbb8b520aa..87a9e1daff 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentAppendOnlyChunkedListTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentAppendOnlyChunkedListTest.java @@ -16,10 +16,14 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ConcurrentAppendOnlyChunkedListTest { @@ -32,24 +36,28 @@ public class ConcurrentAppendOnlyChunkedListTest { chunkedList = new ConcurrentAppendOnlyChunkedList<>(CHUNK_SIZE); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailToCreateNotPowerOf2ChunkSizeCollection() { - new ConcurrentAppendOnlyChunkedList<>(3); + assertThrows(IllegalArgumentException.class, () -> { + new ConcurrentAppendOnlyChunkedList<>(3); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailToCreateNegativeChunkSizeCollection() { - new ConcurrentAppendOnlyChunkedList<>(-1); + assertThrows(IllegalArgumentException.class, () -> { + new ConcurrentAppendOnlyChunkedList<>(-1); + }); } @Test public void shouldNumberOfElementsBeTheSameOfTheAddedElements() { final int messages = ELEMENTS; for (int i = 0; i < messages; i++) { - Assert.assertEquals(i, chunkedList.size()); + assertEquals(i, chunkedList.size()); chunkedList.add(i); } - Assert.assertEquals(messages, chunkedList.size()); + assertEquals(messages, chunkedList.size()); } @Test @@ -61,19 +69,19 @@ public class ConcurrentAppendOnlyChunkedListTest { elements[i] = element; } chunkedList.addAll(elements); - Assert.assertEquals(messages, chunkedList.size()); + assertEquals(messages, chunkedList.size()); } @Test public void shouldGetReturnNullIfEmpty() { - Assert.assertNull(chunkedList.get(0)); + assertNull(chunkedList.get(0)); } @Test public void shouldNegativeIndexedGetReturnNull() { - Assert.assertNull(chunkedList.get(-1)); + assertNull(chunkedList.get(-1)); chunkedList.add(0); - Assert.assertNull(chunkedList.get(-1)); + assertNull(chunkedList.get(-1)); } @Test @@ -82,7 +90,7 @@ public class ConcurrentAppendOnlyChunkedListTest { for (int i = 0; i < messages; i++) { final Integer element = i; chunkedList.add(element); - Assert.assertNull(chunkedList.get(i + 1)); + assertNull(chunkedList.get(i + 1)); } } @@ -99,12 +107,12 @@ public class ConcurrentAppendOnlyChunkedListTest { for (int i = 0; i < messages; i++) { cachedElements[i] = chunkedList.get(i); } - Assert.assertArrayEquals(elements, cachedElements); + assertArrayEquals(elements, cachedElements); Arrays.fill(cachedElements, null); for (int i = messages - 1; i >= 0; i--) { cachedElements[i] = chunkedList.get(i); } - Assert.assertArrayEquals(elements, cachedElements); + assertArrayEquals(elements, cachedElements); } @Test @@ -120,7 +128,7 @@ public class ConcurrentAppendOnlyChunkedListTest { for (int i = 0; i < messages; i++) { cachedElements[i] = chunkedList.get(i); } - Assert.assertArrayEquals(elements, cachedElements); + assertArrayEquals(elements, cachedElements); } @Test @@ -133,7 +141,7 @@ public class ConcurrentAppendOnlyChunkedListTest { chunkedList.add(element); } final Integer[] cachedElements = chunkedList.toArray(Integer[]::new); - Assert.assertArrayEquals(elements, cachedElements); + assertArrayEquals(elements, cachedElements); } @Test @@ -147,31 +155,37 @@ public class ConcurrentAppendOnlyChunkedListTest { } final int offset = 10; final Integer[] cachedElements = chunkedList.toArray(size -> new Integer[offset + size], offset); - Assert.assertArrayEquals(elements, Arrays.copyOfRange(cachedElements, offset, cachedElements.length)); - Assert.assertArrayEquals(new Integer[offset], Arrays.copyOfRange(cachedElements, 0, offset)); + assertArrayEquals(elements, Arrays.copyOfRange(cachedElements, offset, cachedElements.length)); + assertArrayEquals(new Integer[offset], Arrays.copyOfRange(cachedElements, 0, offset)); } - @Test(expected = ArrayIndexOutOfBoundsException.class) + @Test public void shouldFailToArrayWithInsufficientArrayCapacity() { - final int messages = ELEMENTS; - final Integer[] elements = new Integer[messages]; - for (int i = 0; i < messages; i++) { - final Integer element = i; - elements[i] = element; - chunkedList.add(element); - } - final int offset = 10; - chunkedList.toArray(size -> new Integer[offset + size - 1], offset); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + final int messages = ELEMENTS; + final Integer[] elements = new Integer[messages]; + for (int i = 0;i < messages;i++) { + final Integer element = i; + elements[i] = element; + chunkedList.add(element); + } + final int offset = 10; + chunkedList.toArray(size -> new Integer[offset + size - 1], offset); + }); } - @Test(expected = ArrayIndexOutOfBoundsException.class) + @Test public void shouldFailToArrayWithNegativeStartIndex() { - chunkedList.toArray(Integer[]::new, -1); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + chunkedList.toArray(Integer[]::new, -1); + }); } - @Test(expected = NullPointerException.class) + @Test public void shouldFailToArrayWithNullArray() { - chunkedList.toArray(size -> null); + assertThrows(NullPointerException.class, () -> { + chunkedList.toArray(size -> null); + }); } @Test @@ -184,13 +198,13 @@ public class ConcurrentAppendOnlyChunkedListTest { } chunkedList.addAll(elements); final Integer[] cachedElements = chunkedList.toArray(Integer[]::new); - Assert.assertArrayEquals(elements, cachedElements); + assertArrayEquals(elements, cachedElements); } @Test public void shouldToArrayReturnEmptyArrayIfEmpty() { final Integer[] array = chunkedList.toArray(Integer[]::new); - Assert.assertArrayEquals(new Integer[0], array); + assertArrayEquals(new Integer[0], array); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java index 1b5f1dd4cb..727bc2c1f9 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -30,12 +35,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.LongFunction; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.Test; public class ConcurrentLongHashMapTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java index b44f1d91e0..e044f3c42b 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.utils.collections; +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.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -26,11 +30,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class ConcurrentLongHashSetTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/LongHashSetTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/LongHashSetTest.java index 0e40e8cd15..207a255062 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/LongHashSetTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/LongHashSetTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -24,8 +31,7 @@ import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * These tests are based on Agrona IntHashSetTest @@ -40,64 +46,64 @@ public class LongHashSetTest { @Test public void initiallyContainsNoElements() { for (long i = 0; i < 10_000; i++) { - Assert.assertFalse(testSet.contains(i)); + assertFalse(testSet.contains(i)); } } @Test public void initiallyContainsNoBoxedElements() { for (long i = 0; i < 10_000; i++) { - Assert.assertFalse(testSet.contains(Long.valueOf(i))); + assertFalse(testSet.contains(Long.valueOf(i))); } } @Test public void containsAddedElement() { - Assert.assertTrue(testSet.add(1L)); + assertTrue(testSet.add(1L)); - Assert.assertTrue(testSet.contains(1L)); + assertTrue(testSet.contains(1L)); } @Test public void addingAnElementTwiceDoesNothing() { - Assert.assertTrue(testSet.add(1L)); + assertTrue(testSet.add(1L)); - Assert.assertFalse(testSet.add(1L)); + assertFalse(testSet.add(1L)); } @Test public void containsAddedBoxedElements() { - Assert.assertTrue(testSet.add(1L)); - Assert.assertTrue(testSet.add(Long.valueOf(2L))); + assertTrue(testSet.add(1L)); + assertTrue(testSet.add(Long.valueOf(2L))); - Assert.assertTrue(testSet.contains(Long.valueOf(1L))); - Assert.assertTrue(testSet.contains(2L)); + assertTrue(testSet.contains(Long.valueOf(1L))); + assertTrue(testSet.contains(2L)); } @Test public void removingAnElementFromAnEmptyListDoesNothing() { - Assert.assertFalse(testSet.remove(0L)); + assertFalse(testSet.remove(0L)); } @Test public void removingAPresentElementRemovesIt() { - Assert.assertTrue(testSet.add(1L)); + assertTrue(testSet.add(1L)); - Assert.assertTrue(testSet.remove(1L)); + assertTrue(testSet.remove(1L)); - Assert.assertFalse(testSet.contains(1L)); + assertFalse(testSet.contains(1L)); } @Test public void sizeIsInitiallyZero() { - Assert.assertEquals(0, testSet.size()); + assertEquals(0, testSet.size()); } @Test public void sizeIncrementsWithNumberOfAddedElements() { addTwoElements(testSet); - Assert.assertEquals(2, testSet.size()); + assertEquals(2, testSet.size()); } @Test @@ -105,7 +111,7 @@ public class LongHashSetTest { testSet.add(1L); testSet.add(1L); - Assert.assertEquals(1, testSet.size()); + assertEquals(1, testSet.size()); } @Test @@ -136,33 +142,39 @@ public class LongHashSetTest { assertIteratorHasElementsWithoutHasNext(); } - @Test(expected = NoSuchElementException.class) + @Test public void iteratorsThrowNoSuchElementException() { - addTwoElements(testSet); + assertThrows(NoSuchElementException.class, () -> { + addTwoElements(testSet); - exhaustIterator(); + exhaustIterator(); + }); } - @Test(expected = NoSuchElementException.class) + @Test public void iteratorsThrowNoSuchElementExceptionFromTheBeginningEveryTime() { - addTwoElements(testSet); + assertThrows(NoSuchElementException.class, () -> { + addTwoElements(testSet); + + try { + exhaustIterator(); + } catch (final NoSuchElementException ignore) { + } - try { exhaustIterator(); - } catch (final NoSuchElementException ignore) { - } - - exhaustIterator(); + }); } @Test public void iteratorHasNoElements() { - Assert.assertFalse(testSet.iterator().hasNext()); + assertFalse(testSet.iterator().hasNext()); } - @Test(expected = NoSuchElementException.class) + @Test public void iteratorThrowExceptionForEmptySet() { - testSet.iterator().next(); + assertThrows(NoSuchElementException.class, () -> { + testSet.iterator().next(); + }); } @Test @@ -171,15 +183,15 @@ public class LongHashSetTest { testSet.clear(); - Assert.assertEquals(0, testSet.size()); - Assert.assertFalse(testSet.contains(1L)); - Assert.assertFalse(testSet.contains(1001L)); + assertEquals(0, testSet.size()); + assertFalse(testSet.contains(1L)); + assertFalse(testSet.contains(1001L)); } @Test public void twoEmptySetsAreEqual() { final LongHashSet other = new LongHashSet(100); - Assert.assertEquals(testSet, other); + assertEquals(testSet, other); } @Test @@ -189,7 +201,7 @@ public class LongHashSetTest { addTwoElements(testSet); addTwoElements(other); - Assert.assertEquals(testSet, other); + assertEquals(testSet, other); } @Test @@ -200,7 +212,7 @@ public class LongHashSetTest { other.add(1001L); - Assert.assertNotEquals(testSet, other); + assertNotEquals(testSet, other); } @Test @@ -212,12 +224,12 @@ public class LongHashSetTest { other.add(2L); other.add(1001L); - Assert.assertNotEquals(testSet, other); + assertNotEquals(testSet, other); } @Test public void twoEmptySetsHaveTheSameHashcode() { - Assert.assertEquals(testSet.hashCode(), new LongHashSet(100).hashCode()); + assertEquals(testSet.hashCode(), new LongHashSet(100).hashCode()); } @Test @@ -228,7 +240,7 @@ public class LongHashSetTest { addTwoElements(other); - Assert.assertEquals(testSet.hashCode(), other.hashCode()); + assertEquals(testSet.hashCode(), other.hashCode()); } @Test @@ -237,19 +249,23 @@ public class LongHashSetTest { testSet.remove(1001L); - Assert.assertEquals(1, testSet.size()); + assertEquals(1, testSet.size()); } @SuppressWarnings("CollectionToArraySafeParameter") - @Test(expected = ArrayStoreException.class) + @Test public void toArrayThrowsArrayStoreExceptionForWrongType() { - testSet.toArray(new String[1]); + assertThrows(ArrayStoreException.class, () -> { + testSet.toArray(new String[1]); + }); } - @Test(expected = NullPointerException.class) + @Test public void toArrayThrowsNullPointerExceptionForNullArgument() { - final Long[] into = null; - testSet.toArray(into); + assertThrows(NullPointerException.class, () -> { + final Long[] into = null; + testSet.toArray(into); + }); } @Test @@ -274,7 +290,7 @@ public class LongHashSetTest { public void toArraySupportsEmptyCollection() { final Long[] result = testSet.toArray(new Long[testSet.size()]); - Assert.assertArrayEquals(result, new Long[]{}); + assertArrayEquals(result, new Long[]{}); } // Test case from usage bug. @@ -288,21 +304,21 @@ public class LongHashSetTest { requiredFields.add(49L); requiredFields.add(56L); - Assert.assertTrue("Failed to remove 8", requiredFields.remove(8L)); - Assert.assertTrue("Failed to remove 9", requiredFields.remove(9L)); - Assert.assertTrue("requiredFields does not contain " + 35, requiredFields.contains(35L)); - Assert.assertTrue("requiredFields does not contain " + 49, requiredFields.contains(49L)); - Assert.assertTrue("requiredFields does not contain " + 56, requiredFields.contains(56L)); + assertTrue(requiredFields.remove(8L), "Failed to remove 8"); + assertTrue(requiredFields.remove(9L), "Failed to remove 9"); + assertTrue(requiredFields.contains(35L), "requiredFields does not contain " + 35); + assertTrue(requiredFields.contains(49L), "requiredFields does not contain " + 49); + assertTrue(requiredFields.contains(56L), "requiredFields does not contain " + 56); } @Test public void shouldResizeWhenItHitsCapacity() { for (long i = 0; i < 2 * INITIAL_CAPACITY; i++) { - Assert.assertTrue(testSet.add(i)); + assertTrue(testSet.add(i)); } for (long i = 0; i < 2 * INITIAL_CAPACITY; i++) { - Assert.assertTrue(testSet.contains(i)); + assertTrue(testSet.contains(i)); } } @@ -310,8 +326,8 @@ public class LongHashSetTest { public void containsEmptySet() { final LongHashSet other = new LongHashSet(100); - Assert.assertTrue(testSet.containsAll(other)); - Assert.assertTrue(testSet.containsAll((Collection) other)); + assertTrue(testSet.containsAll(other)); + assertTrue(testSet.containsAll((Collection) other)); } @Test @@ -322,8 +338,8 @@ public class LongHashSetTest { subset.add(1L); - Assert.assertTrue(testSet.containsAll(subset)); - Assert.assertTrue(testSet.containsAll((Collection) subset)); + assertTrue(testSet.containsAll(subset)); + assertTrue(testSet.containsAll((Collection) subset)); } @Test @@ -335,8 +351,8 @@ public class LongHashSetTest { other.add(1L); other.add(1002L); - Assert.assertFalse(testSet.containsAll(other)); - Assert.assertFalse(testSet.containsAll((Collection) other)); + assertFalse(testSet.containsAll(other)); + assertFalse(testSet.containsAll((Collection) other)); } @Test @@ -348,16 +364,16 @@ public class LongHashSetTest { addTwoElements(superset); superset.add(15L); - Assert.assertFalse(testSet.containsAll(superset)); - Assert.assertFalse(testSet.containsAll((Collection) superset)); + assertFalse(testSet.containsAll(superset)); + assertFalse(testSet.containsAll((Collection) superset)); } @Test public void addingEmptySetDoesNothing() { addTwoElements(testSet); - Assert.assertFalse(testSet.addAll(new LongHashSet(100))); - Assert.assertFalse(testSet.addAll(new HashSet<>())); + assertFalse(testSet.addAll(new LongHashSet(100))); + assertFalse(testSet.addAll(new HashSet<>())); assertContainsElements(testSet); } @@ -371,8 +387,8 @@ public class LongHashSetTest { final HashSet subSetCollection = new HashSet<>(subset); - Assert.assertFalse(testSet.addAll(subset)); - Assert.assertFalse(testSet.addAll(subSetCollection)); + assertFalse(testSet.addAll(subset)); + assertFalse(testSet.addAll(subSetCollection)); assertContainsElements(testSet); } @@ -386,8 +402,8 @@ public class LongHashSetTest { final HashSet equalCollection = new HashSet<>(equal); - Assert.assertFalse(testSet.addAll(equal)); - Assert.assertFalse(testSet.addAll(equalCollection)); + assertFalse(testSet.addAll(equal)); + assertFalse(testSet.addAll(equalCollection)); assertContainsElements(testSet); } @@ -400,10 +416,10 @@ public class LongHashSetTest { disjoint.add(2L); disjoint.add(1002L); - Assert.assertTrue(testSet.addAll(disjoint)); - Assert.assertTrue(testSet.contains(1L)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertTrue(testSet.containsAll(disjoint)); + assertTrue(testSet.addAll(disjoint)); + assertTrue(testSet.contains(1L)); + assertTrue(testSet.contains(1001L)); + assertTrue(testSet.containsAll(disjoint)); } @Test @@ -415,10 +431,10 @@ public class LongHashSetTest { disjoint.add(2L); disjoint.add(1002L); - Assert.assertTrue(testSet.addAll(disjoint)); - Assert.assertTrue(testSet.contains(1L)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertTrue(testSet.containsAll(disjoint)); + assertTrue(testSet.addAll(disjoint)); + assertTrue(testSet.contains(1L)); + assertTrue(testSet.contains(1001L)); + assertTrue(testSet.containsAll(disjoint)); } @Test @@ -430,10 +446,10 @@ public class LongHashSetTest { intersecting.add(1L); intersecting.add(1002L); - Assert.assertTrue(testSet.addAll(intersecting)); - Assert.assertTrue(testSet.contains(1L)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertTrue(testSet.containsAll(intersecting)); + assertTrue(testSet.addAll(intersecting)); + assertTrue(testSet.contains(1L)); + assertTrue(testSet.contains(1001L)); + assertTrue(testSet.containsAll(intersecting)); } @Test @@ -445,18 +461,18 @@ public class LongHashSetTest { intersecting.add(1L); intersecting.add(1002L); - Assert.assertTrue(testSet.addAll(intersecting)); - Assert.assertTrue(testSet.contains(1L)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertTrue(testSet.containsAll(intersecting)); + assertTrue(testSet.addAll(intersecting)); + assertTrue(testSet.contains(1L)); + assertTrue(testSet.contains(1001L)); + assertTrue(testSet.containsAll(intersecting)); } @Test public void removingEmptySetDoesNothing() { addTwoElements(testSet); - Assert.assertFalse(testSet.removeAll(new LongHashSet(100))); - Assert.assertFalse(testSet.removeAll(new HashSet())); + assertFalse(testSet.removeAll(new LongHashSet(100))); + assertFalse(testSet.removeAll(new HashSet())); assertContainsElements(testSet); } @@ -469,8 +485,8 @@ public class LongHashSetTest { disjoint.add(2L); disjoint.add(1002L); - Assert.assertFalse(testSet.removeAll(disjoint)); - Assert.assertFalse(testSet.removeAll(new HashSet())); + assertFalse(testSet.removeAll(disjoint)); + assertFalse(testSet.removeAll(new HashSet())); assertContainsElements(testSet); } @@ -483,9 +499,9 @@ public class LongHashSetTest { intersecting.add(1L); intersecting.add(1002L); - Assert.assertTrue(testSet.removeAll(intersecting)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertFalse(testSet.containsAll(intersecting)); + assertTrue(testSet.removeAll(intersecting)); + assertTrue(testSet.contains(1001L)); + assertFalse(testSet.containsAll(intersecting)); } @Test @@ -497,9 +513,9 @@ public class LongHashSetTest { intersecting.add(1L); intersecting.add(1002L); - Assert.assertTrue(testSet.removeAll(intersecting)); - Assert.assertTrue(testSet.contains(1001L)); - Assert.assertFalse(testSet.containsAll(intersecting)); + assertTrue(testSet.removeAll(intersecting)); + assertTrue(testSet.contains(1001L)); + assertFalse(testSet.containsAll(intersecting)); } @Test @@ -510,8 +526,8 @@ public class LongHashSetTest { addTwoElements(equal); - Assert.assertTrue(testSet.removeAll(equal)); - Assert.assertTrue(testSet.isEmpty()); + assertTrue(testSet.removeAll(equal)); + assertTrue(testSet.isEmpty()); } @Test @@ -522,8 +538,8 @@ public class LongHashSetTest { addTwoElements(equal); - Assert.assertTrue(testSet.removeAll(equal)); - Assert.assertTrue(testSet.isEmpty()); + assertTrue(testSet.removeAll(equal)); + assertTrue(testSet.isEmpty()); } @Test @@ -537,33 +553,33 @@ public class LongHashSetTest { } } - Assert.assertTrue("testSet does not contain 1001", testSet.contains(1001L)); - Assert.assertEquals(1, testSet.size()); + assertTrue(testSet.contains(1001L), "testSet does not contain 1001"); + assertEquals(1, testSet.size()); } @Test public void shouldNotContainMissingValueInitially() { - Assert.assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); } @Test public void shouldAllowMissingValue() { - Assert.assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); + assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); - Assert.assertTrue(testSet.contains(LongHashSet.MISSING_VALUE)); + assertTrue(testSet.contains(LongHashSet.MISSING_VALUE)); - Assert.assertFalse(testSet.add(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.add(LongHashSet.MISSING_VALUE)); } @Test public void shouldAllowRemovalOfMissingValue() { - Assert.assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); + assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); - Assert.assertTrue(testSet.remove(LongHashSet.MISSING_VALUE)); + assertTrue(testSet.remove(LongHashSet.MISSING_VALUE)); - Assert.assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); - Assert.assertFalse(testSet.remove(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.remove(LongHashSet.MISSING_VALUE)); } @Test @@ -571,7 +587,7 @@ public class LongHashSetTest { testSet.add(1L); testSet.add(LongHashSet.MISSING_VALUE); - Assert.assertEquals(2, testSet.size()); + assertEquals(2, testSet.size()); } @Test @@ -582,9 +598,9 @@ public class LongHashSetTest { final Long[] result = testSet.toArray(new Long[testSet.size()]); - Assert.assertTrue(Arrays.asList(result).contains(1L)); - Assert.assertTrue(Arrays.asList(result).contains(1001L)); - Assert.assertTrue(Arrays.asList(result).contains(LongHashSet.MISSING_VALUE)); + assertTrue(Arrays.asList(result).contains(1L)); + assertTrue(Arrays.asList(result).contains(1001L)); + assertTrue(Arrays.asList(result).contains(LongHashSet.MISSING_VALUE)); } @Test @@ -595,9 +611,9 @@ public class LongHashSetTest { final Object[] result = testSet.toArray(); - Assert.assertTrue(Arrays.asList(result).contains(1L)); - Assert.assertTrue(Arrays.asList(result).contains(1001L)); - Assert.assertTrue(Arrays.asList(result).contains(LongHashSet.MISSING_VALUE)); + assertTrue(Arrays.asList(result).contains(1L)); + assertTrue(Arrays.asList(result).contains(1001L)); + assertTrue(Arrays.asList(result).contains(LongHashSet.MISSING_VALUE)); } @Test @@ -608,14 +624,14 @@ public class LongHashSetTest { final LongHashSet other = new LongHashSet(100); addTwoElements(other); - Assert.assertNotEquals(testSet, other); + assertNotEquals(testSet, other); other.add(LongHashSet.MISSING_VALUE); - Assert.assertEquals(testSet, other); + assertEquals(testSet, other); testSet.remove(LongHashSet.MISSING_VALUE); - Assert.assertNotEquals(testSet, other); + assertNotEquals(testSet, other); } @Test @@ -624,14 +640,14 @@ public class LongHashSetTest { testSet.add(i); } - Assert.assertEquals(10_000, testSet.size()); + assertEquals(10_000, testSet.size()); int distinctElements = 0; for (final long ignore : testSet) { distinctElements++; } - Assert.assertEquals(10_000, distinctElements); + assertEquals(10_000, distinctElements); } @Test @@ -642,14 +658,14 @@ public class LongHashSetTest { final LongHashSet other = new LongHashSet(100); addTwoElements(other); - Assert.assertNotEquals(testSet.hashCode(), other.hashCode()); + assertNotEquals(testSet.hashCode(), other.hashCode()); other.add(LongHashSet.MISSING_VALUE); - Assert.assertEquals(testSet.hashCode(), other.hashCode()); + assertEquals(testSet.hashCode(), other.hashCode()); testSet.remove(LongHashSet.MISSING_VALUE); - Assert.assertNotEquals(testSet.hashCode(), other.hashCode()); + assertNotEquals(testSet.hashCode(), other.hashCode()); } @Test @@ -665,7 +681,7 @@ public class LongHashSetTest { } } - Assert.assertEquals(1, missingValueCount); + assertEquals(1, missingValueCount); } @Test @@ -680,7 +696,7 @@ public class LongHashSetTest { } } - Assert.assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); } @Test @@ -692,16 +708,16 @@ public class LongHashSetTest { } final String mapAsAString = "{1, 19, 11, 7, 3, 12, -2}"; - Assert.assertEquals(testSet.toString(), mapAsAString); + assertEquals(testSet.toString(), mapAsAString); } @Test public void shouldRemoveMissingValueWhenCleared() { - Assert.assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); + assertTrue(testSet.add(LongHashSet.MISSING_VALUE)); testSet.clear(); - Assert.assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); + assertFalse(testSet.contains(LongHashSet.MISSING_VALUE)); } @Test @@ -720,9 +736,9 @@ public class LongHashSetTest { testSet.add(LongHashSet.MISSING_VALUE); } - Assert.assertEquals("Fail with seed:" + seed, testSet, compatibleSet); - Assert.assertEquals("Fail with seed:" + seed, compatibleSet, testSet); - Assert.assertEquals("Fail with seed:" + seed, compatibleSet.hashCode(), testSet.hashCode()); + assertEquals(testSet, compatibleSet, "Fail with seed:" + seed); + assertEquals(compatibleSet, testSet, "Fail with seed:" + seed); + assertEquals(compatibleSet.hashCode(), testSet.hashCode(), "Fail with seed:" + seed); } private static void addTwoElements(final LongHashSet obj) { @@ -740,11 +756,11 @@ public class LongHashSetTest { final Set values = new HashSet<>(); - Assert.assertTrue(iter.hasNext()); + assertTrue(iter.hasNext()); values.add(iter.next()); - Assert.assertTrue(iter.hasNext()); + assertTrue(iter.hasNext()); values.add(iter.next()); - Assert.assertFalse(iter.hasNext()); + assertFalse(iter.hasNext()); assertContainsElements(values); } @@ -761,13 +777,13 @@ public class LongHashSetTest { } private static void assertArrayContainingElements(final Long[] result) { - Assert.assertTrue(Arrays.asList(result).contains(1L)); - Assert.assertTrue(Arrays.asList(result).contains(1001L)); + assertTrue(Arrays.asList(result).contains(1L)); + assertTrue(Arrays.asList(result).contains(1001L)); } private static void assertContainsElements(final Set other) { - Assert.assertTrue(other.contains(1L)); - Assert.assertTrue(other.contains(1001L)); + assertTrue(other.contains(1L)); + assertTrue(other.contains(1001L)); } private void exhaustIterator() { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiIteratorTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiIteratorTest.java index 5e9f9219b4..a02c05f005 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiIteratorTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiIteratorTest.java @@ -16,14 +16,14 @@ */ package org.apache.activemq.artemis.utils.collections; -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.assertTrue; import java.util.ArrayList; import java.util.Iterator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class MultiIteratorTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiResettableIteratorTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiResettableIteratorTest.java index 84cc79a85c..179d356d8a 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiResettableIteratorTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/MultiResettableIteratorTest.java @@ -16,14 +16,14 @@ */ package org.apache.activemq.artemis.utils.collections; -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.assertTrue; import java.util.ArrayList; -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 org.junit.jupiter.api.Test; public class MultiResettableIteratorTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/NoOpMapTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/NoOpMapTest.java index 74c56f5500..57ae8065e2 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/NoOpMapTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/NoOpMapTest.java @@ -16,14 +16,16 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Collection; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class NoOpMapTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/PriorityCollectionTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/PriorityCollectionTest.java index e177a35c0d..18a2ffbb94 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/PriorityCollectionTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/PriorityCollectionTest.java @@ -16,8 +16,12 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.core.PriorityAware; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Iterator; @@ -29,10 +33,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class PriorityCollectionTest { @Test diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/SparseArrayLinkedListTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/SparseArrayLinkedListTest.java index 85bd53294e..559c382061 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/SparseArrayLinkedListTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/SparseArrayLinkedListTest.java @@ -16,11 +16,13 @@ */ package org.apache.activemq.artemis.utils.collections; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SparseArrayLinkedListTest { @@ -33,35 +35,41 @@ public class SparseArrayLinkedListTest { list = new SparseArrayLinkedList<>(SPARSE_ARRAY_CAPACITY); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailToCreateZeroArrayCapacityCollection() { - new SparseArrayLinkedList<>(0); + assertThrows(IllegalArgumentException.class, () -> { + new SparseArrayLinkedList<>(0); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldFailToCreateNegativeArrayCapacityCollection() { - new SparseArrayLinkedList<>(-1); + assertThrows(IllegalArgumentException.class, () -> { + new SparseArrayLinkedList<>(-1); + }); } - @Test(expected = NullPointerException.class) + @Test public void shouldFailToAddNull() { - list.add(null); + assertThrows(NullPointerException.class, () -> { + list.add(null); + }); } @Test public void shouldNumberOfElementsBeTheSameOfTheAddedElements() { final int elements = ELEMENTS; for (int i = 0; i < elements; i++) { - Assert.assertEquals(i, list.size()); + assertEquals(i, list.size()); list.add(i); } - Assert.assertEquals(elements, list.size()); + assertEquals(elements, list.size()); } @Test public void shouldClearConsumeElementsInOrder() { final int elements = ELEMENTS; - Assert.assertEquals(0, list.clear(null)); + assertEquals(0, list.clear(null)); final ArrayList expected = new ArrayList<>(elements); for (int i = 0; i < elements; i++) { final Integer added = i; @@ -69,10 +77,10 @@ public class SparseArrayLinkedListTest { expected.add(added); } final List removed = new ArrayList<>(elements); - Assert.assertEquals(elements, list.clear(removed::add)); - Assert.assertEquals(1, list.sparseArraysCount()); - Assert.assertEquals(0, list.size()); - Assert.assertEquals(expected, removed); + assertEquals(elements, list.clear(removed::add)); + assertEquals(1, list.sparseArraysCount()); + assertEquals(0, list.size()); + assertEquals(expected, removed); } @Test @@ -81,15 +89,15 @@ public class SparseArrayLinkedListTest { for (int i = 0; i < elements; i++) { list.add(i); } - Assert.assertEquals(1, list.remove(e -> e.intValue() == 0)); - Assert.assertEquals(elements - 1, list.size()); - Assert.assertEquals(0, list.remove(e -> e.intValue() == 0)); - Assert.assertEquals(elements - 1, list.size()); - Assert.assertEquals(elements - 1, list.remove(e -> true)); - Assert.assertEquals(0, list.size()); - Assert.assertEquals(1, list.sparseArraysCount()); - Assert.assertEquals(0, list.remove(e -> true)); - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.remove(e -> e.intValue() == 0)); + assertEquals(elements - 1, list.size()); + assertEquals(0, list.remove(e -> e.intValue() == 0)); + assertEquals(elements - 1, list.size()); + assertEquals(elements - 1, list.remove(e -> true)); + assertEquals(0, list.size()); + assertEquals(1, list.sparseArraysCount()); + assertEquals(0, list.remove(e -> true)); + assertEquals(1, list.sparseArraysCount()); } @Test @@ -101,21 +109,21 @@ public class SparseArrayLinkedListTest { // remove elements in the middle final int startInclusiveMiddle = list.sparseArrayCapacity(); final int endNotInclusiveMiddle = startInclusiveMiddle + list.sparseArrayCapacity(); - Assert.assertEquals(list.sparseArrayCapacity(), + assertEquals(list.sparseArrayCapacity(), list.remove(e -> e.intValue() >= startInclusiveMiddle && e.intValue() < endNotInclusiveMiddle)); - Assert.assertEquals(2, list.sparseArraysCount()); + assertEquals(2, list.sparseArraysCount()); // remove elements at the beginning final int startInclusiveFirst = 0; final int endNotInclusiveFirst = startInclusiveMiddle; - Assert.assertEquals(list.sparseArrayCapacity(), + assertEquals(list.sparseArrayCapacity(), list.remove(e -> e.intValue() >= startInclusiveFirst && e.intValue() < endNotInclusiveFirst)); - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.sparseArraysCount()); // remove all elements at the end final int startInclusiveLast = endNotInclusiveMiddle; final int endNotInclusiveLast = elements; - Assert.assertEquals(list.sparseArrayCapacity(), + assertEquals(list.sparseArrayCapacity(), list.remove(e -> e.intValue() >= startInclusiveLast && e.intValue() < endNotInclusiveLast)); - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.sparseArraysCount()); } @Test @@ -124,14 +132,14 @@ public class SparseArrayLinkedListTest { for (int i = 0; i < elements; i++) { list.add(i); } - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.sparseArraysCount()); // removing last element - Assert.assertEquals(1, list.remove(e -> e.intValue() == elements - 1)); + assertEquals(1, list.remove(e -> e.intValue() == elements - 1)); list.add(elements - 1); - Assert.assertEquals(1, list.sparseArraysCount()); - Assert.assertEquals(1, list.remove(e -> e.intValue() == 0)); + assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.remove(e -> e.intValue() == 0)); list.add(elements); - Assert.assertEquals(2, list.sparseArraysCount()); + assertEquals(2, list.sparseArraysCount()); } @Test @@ -140,14 +148,14 @@ public class SparseArrayLinkedListTest { for (int i = 0; i < elements; i++) { list.add(i); } - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.sparseArraysCount()); // removing all elements - Assert.assertEquals(elements, list.remove(e -> true)); - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(elements, list.remove(e -> true)); + assertEquals(1, list.sparseArraysCount()); for (int i = 0; i < elements; i++) { list.add(i); } - Assert.assertEquals(1, list.sparseArraysCount()); + assertEquals(1, list.sparseArraysCount()); } @Test @@ -158,12 +166,12 @@ public class SparseArrayLinkedListTest { for (int i = 1; i < elements; i++) { list.add(i); } - Assert.assertEquals(elements - 1, list.remove(e -> !zero.equals(e))); + assertEquals(elements - 1, list.remove(e -> !zero.equals(e))); final ArrayList remaining = new ArrayList<>(); - Assert.assertEquals(1, list.clear(remaining::add)); - Assert.assertEquals(0, list.size()); - Assert.assertEquals(1, remaining.size()); - Assert.assertEquals(zero, remaining.get(0)); + assertEquals(1, list.clear(remaining::add)); + assertEquals(0, list.size()); + assertEquals(1, remaining.size()); + assertEquals(zero, remaining.get(0)); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/UpdatableIteratorTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/UpdatableIteratorTest.java index 1f0fd32d73..80192c5332 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/UpdatableIteratorTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/UpdatableIteratorTest.java @@ -16,13 +16,13 @@ */ package org.apache.activemq.artemis.utils.collections; -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.assertTrue; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class UpdatableIteratorTest { diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalAnalyzerTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalAnalyzerTest.java index 659f4c5b74..2d464b72a8 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalAnalyzerTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalAnalyzerTest.java @@ -16,26 +16,25 @@ */ package org.apache.activemq.artemis.utils.critical; +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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; import org.apache.activemq.artemis.utils.ArtemisCloseable; import org.apache.activemq.artemis.utils.ReusableLatch; -import org.apache.activemq.artemis.utils.ThreadLeakCheckRule; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -public class CriticalAnalyzerTest { - - @Rule - public ThreadLeakCheckRule rule = new ThreadLeakCheckRule(); +public class CriticalAnalyzerTest extends ArtemisTestCase { private CriticalAnalyzer analyzer; - @After + @AfterEach public void tearDown() throws Exception { if (analyzer != null) { analyzer.stop(); @@ -51,17 +50,17 @@ public class CriticalAnalyzerTest { CriticalCloseable closeable1 = component.measureCritical(0); - Assert.assertFalse(CriticalMeasure.isDummy(closeable1)); + assertFalse(CriticalMeasure.isDummy(closeable1)); ArtemisCloseable closeable2 = component.measureCritical(0); - Assert.assertTrue(CriticalMeasure.isDummy(closeable2)); + assertTrue(CriticalMeasure.isDummy(closeable2)); closeable1.close(); closeable2 = component.measureCritical(0); - Assert.assertFalse(CriticalMeasure.isDummy(closeable2)); + assertFalse(CriticalMeasure.isDummy(closeable2)); } @Test @@ -72,7 +71,7 @@ public class CriticalAnalyzerTest { analyzer.add(component); CriticalCloseable closeable = component.measureCritical(0); - Assert.assertFalse(CriticalMeasure.isDummy(closeable)); + assertFalse(CriticalMeasure.isDummy(closeable)); CriticalCloseable dummy = component.measureCritical(0); @@ -83,17 +82,17 @@ public class CriticalAnalyzerTest { exception = true; } - Assert.assertTrue(exception); + assertTrue(exception); AtomicInteger value = new AtomicInteger(0); closeable.beforeClose(() -> value.set(1000)); - Assert.assertEquals(0, value.get()); + assertEquals(0, value.get()); closeable.close(); - Assert.assertEquals(1000, value.get()); + assertEquals(1000, value.get()); } @@ -125,7 +124,7 @@ public class CriticalAnalyzerTest { latch.countDown(); }); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); analyzer.stop(); } @@ -149,7 +148,7 @@ public class CriticalAnalyzerTest { analyzer.start(); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); analyzer.stop(); } @@ -159,7 +158,7 @@ public class CriticalAnalyzerTest { analyzer = new CriticalAnalyzerImpl().setTimeout(10, TimeUnit.MILLISECONDS).setCheckTime(5, TimeUnit.MILLISECONDS); CriticalComponent component = new CriticalComponentImpl(analyzer, 2); component.measureCritical(0); - Assert.assertFalse(component.checkExpiration(TimeUnit.MINUTES.toNanos(1), false)); + assertFalse(component.checkExpiration(TimeUnit.MINUTES.toNanos(1), false)); analyzer.stop(); } @@ -170,7 +169,7 @@ public class CriticalAnalyzerTest { CriticalComponent component = new CriticalComponentImpl(analyzer, 2); component.measureCritical(0); Thread.sleep(50); - Assert.assertTrue(component.checkExpiration(0, false)); + assertTrue(component.checkExpiration(0, false)); analyzer.stop(); } @@ -192,7 +191,7 @@ public class CriticalAnalyzerTest { analyzer.start(); - Assert.assertFalse(latch.await(100, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(100, TimeUnit.MILLISECONDS)); analyzer.stop(); } @@ -215,13 +214,13 @@ public class CriticalAnalyzerTest { analyzer.start(); - Assert.assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); measure.close(); latch.setCount(1); - Assert.assertFalse(latch.await(100, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(100, TimeUnit.MILLISECONDS)); analyzer.stop(); } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalMeasureTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalMeasureTest.java index 0d89fb80ef..ec6517a752 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalMeasureTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/CriticalMeasureTest.java @@ -17,13 +17,16 @@ package org.apache.activemq.artemis.utils.critical; +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.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.LockSupport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CriticalMeasureTest { @@ -32,7 +35,7 @@ public class CriticalMeasureTest { CriticalMeasure measure = new CriticalMeasure(null, 1); long time = System.nanoTime(); measure.timeEnter = time - TimeUnit.SECONDS.toNanos(5); - Assert.assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); + assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); } @Test @@ -44,7 +47,7 @@ public class CriticalMeasureTest { measure.enterCritical(); measure.timeEnter = time - TimeUnit.MINUTES.toNanos(30); measure.leaveCritical(); - Assert.assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); + assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); } @Test @@ -55,11 +58,11 @@ public class CriticalMeasureTest { long time = System.nanoTime(); AutoCloseable closeable = measure.measure(); measure.timeEnter = time - TimeUnit.MINUTES.toNanos(5); - Assert.assertTrue(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); // on this call we should had a reset before + assertTrue(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); // on this call we should had a reset before // subsequent call without reset should still fail - Assert.assertTrue(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), true)); + assertTrue(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), true)); // previous reset should have cleared it - Assert.assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); + assertFalse(measure.checkExpiration(TimeUnit.SECONDS.toNanos(30), false)); closeable.close(); } @@ -69,9 +72,9 @@ public class CriticalMeasureTest { CriticalComponent component = new CriticalComponentImpl(analyzer, 5); try (AutoCloseable theMeasure = component.measureCritical(0)) { LockSupport.parkNanos(1000); - Assert.assertTrue(component.checkExpiration(100, false)); + assertTrue(component.checkExpiration(100, false)); } - Assert.assertFalse(component.checkExpiration(100, false)); + assertFalse(component.checkExpiration(100, false)); } @Test @@ -101,7 +104,7 @@ public class CriticalMeasureTest { running.set(false); } t.join(1000); - Assert.assertFalse(t.isAlive()); - Assert.assertEquals(0, errors.get()); + assertFalse(t.isAlive()); + assertEquals(0, errors.get()); } } diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/MultiThreadCriticalMeasureTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/MultiThreadCriticalMeasureTest.java index 63f664c429..251e6e048a 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/MultiThreadCriticalMeasureTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/critical/MultiThreadCriticalMeasureTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.utils.critical; +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.lang.invoke.MethodHandles; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -27,11 +32,9 @@ import java.util.concurrent.locks.LockSupport; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.Wait; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.invoke.MethodHandles; -import org.junit.Assert; -import org.junit.Test; public class MultiThreadCriticalMeasureTest { @@ -92,7 +95,7 @@ public class MultiThreadCriticalMeasureTest { // waiting a few milliseconds as the bug was about measuring load after a no load LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(20)); - Assert.assertFalse(measure.checkExpiration(TimeUnit.MILLISECONDS.toNanos(10), false)); + assertFalse(measure.checkExpiration(TimeUnit.MILLISECONDS.toNanos(10), false)); logger.debug("Count down"); // letting load to happen again @@ -102,14 +105,14 @@ public class MultiThreadCriticalMeasureTest { } latchOnMeasure.countUp(); - Assert.assertTrue(Wait.waitFor(() -> measure.checkExpiration(TimeUnit.MILLISECONDS.toNanos(100), false), 1_000, 1)); + assertTrue(Wait.waitFor(() -> measure.checkExpiration(TimeUnit.MILLISECONDS.toNanos(100), false), 1_000, 1)); } finally { load.set(true); running.set(false); latchOnMeasure.countDown(); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); executorService.shutdown(); Wait.assertTrue(executorService::isShutdown); Wait.assertTrue(executorService::isTerminated, 5000, 1); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/runnables/RunnableListTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/runnables/RunnableListTest.java index 8d21fd58d6..94e5a823ed 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/runnables/RunnableListTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/runnables/RunnableListTest.java @@ -17,12 +17,13 @@ package org.apache.activemq.artemis.utils.runnables; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RunnableListTest { @@ -50,16 +51,16 @@ public class RunnableListTest { } } - Assert.assertEquals(30, masterList.size()); + assertEquals(30, masterList.size()); runList(listA); - Assert.assertEquals(10, result.get()); + assertEquals(10, result.get()); - Assert.assertEquals(20, masterList.size()); - Assert.assertEquals(0, listA.size()); - Assert.assertEquals(10, listB.size()); - Assert.assertEquals(10, listC.size()); + assertEquals(20, masterList.size()); + assertEquals(0, listA.size()); + assertEquals(10, listB.size()); + assertEquals(10, listC.size()); HashSet copyList = new HashSet<>(); copyList.addAll(masterList); @@ -67,10 +68,10 @@ public class RunnableListTest { copyList.forEach(r -> r.run()); for (RunnableList l : lists) { - Assert.assertEquals(0, l.size()); + assertEquals(0, l.size()); } - Assert.assertEquals(30, result.get()); + assertEquals(30, result.get()); } @Test @@ -95,25 +96,25 @@ public class RunnableListTest { } } - Assert.assertEquals(30, masterList.size()); + assertEquals(30, masterList.size()); listA.cancel(); - Assert.assertEquals(0, result.get()); + assertEquals(0, result.get()); - Assert.assertEquals(20, masterList.size()); - Assert.assertEquals(0, listA.size()); - Assert.assertEquals(10, listB.size()); - Assert.assertEquals(10, listC.size()); + assertEquals(20, masterList.size()); + assertEquals(0, listA.size()); + assertEquals(10, listB.size()); + assertEquals(10, listC.size()); listB.cancel(); listC.cancel(); for (RunnableList l : lists) { - Assert.assertEquals(0, l.size()); + assertEquals(0, l.size()); } - Assert.assertEquals(0, masterList.size()); + assertEquals(0, masterList.size()); } // runs all AtomicRunnables inside the list diff --git a/artemis-core-client/pom.xml b/artemis-core-client/pom.xml index c7aeda97b2..9ed35e46e5 100644 --- a/artemis-core-client/pom.xml +++ b/artemis-core-client/pom.xml @@ -62,8 +62,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/ClientThreadPoolsTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/ClientThreadPoolsTest.java index ec53d46fb1..09206ab6e1 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/ClientThreadPoolsTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/ClientThreadPoolsTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Properties; @@ -32,30 +35,27 @@ import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class ClientThreadPoolsTest { private static Properties systemProperties; - @BeforeClass + @BeforeAll public static void setup() { systemProperties = System.getProperties(); } - @AfterClass + @AfterAll public static void tearDown() { System.clearProperty(ActiveMQClient.THREAD_POOL_MAX_SIZE_PROPERTY_KEY); System.clearProperty(ActiveMQClient.SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY); ActiveMQClient.initializeGlobalThreadPoolProperties(); ActiveMQClient.clearThreadPools(); - Assert.assertEquals(ActiveMQClient.DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE, ActiveMQClient.getGlobalThreadPoolSize()); + assertEquals(ActiveMQClient.DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE, ActiveMQClient.getGlobalThreadPoolSize()); } @Test @@ -94,9 +94,9 @@ public class ClientThreadPoolsTest { } }); - Assert.assertTrue(inUse.await(10, TimeUnit.SECONDS)); + assertTrue(inUse.await(10, TimeUnit.SECONDS)); ActiveMQClient.clearThreadPools(100, TimeUnit.MILLISECONDS); - Assert.assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); + assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); } @Test @@ -127,14 +127,14 @@ public class ClientThreadPoolsTest { } }); - Assert.assertTrue(inUse.await(10, TimeUnit.SECONDS)); + assertTrue(inUse.await(10, TimeUnit.SECONDS)); poolExecutor.shutdownNow(); scheduledThreadPoolExecutor.shutdownNow(); flowControlPoolExecutor.shutdownNow(); - Assert.assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); + assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(inUse.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); + assertTrue(inUse.await(10, TimeUnit.SECONDS)); + assertTrue(neverLeave.await(10, TimeUnit.SECONDS)); ActiveMQClient.clearThreadPools(100, TimeUnit.MILLISECONDS); } @@ -214,9 +214,9 @@ public class ClientThreadPoolsTest { }); } - Assert.assertTrue(doneMax.await(5, TimeUnit.SECONDS)); + assertTrue(doneMax.await(5, TimeUnit.SECONDS)); latch.countDown(); - Assert.assertTrue(latchTotal.await(5, TimeUnit.SECONDS)); + assertTrue(latchTotal.await(5, TimeUnit.SECONDS)); ScheduledThreadPoolExecutor scheduledThreadPool = (ScheduledThreadPoolExecutor) scheduledThreadPoolField.get(serverLocator); ThreadPoolExecutor flowControlThreadPool = (ThreadPoolExecutor) flowControlThreadPoolField.get(serverLocator); @@ -255,7 +255,7 @@ public class ClientThreadPoolsTest { assertEquals(flowControlThreadPool, fctpe); } - @After + @AfterEach public void cleanup() { // Resets the global thread pool properties back to default. System.setProperties(systemProperties); diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/JsonUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/JsonUtilTest.java index 4e3244031b..8b77475444 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/JsonUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/JsonUtilTest.java @@ -16,14 +16,16 @@ */ package org.apache.activemq.artemis.api.core; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.json.JsonArray; import org.apache.activemq.artemis.json.JsonArrayBuilder; import org.apache.activemq.artemis.json.JsonObject; import org.apache.activemq.artemis.json.JsonObjectBuilder; import org.apache.activemq.artemis.utils.JsonLoader; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JsonUtilTest { @@ -36,9 +38,9 @@ public class JsonUtilTest { JsonObject jsonObject = jsonObjectBuilder.build(); - Assert.assertTrue(jsonObject.containsKey("not-null")); - Assert.assertTrue(jsonObject.containsKey("null")); - Assert.assertEquals(2, jsonObject.size()); + assertTrue(jsonObject.containsKey("not-null")); + assertTrue(jsonObject.containsKey("null")); + assertEquals(2, jsonObject.size()); } @Test @@ -50,7 +52,7 @@ public class JsonUtilTest { JsonArray jsonArray = jsonArrayBuilder.build(); - Assert.assertEquals(2, jsonArray.size()); + assertEquals(2, jsonArray.size()); } @Test @@ -64,8 +66,8 @@ public class JsonUtilTest { JsonObject jsonObject = jsonObjectBuilder.build(); - Assert.assertTrue(jsonObject.containsKey("byteArray")); - Assert.assertEquals(6, jsonObject.getJsonArray("byteArray").size()); + assertTrue(jsonObject.containsKey("byteArray")); + assertEquals(6, jsonObject.getJsonArray("byteArray").size()); } @Test @@ -77,7 +79,7 @@ public class JsonUtilTest { JsonArray jsonArray = jsonArrayBuilder.build(); - Assert.assertEquals(1, jsonArray.size()); + assertEquals(1, jsonArray.size()); } @Test @@ -89,7 +91,7 @@ public class JsonUtilTest { String truncated = (String) JsonUtil.truncate(prefix + remaining, valueSizeLimit); String expected = prefix + ", + " + String.valueOf(remaining.length()) + " more"; - Assert.assertEquals(expected, truncated); + assertEquals(expected, truncated); } @Test @@ -97,14 +99,14 @@ public class JsonUtilTest { String input = "testTruncateUsingStringWithoutValueSizeLimit"; String notTruncated = (String) JsonUtil.truncate(input, -1); - Assert.assertEquals(input, notTruncated); + assertEquals(input, notTruncated); } @Test public void testTruncateWithoutNullValue() { Object result = JsonUtil.truncate(null, -1); - Assert.assertEquals("", result); + assertEquals("", result); } @Test @@ -116,7 +118,7 @@ public class JsonUtilTest { String truncated = JsonUtil.truncateString(prefix + remaining, valueSizeLimit); String expected = prefix + ", + " + String.valueOf(remaining.length()) + " more"; - Assert.assertEquals(expected, truncated); + assertEquals(expected, truncated); } @Test @@ -124,7 +126,7 @@ public class JsonUtilTest { String input = "testTruncateStringWithoutValueSizeLimit"; String notTruncated = JsonUtil.truncateString(input, -1); - Assert.assertEquals(input, notTruncated); + assertEquals(input, notTruncated); } @Test @@ -156,7 +158,7 @@ public class JsonUtilTest { JsonObject mergedExpected = jsonMergedObjectBuilder.build(); - Assert.assertEquals(mergedExpected, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); + assertEquals(mergedExpected, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); } @Test @@ -180,7 +182,7 @@ public class JsonUtilTest { JsonObject mergedExpected = jsonMergedObjectBuilder.build(); - Assert.assertEquals(mergedExpected, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); + assertEquals(mergedExpected, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); } @@ -196,7 +198,7 @@ public class JsonUtilTest { JsonUtil.addToObject("dup", "b", jsonTargetObjectBuilder); JsonObject sourceTwo = jsonTargetObjectBuilder.build(); - Assert.assertEquals(sourceTwo, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); + assertEquals(sourceTwo, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); } @Test @@ -209,7 +211,7 @@ public class JsonUtilTest { JsonUtil.addToObject("dup", "b", jsonTargetObjectBuilder); JsonObject sourceTwo = jsonTargetObjectBuilder.build(); - Assert.assertEquals(sourceTwo, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); + assertEquals(sourceTwo, JsonUtil.mergeAndUpdate(sourceOne, sourceTwo)); } @Test @@ -221,13 +223,13 @@ public class JsonUtilTest { JsonObjectBuilder nested = JsonUtil.objectBuilderWithValueAtPath("a/b/c", target); JsonObject inserted = nested.build(); - Assert.assertTrue(inserted.containsKey("a")); + assertTrue(inserted.containsKey("a")); - Assert.assertEquals(target, inserted.getJsonObject("a").getJsonObject("b").getJsonObject("c")); + assertEquals(target, inserted.getJsonObject("a").getJsonObject("b").getJsonObject("c")); nested = JsonUtil.objectBuilderWithValueAtPath("c", target); inserted = nested.build(); - Assert.assertTrue(inserted.containsKey("c")); - Assert.assertEquals(target, inserted.getJsonObject("c")); + assertTrue(inserted.containsKey("c")); + assertEquals(target, inserted.getJsonObject("c")); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/TransportConfigurationTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/TransportConfigurationTest.java index f035b02359..d50d6f6919 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/TransportConfigurationTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/TransportConfigurationTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.api.core; +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.Collections; import java.util.HashMap; import java.util.Map; @@ -23,8 +28,7 @@ import java.util.Map; import io.netty.buffer.Unpooled; import org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TransportConfigurationTest { @@ -33,8 +37,8 @@ public class TransportConfigurationTest { TransportConfiguration configuration = new TransportConfiguration("SomeClass", new HashMap(), null); TransportConfiguration configuration2 = new TransportConfiguration("SomeClass", new HashMap(), null); - Assert.assertEquals(configuration, configuration2); - Assert.assertEquals(configuration.hashCode(), configuration2.hashCode()); + assertEquals(configuration, configuration2); + assertEquals(configuration.hashCode(), configuration2.hashCode()); HashMap configMap1 = new HashMap<>(); configMap1.put("host", "localhost"); @@ -43,14 +47,14 @@ public class TransportConfigurationTest { configuration = new TransportConfiguration("SomeClass", configMap1, null); configuration2 = new TransportConfiguration("SomeClass", configMap2, null); - Assert.assertEquals(configuration, configuration2); - Assert.assertEquals(configuration.hashCode(), configuration2.hashCode()); + assertEquals(configuration, configuration2); + assertEquals(configuration.hashCode(), configuration2.hashCode()); configuration = new TransportConfiguration("SomeClass", configMap1, "name1"); configuration2 = new TransportConfiguration("SomeClass", configMap2, "name2"); - Assert.assertNotEquals(configuration, configuration2); - Assert.assertNotEquals(configuration.hashCode(), configuration2.hashCode()); - Assert.assertTrue(configuration.isEquivalent(configuration2)); + assertNotEquals(configuration, configuration2); + assertNotEquals(configuration.hashCode(), configuration2.hashCode()); + assertTrue(configuration.isEquivalent(configuration2)); configMap1 = new HashMap<>(); configMap1.put("host", "localhost"); @@ -58,8 +62,8 @@ public class TransportConfigurationTest { configMap2.put("host", "localhost3"); configuration = new TransportConfiguration("SomeClass", configMap1, null); configuration2 = new TransportConfiguration("SomeClass", configMap2, null); - Assert.assertNotEquals(configuration, configuration2); - Assert.assertNotEquals(configuration.hashCode(), configuration2.hashCode()); + assertNotEquals(configuration, configuration2); + assertNotEquals(configuration.hashCode(), configuration2.hashCode()); } @@ -70,17 +74,17 @@ public class TransportConfigurationTest { final Map params = Collections.emptyMap(); final Map extraParams = Collections.singletonMap("key", "foo"); - Assert.assertEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, null)); - Assert.assertEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, Collections.emptyMap())); - Assert.assertEquals(new TransportConfiguration(className, params, name, Collections.emptyMap()), new TransportConfiguration(className, params, name, null)); - Assert.assertEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, extraParams)); - Assert.assertEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, new HashMap<>(extraParams))); + assertEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, null)); + assertEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, Collections.emptyMap())); + assertEquals(new TransportConfiguration(className, params, name, Collections.emptyMap()), new TransportConfiguration(className, params, name, null)); + assertEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, extraParams)); + assertEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, new HashMap<>(extraParams))); - Assert.assertNotEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, extraParams)); - Assert.assertNotEquals(new TransportConfiguration(className, params, name, Collections.emptyMap()), new TransportConfiguration(className, params, name, extraParams)); - Assert.assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, Collections.singletonMap("key", "other"))); - Assert.assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, null)); - Assert.assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, Collections.emptyMap())); + assertNotEquals(new TransportConfiguration(className, params, name, null), new TransportConfiguration(className, params, name, extraParams)); + assertNotEquals(new TransportConfiguration(className, params, name, Collections.emptyMap()), new TransportConfiguration(className, params, name, extraParams)); + assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, Collections.singletonMap("key", "other"))); + assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, null)); + assertNotEquals(new TransportConfiguration(className, params, name, extraParams), new TransportConfiguration(className, params, name, Collections.emptyMap())); } @Test @@ -91,7 +95,7 @@ public class TransportConfigurationTest { TransportConfiguration configuration = new TransportConfiguration("SomeClass", params, null); - Assert.assertFalse("configuration contains secret_password", configuration.toString().contains("secret_password")); + assertFalse(configuration.toString().contains("secret_password"), "configuration contains secret_password"); } @Test @@ -129,14 +133,14 @@ public class TransportConfigurationTest { TransportConfiguration decodedTransportConfiguration = new TransportConfiguration(); decodedTransportConfiguration.decode(buffer); - Assert.assertFalse(buffer.readable()); + assertFalse(buffer.readable()); - Assert.assertEquals(transportConfiguration.getParams(), decodedTransportConfiguration.getParams()); + assertEquals(transportConfiguration.getParams(), decodedTransportConfiguration.getParams()); - Assert.assertTrue((transportConfiguration.getExtraParams() == null && (decodedTransportConfiguration.getExtraParams() == null || decodedTransportConfiguration.getExtraParams().isEmpty())) || + assertTrue((transportConfiguration.getExtraParams() == null && (decodedTransportConfiguration.getExtraParams() == null || decodedTransportConfiguration.getExtraParams().isEmpty())) || (decodedTransportConfiguration.getExtraParams() == null && (transportConfiguration.getExtraParams() == null || transportConfiguration.getExtraParams().isEmpty())) || (transportConfiguration.getExtraParams() != null && decodedTransportConfiguration.getExtraParams() != null && transportConfiguration.getExtraParams().equals(decodedTransportConfiguration.getExtraParams()))); - Assert.assertEquals(transportConfiguration, decodedTransportConfiguration); + assertEquals(transportConfiguration, decodedTransportConfiguration); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java index 168aa71529..1098edb59b 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java @@ -19,12 +19,12 @@ package org.apache.activemq.artemis.api.core.management; -import org.apache.activemq.artemis.api.core.RoutingType; -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.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.apache.activemq.artemis.api.core.RoutingType; +import org.junit.jupiter.api.Test; public class AddressSettingsInfoTest { @@ -146,7 +146,7 @@ public class AddressSettingsInfoTest { assertEquals(404, addressSettingsInfo.getExpiryDelay()); assertEquals(40, addressSettingsInfo.getMinExpiryDelay()); assertEquals(4004, addressSettingsInfo.getMaxExpiryDelay()); - assertEquals(false, addressSettingsInfo.isEnableMetrics()); + assertFalse(addressSettingsInfo.isEnableMetrics()); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/OperationAnnotationTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/OperationAnnotationTest.java index 8ef438f346..101b7a3040 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/OperationAnnotationTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/OperationAnnotationTest.java @@ -19,21 +19,22 @@ package org.apache.activemq.artemis.api.core.management; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; -import static org.junit.Assert.assertTrue; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class OperationAnnotationTest { - @Parameterized.Parameters(name = "class=({0})") + @Parameters(name = "class=({0})") public static Collection getTestParameters() { return Arrays.asList(new Object[][]{{ActiveMQServerControl.class}, {AddressControl.class}, @@ -52,7 +53,7 @@ public class OperationAnnotationTest { this.managementClass = managementClass; } - @Test + @TestTemplate public void testEachParameterAnnotated() throws Exception { checkControlInterface(managementClass); } @@ -76,7 +77,7 @@ public class OperationAnnotationTest { break; } } - assertTrue("method " + m + " has parameters with no Parameter annotation", hasParameterAnnotation); + assertTrue(hasParameterAnnotation, "method " + m + " has parameters with no Parameter annotation"); } } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/ResourceNamesTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/ResourceNamesTest.java index 74559e6199..285fc42d85 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/ResourceNamesTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/ResourceNamesTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.api.core.management; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Collection; import java.util.UUID; @@ -23,13 +26,13 @@ import java.util.UUID; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(value = Parameterized.class) -public class ResourceNamesTest extends Assert { +@ExtendWith(ParameterizedTestExtension.class) +public class ResourceNamesTest { char delimiterChar; final String delimiter; @@ -42,7 +45,7 @@ public class ResourceNamesTest extends Assert { final String testResourceDivertName; - @Parameterized.Parameters(name = "delimiterChar={0}") + @Parameters(name = "delimiterChar={0}") public static Collection getParams() { return Arrays.asList(new Object[][] {{'/'}, {'.'}}); } @@ -60,28 +63,28 @@ public class ResourceNamesTest extends Assert { testResourceDivertName = baseName + ResourceNames.DIVERT.replace('.', delimiterChar) + ResourceNames.RETROACTIVE_SUFFIX; } - @Test + @TestTemplate public void testGetRetroactiveResourceAddressName() { assertEquals(testResourceAddressName, ResourceNames.getRetroactiveResourceAddressName(prefix, delimiter, testAddress).toString()); } - @Test + @TestTemplate public void testGetRetroactiveResourceQueueName() { assertEquals(testResourceMulticastQueueName, ResourceNames.getRetroactiveResourceQueueName(prefix, delimiter, testAddress, RoutingType.MULTICAST).toString()); assertEquals(testResourceAnycastQueueName, ResourceNames.getRetroactiveResourceQueueName(prefix, delimiter, testAddress, RoutingType.ANYCAST).toString()); } - @Test + @TestTemplate public void testGetRetroactiveResourceDivertName() { assertEquals(testResourceDivertName, ResourceNames.getRetroactiveResourceDivertName(prefix, delimiter, testAddress).toString()); } - @Test + @TestTemplate public void testDecomposeRetroactiveResourceAddressName() { assertEquals(testAddress.toString(), ResourceNames.decomposeRetroactiveResourceAddressName(prefix, delimiter, testResourceAddressName)); } - @Test + @TestTemplate public void testIsRetroactiveResource() { assertTrue(ResourceNames.isRetroactiveResource(prefix, SimpleString.toSimpleString(testResourceAddressName))); assertTrue(ResourceNames.isRetroactiveResource(prefix, SimpleString.toSimpleString(testResourceMulticastQueueName))); diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/CoreClientLogBundlesTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/CoreClientLogBundlesTest.java index e7de2db3c4..a1f7bed9b6 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/CoreClientLogBundlesTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/CoreClientLogBundlesTest.java @@ -16,27 +16,27 @@ */ package org.apache.activemq.artemis.core.client; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class CoreClientLogBundlesTest { private static final String LOGGER_NAME = ActiveMQClientLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } @@ -57,7 +57,7 @@ public class CoreClientLogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ219022")); - assertTrue("unexpected message: " + message, message.contains(String.valueOf(headerSize))); + assertTrue(message.startsWith("AMQ219022"), "unexpected message: " + message); + assertTrue(message.contains(String.valueOf(headerSize)), "unexpected message: " + message); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImplTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImplTest.java index a2b486d4b1..a465b6868e 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImplTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/client/impl/LargeMessageControllerImplTest.java @@ -17,15 +17,19 @@ package org.apache.activemq.artemis.core.client.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.util.Arrays; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.api.core.ActiveMQException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,7 +38,8 @@ public class LargeMessageControllerImplTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @Test(timeout = 10_000) + @Test + @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) public void testControllerTimeout() throws Exception { ClientConsumerInternal consumerMock = Mockito.mock(ClientConsumerInternal.class); @@ -64,13 +69,13 @@ public class LargeMessageControllerImplTest { exceptionCounter++; } - Assert.assertEquals(1, exceptionCounter); + assertEquals(1, exceptionCounter); largeMessageController.addPacket(createBytes(900, filling), 1000, false); - Assert.assertTrue(largeMessageController.waitCompletion(0)); - Assert.assertEquals(1000, bytesWritten.get()); - Assert.assertEquals(0, errors.get()); + assertTrue(largeMessageController.waitCompletion(0)); + assertEquals(1000, bytesWritten.get()); + assertEquals(0, errors.get()); } byte[] createBytes(int size, byte fill) { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImplTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImplTest.java index 9442c62d41..7efa37f31b 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImplTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImplTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.core.protocol.core.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.concurrent.atomic.AtomicInteger; import io.netty.buffer.Unpooled; @@ -26,17 +28,15 @@ import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.ResponseHandler; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.PacketsConfirmedMessage; import org.apache.activemq.artemis.spi.core.remoting.Connection; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; - public class ChannelImplTest { ChannelImpl channel; - @Before + @BeforeEach public void setUp() { CoreRemotingConnection coreRC = Mockito.mock(CoreRemotingConnection.class); Mockito.when(coreRC.createTransportBuffer(Packet.INITIAL_PACKET_SIZE)).thenReturn(new ChannelBufferWrapper(Unpooled.buffer(Packet.INITIAL_PACKET_SIZE))); diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedEventLoopGroupTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedEventLoopGroupTest.java index 618d5ebf61..2000497cf0 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedEventLoopGroupTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/SharedEventLoopGroupTest.java @@ -16,16 +16,16 @@ */ package org.apache.activemq.artemis.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicReference; import io.netty.channel.EventLoop; import io.netty.channel.nio.NioEventLoopGroup; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class SharedEventLoopGroupTest { @Test diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstantTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstantTest.java index 344ab7c295..2243d66e54 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstantTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/remoting/impl/netty/TransportConstantTest.java @@ -17,8 +17,9 @@ package org.apache.activemq.artemis.core.remoting.impl.netty; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; public class TransportConstantTest { @@ -26,7 +27,7 @@ public class TransportConstantTest { * This is just validating the pom still works */ @Test public void testDefaultOnPom() { - Assert.assertEquals("It is expected to have the default at 0 on the testsuite", 0, TransportConstants.DEFAULT_QUIET_PERIOD); - Assert.assertEquals("It is expected to have the default at 0 on the testsuite", 0, TransportConstants.DEFAULT_SHUTDOWN_TIMEOUT); + assertEquals(0, TransportConstants.DEFAULT_QUIET_PERIOD, "It is expected to have the default at 0 on the testsuite"); + assertEquals(0, TransportConstants.DEFAULT_SHUTDOWN_TIMEOUT, "It is expected to have the default at 0 on the testsuite"); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMTMessageTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMTMessageTest.java index bb59512d1a..581e274e33 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMTMessageTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMTMessageTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.message; +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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -30,8 +34,7 @@ import org.apache.activemq.artemis.core.persistence.CoreMessageObjectPools; import org.apache.activemq.artemis.reader.TextMessageUtil; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CoreMTMessageTest { @@ -86,14 +89,14 @@ public class CoreMTMessageTest { try { ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(10 * 1024); aligned.countDown(); - Assert.assertTrue(startFlag.await(5, TimeUnit.SECONDS)); + assertTrue(startFlag.await(5, TimeUnit.SECONDS)); coreMessage.messageChanged(); coreMessage.sendBuffer(buffer.byteBuf(), 0); CoreMessage recMessage = new CoreMessage(); recMessage.receiveBuffer(buffer.byteBuf()); - Assert.assertEquals(ADDRESS2, recMessage.getAddressSimpleString()); - Assert.assertEquals(33, recMessage.getMessageID()); - Assert.assertEquals(propValue, recMessage.getSimpleStringProperty(SimpleString.toSimpleString("str-prop"))); + assertEquals(ADDRESS2, recMessage.getAddressSimpleString()); + assertEquals(33, recMessage.getMessageID()); + assertEquals(propValue, recMessage.getSimpleStringProperty(SimpleString.toSimpleString("str-prop"))); } catch (Throwable e) { e.printStackTrace(); errors.incrementAndGet(); @@ -113,10 +116,10 @@ public class CoreMTMessageTest { for (Thread t : threads) { t.join(10000); - Assert.assertFalse(t.isAlive()); + assertFalse(t.isAlive()); } - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMessageTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMessageTest.java index f625f4e976..8f46a95e65 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMessageTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/message/CoreMessageTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.message; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.nio.charset.StandardCharsets; import java.util.LinkedList; @@ -32,10 +38,9 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSen import org.apache.activemq.artemis.reader.TextMessageUtil; import org.apache.activemq.artemis.utils.Base64; import org.apache.activemq.artemis.utils.UUID; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class CoreMessageTest { @@ -65,11 +70,11 @@ public class CoreMessageTest { private ByteBuf BYTE_ENCODE; - @Before + @BeforeEach public void before() { BYTE_ENCODE = Unpooled.wrappedBuffer(Base64.decode(STRING_ENCODE, Base64.DONT_BREAK_LINES | Base64.URL_SAFE)); // some extra caution here, nothing else, to make sure we would get the same encoding back - Assert.assertEquals(STRING_ENCODE, encodeString(BYTE_ENCODE.array())); + assertEquals(STRING_ENCODE, encodeString(BYTE_ENCODE.array())); BYTE_ENCODE.readerIndex(0).writerIndex(BYTE_ENCODE.capacity()); } @@ -78,7 +83,7 @@ public class CoreMessageTest { public void testPassThrough() { CoreMessage decodedMessage = decodeMessage(); - Assert.assertEquals(TEXT, TextMessageUtil.readBodyText(decodedMessage.getReadOnlyBodyBuffer()).toString()); + assertEquals(TEXT, TextMessageUtil.readBodyText(decodedMessage.getReadOnlyBodyBuffer()).toString()); } @Test @@ -86,7 +91,7 @@ public class CoreMessageTest { final CoreMessage decodedMessage = decodeMessage(); final int bodyBufferSize = decodedMessage.getBodyBufferSize(); final int readonlyBodyBufferReadableBytes = decodedMessage.getReadOnlyBodyBuffer().readableBytes(); - Assert.assertEquals(bodyBufferSize, readonlyBodyBufferReadableBytes); + assertEquals(bodyBufferSize, readonlyBodyBufferReadableBytes); } /** The message is received, then sent to the other side untouched */ @@ -95,7 +100,7 @@ public class CoreMessageTest { CoreMessage decodedMessage = decodeMessage(); int encodeSize = decodedMessage.getEncodeSize(); - Assert.assertEquals(BYTE_ENCODE.capacity(), encodeSize); + assertEquals(BYTE_ENCODE.capacity(), encodeSize); SessionSendMessage sendMessage = new SessionSendMessage(decodedMessage, true, null); sendMessage.setChannelID(777); @@ -111,11 +116,11 @@ public class CoreMessageTest { sendMessageReceivedSent.decode(buffer); - Assert.assertEquals(encodeSize, sendMessageReceivedSent.getMessage().getEncodeSize()); + assertEquals(encodeSize, sendMessageReceivedSent.getMessage().getEncodeSize()); - Assert.assertTrue(sendMessageReceivedSent.isRequiresResponse()); + assertTrue(sendMessageReceivedSent.isRequiresResponse()); - Assert.assertEquals(TEXT, TextMessageUtil.readBodyText(sendMessageReceivedSent.getMessage().getReadOnlyBodyBuffer()).toString()); + assertEquals(TEXT, TextMessageUtil.readBodyText(sendMessageReceivedSent.getMessage().getReadOnlyBodyBuffer()).toString()); } /** The message is received, then sent to the other side untouched */ @@ -124,7 +129,7 @@ public class CoreMessageTest { CoreMessage decodedMessage = decodeMessage(); int encodeSize = decodedMessage.getEncodeSize(); - Assert.assertEquals(BYTE_ENCODE.capacity(), encodeSize); + assertEquals(BYTE_ENCODE.capacity(), encodeSize); SessionReceiveMessage sendMessage = new SessionReceiveMessage(33, decodedMessage, 7); sendMessage.setChannelID(777); @@ -137,13 +142,13 @@ public class CoreMessageTest { sendMessageReceivedSent.decode(buffer); - Assert.assertEquals(33, sendMessageReceivedSent.getConsumerID()); + assertEquals(33, sendMessageReceivedSent.getConsumerID()); - Assert.assertEquals(7, sendMessageReceivedSent.getDeliveryCount()); + assertEquals(7, sendMessageReceivedSent.getDeliveryCount()); - Assert.assertEquals(encodeSize, sendMessageReceivedSent.getMessage().getEncodeSize()); + assertEquals(encodeSize, sendMessageReceivedSent.getMessage().getEncodeSize()); - Assert.assertEquals(TEXT, TextMessageUtil.readBodyText(sendMessageReceivedSent.getMessage().getReadOnlyBodyBuffer()).toString()); + assertEquals(TEXT, TextMessageUtil.readBodyText(sendMessageReceivedSent.getMessage().getReadOnlyBodyBuffer()).toString()); } private CoreMessage decodeMessage() { @@ -155,11 +160,11 @@ public class CoreMessageTest { int encodeSize = coreMessage.getEncodeSize(); - Assert.assertEquals(newBuffer.capacity(), encodeSize); + assertEquals(newBuffer.capacity(), encodeSize); - Assert.assertEquals(ADDRESS, coreMessage.getAddressSimpleString()); + assertEquals(ADDRESS, coreMessage.getAddressSimpleString()); - Assert.assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME)); + assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME)); ByteBuf destinedBuffer = Unpooled.buffer(BYTE_ENCODE.array().length); coreMessage.sendBuffer(destinedBuffer, 0); @@ -169,9 +174,9 @@ public class CoreMessageTest { CoreMessage newDecoded = internalDecode(Unpooled.wrappedBuffer(destinedArray)); - Assert.assertEquals(encodeSize, newDecoded.getEncodeSize()); + assertEquals(encodeSize, newDecoded.getEncodeSize()); - Assert.assertArrayEquals(sourceArray, destinedArray); + assertArrayEquals(sourceArray, destinedArray); return coreMessage; } @@ -205,7 +210,7 @@ public class CoreMessageTest { try { empty2.getBodyBuffer().readLong(); - Assert.fail("should throw exception"); + fail("should throw exception"); } catch (Exception expected) { } @@ -218,23 +223,23 @@ public class CoreMessageTest { coreMessage.putStringProperty("prop", BIGGER_TEXT); coreMessage.putBytesProperty("bytesProp", BIGGER_TEXT.getBytes(StandardCharsets.UTF_8)); - Assert.assertEquals(BIGGER_TEXT.length(), ((String)coreMessage.toMap().get("prop")).length()); - Assert.assertEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toMap().get("bytesProp")).length); + assertEquals(BIGGER_TEXT.length(), ((String)coreMessage.toMap().get("prop")).length()); + assertEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toMap().get("bytesProp")).length); // limit the values - Assert.assertNotEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toMap(40).get("bytesProp")).length); + assertNotEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toMap(40).get("bytesProp")).length); String mapVal = ((String)coreMessage.toMap(40).get("prop")); - Assert.assertNotEquals(BIGGER_TEXT.length(), mapVal.length()); - Assert.assertTrue(mapVal.contains("more")); + assertNotEquals(BIGGER_TEXT.length(), mapVal.length()); + assertTrue(mapVal.contains("more")); mapVal = ((String)coreMessage.toMap(0).get("prop")); - Assert.assertNotEquals(BIGGER_TEXT.length(), mapVal.length()); - Assert.assertTrue(mapVal.contains("more")); + assertNotEquals(BIGGER_TEXT.length(), mapVal.length()); + assertTrue(mapVal.contains("more")); - Assert.assertEquals(BIGGER_TEXT.length(), Integer.parseInt(mapVal.substring(mapVal.lastIndexOf('+') + 1, mapVal.lastIndexOf('m')).trim())); + assertEquals(BIGGER_TEXT.length(), Integer.parseInt(mapVal.substring(mapVal.lastIndexOf('+') + 1, mapVal.lastIndexOf('m')).trim())); - Assert.assertEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toPropertyMap().get("bytesProp")).length); - Assert.assertNotEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toPropertyMap(40).get("bytesProp")).length); + assertEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toPropertyMap().get("bytesProp")).length); + assertNotEquals(BIGGER_TEXT.getBytes(StandardCharsets.UTF_8).length, ((byte[])coreMessage.toPropertyMap(40).get("bytesProp")).length); } @Test @@ -248,11 +253,11 @@ public class CoreMessageTest { CoreMessage empty2 = new CoreMessage(); empty2.receiveBuffer(buffer); - Assert.assertEquals((byte)7, empty2.getBodyBuffer().readByte()); + assertEquals((byte)7, empty2.getBodyBuffer().readByte()); try { empty2.getBodyBuffer().readByte(); - Assert.fail("should throw exception"); + fail("should throw exception"); } catch (Exception expected) { } @@ -284,7 +289,7 @@ public class CoreMessageTest { SimpleString newText = TextMessageUtil.readBodyText(newCoreMessage.getReadOnlyBodyBuffer()); - Assert.assertEquals(newString, newText.toString()); + assertEquals(newString, newText.toString()); // coreMessage.putStringProperty() } @@ -301,8 +306,8 @@ public class CoreMessageTest { threads[i] = new Thread(() -> { try { for (int j = 0; j < 50; j++) { - Assert.assertEquals(ADDRESS, coreMessage.getAddressSimpleString()); - Assert.assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME)); + assertEquals(ADDRESS, coreMessage.getAddressSimpleString()); + assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME)); ByteBuf destinedBuffer = Unpooled.buffer(BYTE_ENCODE.array().length); coreMessage.sendBuffer(destinedBuffer, 0); @@ -310,9 +315,9 @@ public class CoreMessageTest { byte[] destinedArray = destinedBuffer.array(); byte[] sourceArray = BYTE_ENCODE.array(); - Assert.assertArrayEquals(sourceArray, destinedArray); + assertArrayEquals(sourceArray, destinedArray); - Assert.assertEquals(TEXT, TextMessageUtil.readBodyText(coreMessage.getReadOnlyBodyBuffer()).toString()); + assertEquals(TEXT, TextMessageUtil.readBodyText(coreMessage.getReadOnlyBodyBuffer()).toString()); } } catch (Throwable e) { e.printStackTrace(); @@ -340,15 +345,15 @@ public class CoreMessageTest { public void compareOriginal() throws Exception { String generated = generate(TEXT); - Assert.assertEquals(STRING_ENCODE, generated); + assertEquals(STRING_ENCODE, generated); for (int i = 0; i < generated.length(); i++) { - Assert.assertEquals("Chart at " + i + " was " + generated.charAt(i) + " instead of " + STRING_ENCODE.charAt(i), generated.charAt(i), STRING_ENCODE.charAt(i)); + assertEquals(generated.charAt(i), STRING_ENCODE.charAt(i), "Chart at " + i + " was " + generated.charAt(i) + " instead of " + STRING_ENCODE.charAt(i)); } } /** Use this method to update the encode for the known message */ - @Ignore + @Disabled @Test public void generate() throws Exception { @@ -368,8 +373,8 @@ public class CoreMessageTest { copy.putBytesProperty(Message.HDR_ROUTE_TO_IDS, new byte[Long.BYTES]); final int increasedMemoryFootprint = copy.getMemoryEstimate() - memoryEstimate; final int increasedPropertyFootprint = copy.getProperties().getMemoryOffset() - msg.getProperties().getMemoryOffset(); - Assert.assertTrue("memory estimation isn't accounting for the additional encoded property", - increasedMemoryFootprint > increasedPropertyFootprint); + assertTrue(increasedMemoryFootprint > increasedPropertyFootprint, + "memory estimation isn't accounting for the additional encoded property"); } @Test @@ -378,12 +383,12 @@ public class CoreMessageTest { msg.setAddress("a"); msg.putBytesProperty("_", new byte[4096]); final CoreMessage copy = (CoreMessage) msg.copy(2); - Assert.assertEquals(msg.getEncodeSize(), copy.getBuffer().capacity()); + assertEquals(msg.getEncodeSize(), copy.getBuffer().capacity()); copy.setAddress("b"); copy.setBrokerProperty(Message.HDR_ORIGINAL_QUEUE, "a"); copy.setBrokerProperty(Message.HDR_ORIGINAL_ADDRESS, msg.getAddressSimpleString()); copy.setBrokerProperty(Message.HDR_ORIG_MESSAGE_ID, msg.getMessageID()); - Assert.assertEquals(copy.getEncodeSize(), copy.getBuffer().capacity()); + assertEquals(copy.getEncodeSize(), copy.getBuffer().capacity()); } private void printVariable(String body, String encode) { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/remoting/ssl/OpenSSLContextFactoryProviderTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/remoting/ssl/OpenSSLContextFactoryProviderTest.java index 1869d950eb..57ed8390d9 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/remoting/ssl/OpenSSLContextFactoryProviderTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/remoting/ssl/OpenSSLContextFactoryProviderTest.java @@ -16,9 +16,9 @@ */ package org.apache.activemq.artemis.spi.core.remoting.ssl; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class OpenSSLContextFactoryProviderTest { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/uri/ConnectorTransportConfigurationParserURITest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/uri/ConnectorTransportConfigurationParserURITest.java index 6c8f5bc859..91d0b67529 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/uri/ConnectorTransportConfigurationParserURITest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/tests/uri/ConnectorTransportConfigurationParserURITest.java @@ -16,16 +16,17 @@ */ package org.apache.activemq.artemis.tests.uri; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.invoke.MethodHandles; import java.net.URI; import java.util.List; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.uri.ConnectorTransportConfigurationParser; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.invoke.MethodHandles; -import org.junit.Assert; -import org.junit.Test; public class ConnectorTransportConfigurationParserURITest { @@ -42,13 +43,13 @@ public class ConnectorTransportConfigurationParserURITest { objects.forEach(t -> logger.info("transportConfig: {}", t)); } - Assert.assertEquals(3, objects.size()); - Assert.assertEquals("live", objects.get(0).getParams().get("host")); - Assert.assertEquals("1", objects.get(0).getParams().get("port")); - Assert.assertEquals("backupA", objects.get(1).getParams().get("host")); - Assert.assertEquals("2", objects.get(1).getParams().get("port")); - Assert.assertEquals("backupB", objects.get(2).getParams().get("host")); - Assert.assertEquals("3", objects.get(2).getParams().get("port")); + assertEquals(3, objects.size()); + assertEquals("live", objects.get(0).getParams().get("host")); + assertEquals("1", objects.get(0).getParams().get("port")); + assertEquals("backupA", objects.get(1).getParams().get("host")); + assertEquals("2", objects.get(1).getParams().get("port")); + assertEquals("backupB", objects.get(2).getParams().get("host")); + assertEquals("3", objects.get(2).getParams().get("port")); } @Test @@ -62,15 +63,15 @@ public class ConnectorTransportConfigurationParserURITest { objects.forEach(t -> logger.info("transportConfig: {}", t)); } - Assert.assertEquals(3, objects.size()); - Assert.assertEquals("live1", objects.get(0).getName()); - Assert.assertEquals("live", objects.get(0).getParams().get("host")); - Assert.assertEquals("1", objects.get(0).getParams().get("port")); - Assert.assertEquals("backupA2", objects.get(1).getName()); - Assert.assertEquals("backupA", objects.get(1).getParams().get("host")); - Assert.assertEquals("2", objects.get(1).getParams().get("port")); - Assert.assertEquals("backupB3", objects.get(2).getName()); - Assert.assertEquals("backupB", objects.get(2).getParams().get("host")); - Assert.assertEquals("3", objects.get(2).getParams().get("port")); + assertEquals(3, objects.size()); + assertEquals("live1", objects.get(0).getName()); + assertEquals("live", objects.get(0).getParams().get("host")); + assertEquals("1", objects.get(0).getParams().get("port")); + assertEquals("backupA2", objects.get(1).getName()); + assertEquals("backupA", objects.get(1).getParams().get("host")); + assertEquals("2", objects.get(1).getParams().get("port")); + assertEquals("backupB3", objects.get(2).getName()); + assertEquals("backupB", objects.get(2).getParams().get("host")); + assertEquals("3", objects.get(2).getParams().get("port")); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/BufferHelperTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/BufferHelperTest.java index 961bd511d9..768b93bb24 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/BufferHelperTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/BufferHelperTest.java @@ -16,11 +16,12 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.utils.BufferHelper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BufferHelperTest { @Test @@ -33,9 +34,9 @@ public class BufferHelperTest { buffer.writeNullableString(s); int size = BufferHelper.sizeOfNullableString(s); int written = buffer.writerIndex(); - Assert.assertEquals(written, size); + assertEquals(written, size); String readString = buffer.readNullableString(); - Assert.assertEquals(s, readString); + assertEquals(s, readString); } } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java index ff2474a6f5..981ede1f21 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/CompressionUtilTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; @@ -26,10 +28,9 @@ import java.util.zip.Deflater; import org.apache.activemq.artemis.utils.DeflaterReader; import org.apache.activemq.artemis.utils.InflaterReader; import org.apache.activemq.artemis.utils.InflaterWriter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CompressionUtilTest extends Assert { +public class CompressionUtilTest { @Test public void testDeflaterReader() throws Exception { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConfigurationHelperTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConfigurationHelperTest.java index 4cd8eeb1e0..cfb2a8cd20 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConfigurationHelperTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/ConfigurationHelperTest.java @@ -16,12 +16,13 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.HashMap; import java.util.Map; import org.apache.activemq.artemis.utils.ConfigurationHelper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ConfigurationHelperTest { @@ -29,13 +30,13 @@ public class ConfigurationHelperTest { public void testDefaultInt() { Map values = new HashMap<>(); values.put("test", "zzz"); - Assert.assertEquals(3, ConfigurationHelper.getIntProperty("test", 3, values)); + assertEquals(3, ConfigurationHelper.getIntProperty("test", 3, values)); } @Test public void testDefaultLong() { Map values = new HashMap<>(); values.put("test", "zzz"); - Assert.assertEquals(3L, ConfigurationHelper.getLongProperty("test", 3L, values)); + assertEquals(3L, ConfigurationHelper.getLongProperty("test", 3L, values)); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/StringUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/StringUtilTest.java index d1022e102c..c73b455fc0 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/StringUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/StringUtilTest.java @@ -16,14 +16,15 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.List; import org.apache.activemq.artemis.utils.StringUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class StringUtilTest extends Assert { +public class StringUtilTest { @Test public void testJoinStringList() throws Exception { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java index 081996ab08..ee1ee28335 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/TimeAndCounterIDGeneratorTest.java @@ -16,15 +16,18 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.utils.TimeAndCounterIDGenerator; import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TimeAndCounterIDGeneratorTest extends Assert { +public class TimeAndCounterIDGeneratorTest { @Test public void testCalculation() { @@ -36,7 +39,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert { for (long i = 0; i < max; i++) { long seqNr = seq.generateID(); - Assert.assertTrue("The sequence generator should aways generate crescent numbers", seqNr > lastNr); + assertTrue(seqNr > lastNr, "The sequence generator should aways generate crescent numbers"); lastNr = seqNr; } @@ -48,16 +51,16 @@ public class TimeAndCounterIDGeneratorTest extends Assert { TimeAndCounterIDGenerator seq = new TimeAndCounterIDGenerator(); long id1 = seq.generateID(); - Assert.assertEquals(1, id1 & 0xffff); - Assert.assertEquals(2, seq.generateID() & 0xffff); + assertEquals(1, id1 & 0xffff); + assertEquals(2, seq.generateID() & 0xffff); seq.refresh(); long id2 = seq.generateID(); - Assert.assertTrue(id2 > id1); + assertTrue(id2 > id1); - Assert.assertEquals(1, id2 & 0xffff); + assertEquals(1, id2 & 0xffff); } @@ -83,15 +86,15 @@ public class TimeAndCounterIDGeneratorTest extends Assert { public void run() { try { latchAlign.countDown(); - assertTrue("Latch has got to return within a minute", latchStart.await(1, TimeUnit.MINUTES)); + assertTrue(latchStart.await(1, TimeUnit.MINUTES), "Latch has got to return within a minute"); long lastValue = 0L; for (int i = 0; i < NUMBER_OF_IDS; i++) { long value = seq.generateID(); - Assert.assertTrue(TimeAndCounterIDGeneratorTest.hex(value) + " should be greater than " + + assertTrue(value > lastValue, TimeAndCounterIDGeneratorTest.hex(value) + " should be greater than " + TimeAndCounterIDGeneratorTest.hex(lastValue) + " on seq " + - seq.toString(), value > lastValue); + seq.toString()); lastValue = value; hashSet.add(value); @@ -110,7 +113,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert { arrays[i].start(); } - assertTrue("Latch has got to return within a minute", latchAlign.await(1, TimeUnit.MINUTES)); + assertTrue(latchAlign.await(1, TimeUnit.MINUTES), "Latch has got to return within a minute"); latchStart.countDown(); @@ -121,7 +124,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert { } } - Assert.assertEquals(NUMBER_OF_THREADS * NUMBER_OF_IDS, hashSet.size()); + assertEquals(NUMBER_OF_THREADS * NUMBER_OF_IDS, hashSet.size()); hashSet.clear(); @@ -138,7 +141,7 @@ public class TimeAndCounterIDGeneratorTest extends Assert { try { // This is simulating a situation where we generated more than 268 million messages on the same time interval seq.generateID(); - Assert.fail("It was supposed to throw an exception, as the counter was set to explode on this test"); + fail("It was supposed to throw an exception, as the counter was set to explode on this test"); } catch (Exception e) { } @@ -153,8 +156,8 @@ public class TimeAndCounterIDGeneratorTest extends Assert { // This is ok... the time portion would be added to the next one generated 10 seconds ago seq.generateID(); - Assert.assertTrue(TimeAndCounterIDGeneratorTest.hex(timeMark) + " < " + - TimeAndCounterIDGeneratorTest.hex(seq.getInternalTimeMark()), timeMark < seq.getInternalTimeMark()); + assertTrue(timeMark < seq.getInternalTimeMark(), TimeAndCounterIDGeneratorTest.hex(timeMark) + " < " + + TimeAndCounterIDGeneratorTest.hex(seq.getInternalTimeMark())); } private static String hex(final long value) { diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java index 541ea1f959..92ff8f7323 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XMLUtilTest.java @@ -16,10 +16,13 @@ */ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.activemq.artemis.utils.SilentTestCase; import org.apache.activemq.artemis.utils.XMLUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -33,7 +36,7 @@ public class XMLUtilTest extends SilentTestCase { Element e = XMLUtil.stringToElement(document); - Assert.assertEquals("foo", XMLUtil.getTextContent(e)); + assertEquals("foo", XMLUtil.getTextContent(e)); } @Test @@ -42,7 +45,7 @@ public class XMLUtilTest extends SilentTestCase { Element e = XMLUtil.stringToElement(document); - Assert.assertEquals("foo", XMLUtil.getTextContent(e)); + assertEquals("foo", XMLUtil.getTextContent(e)); } @Test @@ -55,7 +58,7 @@ public class XMLUtilTest extends SilentTestCase { Element subelement = XMLUtil.stringToElement(s); - Assert.assertEquals("a", subelement.getNodeName()); + assertEquals("a", subelement.getNodeName()); } @Test @@ -68,7 +71,7 @@ public class XMLUtilTest extends SilentTestCase { Element subelement = XMLUtil.stringToElement(s); - Assert.assertEquals("a", subelement.getNodeName()); + assertEquals("a", subelement.getNodeName()); } @Test @@ -81,7 +84,7 @@ public class XMLUtilTest extends SilentTestCase { Element subelement = XMLUtil.stringToElement(s); - Assert.assertEquals("a", subelement.getNodeName()); + assertEquals("a", subelement.getNodeName()); NodeList nl = subelement.getChildNodes(); // try to find @@ -92,7 +95,7 @@ public class XMLUtilTest extends SilentTestCase { found = true; } } - Assert.assertTrue(found); + assertTrue(found); } @Test @@ -118,7 +121,7 @@ public class XMLUtilTest extends SilentTestCase { try { XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); - Assert.fail("this should throw exception"); + fail("this should throw exception"); } catch (IllegalArgumentException e) { // expected } @@ -155,7 +158,7 @@ public class XMLUtilTest extends SilentTestCase { try { XMLUtil.assertEquivalent(XMLUtil.stringToElement(s), XMLUtil.stringToElement(s2)); - Assert.fail("this should throw exception"); + fail("this should throw exception"); } catch (IllegalArgumentException e) { // OK e.printStackTrace(); @@ -213,7 +216,7 @@ public class XMLUtilTest extends SilentTestCase { System.setProperty("sysprop1", "test1"); System.setProperty("sysprop2", "content4"); String replaced = XMLUtil.replaceSystemPropsInString(before); - Assert.assertEquals(after, replaced); + assertEquals(after, replaced); } @Test @@ -223,7 +226,7 @@ public class XMLUtilTest extends SilentTestCase { System.setProperty("sysprop1", "test1"); System.setProperty("sysprop2", "content4"); String replaced = XMLUtil.replaceSystemPropsInString(before); - Assert.assertEquals(after, replaced); + assertEquals(after, replaced); } @Test @@ -233,7 +236,7 @@ public class XMLUtilTest extends SilentTestCase { System.setProperty("sysprop1", "test1"); System.setProperty("sysprop2", "content4"); String replaced = XMLUtil.replaceSystemPropsInString(before); - Assert.assertEquals(after, replaced); + assertEquals(after, replaced); } @Test @@ -241,7 +244,7 @@ public class XMLUtilTest extends SilentTestCase { String xml = ""; String stripped = XMLUtil.stripCDATA(xml); - Assert.assertEquals("somedata", stripped); + assertEquals("somedata", stripped); } } diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XidCodecSupportTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XidCodecSupportTest.java index f86547ed13..753cc578e1 100644 --- a/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XidCodecSupportTest.java +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/util/XidCodecSupportTest.java @@ -17,19 +17,20 @@ package org.apache.activemq.artemis.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.core.transaction.impl.XidImpl; import org.apache.activemq.artemis.utils.UUIDGenerator; import org.apache.activemq.artemis.utils.XidCodecSupport; import org.apache.activemq.artemis.api.core.ActiveMQInvalidBufferException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.transaction.xa.Xid; -import static org.junit.Assert.fail; - public class XidCodecSupportTest { private static final Xid VALID_XID = @@ -40,11 +41,11 @@ public class XidCodecSupportTest { final ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(0); XidCodecSupport.encodeXid(VALID_XID, buffer); - Assert.assertEquals(51, buffer.readableBytes()); // formatId(4) + branchQualLength(4) + branchQual(3) + + assertEquals(51, buffer.readableBytes()); // formatId(4) + branchQualLength(4) + branchQual(3) + // globalTxIdLength(4) + globalTx(36) final Xid readXid = XidCodecSupport.decodeXid(buffer); - Assert.assertEquals(VALID_XID, readXid); + assertEquals(VALID_XID, readXid); } @Test @@ -63,13 +64,15 @@ public class XidCodecSupportTest { fail("should have thrown exception"); } - @Test(expected = ActiveMQInvalidBufferException.class) + @Test public void testOverflowLength() { - final ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(0); - XidCodecSupport.encodeXid(VALID_XID, buffer); - // Alter globalTxIdLength to be too big - buffer.setByte(11, (byte) 0x0C); + assertThrows(ActiveMQInvalidBufferException.class, () -> { + final ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(0); + XidCodecSupport.encodeXid(VALID_XID, buffer); + // Alter globalTxIdLength to be too big + buffer.setByte(11, (byte) 0x0C); - XidCodecSupport.decodeXid(buffer); + XidCodecSupport.decodeXid(buffer); + }); } } \ No newline at end of file diff --git a/artemis-dto/pom.xml b/artemis-dto/pom.xml index 80a1a922e0..882317e693 100644 --- a/artemis-dto/pom.xml +++ b/artemis-dto/pom.xml @@ -61,8 +61,13 @@ ${jakarta.activation-api.version} - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/BindingDTOTest.java b/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/BindingDTOTest.java index 728232fcc5..531bb9261e 100644 --- a/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/BindingDTOTest.java +++ b/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/BindingDTOTest.java @@ -16,20 +16,22 @@ */ package org.apache.activemq.artemis.dto.test; -import org.apache.activemq.artemis.dto.BindingDTO; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class BindingDTOTest extends Assert { +import org.apache.activemq.artemis.dto.BindingDTO; +import org.junit.jupiter.api.Test; + +public class BindingDTOTest { @Test public void testDefault() { BindingDTO binding = new BindingDTO(); - Assert.assertNull(binding.getIncludedTLSProtocols()); - Assert.assertNull(binding.getExcludedTLSProtocols()); - Assert.assertNull(binding.getIncludedCipherSuites()); - Assert.assertNull(binding.getExcludedCipherSuites()); + assertNull(binding.getIncludedTLSProtocols()); + assertNull(binding.getExcludedTLSProtocols()); + assertNull(binding.getIncludedCipherSuites()); + assertNull(binding.getExcludedCipherSuites()); } @Test @@ -37,16 +39,16 @@ public class BindingDTOTest extends Assert { BindingDTO binding = new BindingDTO(); binding.setIncludedTLSProtocols("TLSv1.2"); - Assert.assertArrayEquals(new String[] {"TLSv1.2"}, binding.getIncludedTLSProtocols()); + assertArrayEquals(new String[] {"TLSv1.2"}, binding.getIncludedTLSProtocols()); binding.setExcludedTLSProtocols("TLSv1,TLSv1.1"); - Assert.assertArrayEquals(new String[] {"TLSv1", "TLSv1.1"}, binding.getExcludedTLSProtocols()); + assertArrayEquals(new String[] {"TLSv1", "TLSv1.1"}, binding.getExcludedTLSProtocols()); binding.setIncludedCipherSuites( "^SSL_.*$"); - Assert.assertArrayEquals(new String[] {"^SSL_.*$"}, binding.getIncludedCipherSuites()); + assertArrayEquals(new String[] {"^SSL_.*$"}, binding.getIncludedCipherSuites()); binding.setExcludedCipherSuites( "^.*_(MD5|SHA|SHA1)$,^TLS_RSA_.*$,^.*_NULL_.*$,^.*_anon_.*$"); - Assert.assertArrayEquals(new String[] {"^.*_(MD5|SHA|SHA1)$", "^TLS_RSA_.*$", "^.*_NULL_.*$", "^.*_anon_.*$"}, binding.getExcludedCipherSuites()); + assertArrayEquals(new String[] {"^.*_(MD5|SHA|SHA1)$", "^TLS_RSA_.*$", "^.*_NULL_.*$", "^.*_anon_.*$"}, binding.getExcludedCipherSuites()); } @Test @@ -54,16 +56,16 @@ public class BindingDTOTest extends Assert { BindingDTO binding = new BindingDTO(); binding.setIncludedTLSProtocols(""); - Assert.assertArrayEquals(new String[] {""}, binding.getIncludedTLSProtocols()); + assertArrayEquals(new String[] {""}, binding.getIncludedTLSProtocols()); binding.setExcludedTLSProtocols(""); - Assert.assertArrayEquals(new String[] {""}, binding.getExcludedTLSProtocols()); + assertArrayEquals(new String[] {""}, binding.getExcludedTLSProtocols()); binding.setIncludedCipherSuites(""); - Assert.assertArrayEquals(new String[] {""}, binding.getIncludedCipherSuites()); + assertArrayEquals(new String[] {""}, binding.getIncludedCipherSuites()); binding.setExcludedCipherSuites(""); - Assert.assertArrayEquals(new String[] {""}, binding.getExcludedCipherSuites()); + assertArrayEquals(new String[] {""}, binding.getExcludedCipherSuites()); } @Test @@ -71,15 +73,15 @@ public class BindingDTOTest extends Assert { BindingDTO binding = new BindingDTO(); binding.setIncludedTLSProtocols(null); - Assert.assertNull(binding.getIncludedTLSProtocols()); + assertNull(binding.getIncludedTLSProtocols()); binding.setExcludedTLSProtocols(null); - Assert.assertNull(binding.getExcludedTLSProtocols()); + assertNull(binding.getExcludedTLSProtocols()); binding.setIncludedCipherSuites(null); - Assert.assertNull(binding.getIncludedCipherSuites()); + assertNull(binding.getIncludedCipherSuites()); binding.setExcludedCipherSuites(null); - Assert.assertNull(binding.getExcludedCipherSuites()); + assertNull(binding.getExcludedCipherSuites()); } } diff --git a/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/WebServerDTOTest.java b/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/WebServerDTOTest.java index 54709d04cc..b178550fd3 100644 --- a/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/WebServerDTOTest.java +++ b/artemis-dto/src/test/java/org/apache/activemq/artemis/dto/test/WebServerDTOTest.java @@ -16,10 +16,13 @@ */ package org.apache.activemq.artemis.dto.test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.apache.activemq.artemis.dto.BindingDTO; import org.apache.activemq.artemis.dto.WebServerDTO; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -30,26 +33,26 @@ public class WebServerDTOTest { public void testDefault() throws Exception { WebServerDTO webServer = new WebServerDTO(); - Assert.assertNotNull(webServer.getAllBindings()); - Assert.assertEquals(1, webServer.getAllBindings().size()); - Assert.assertNotNull(webServer.getDefaultBinding()); + assertNotNull(webServer.getAllBindings()); + assertEquals(1, webServer.getAllBindings().size()); + assertNotNull(webServer.getDefaultBinding()); BindingDTO defaultBinding = webServer.getDefaultBinding(); - Assert.assertNull(defaultBinding.uri); - Assert.assertNull(defaultBinding.apps); - Assert.assertNull(defaultBinding.clientAuth); - Assert.assertNull(defaultBinding.passwordCodec); - Assert.assertNull(defaultBinding.keyStorePath); - Assert.assertNull(defaultBinding.trustStorePath); - Assert.assertNull(defaultBinding.getIncludedTLSProtocols()); - Assert.assertNull(defaultBinding.getExcludedTLSProtocols()); - Assert.assertNull(defaultBinding.getIncludedCipherSuites()); - Assert.assertNull(defaultBinding.getExcludedCipherSuites()); - Assert.assertNull(defaultBinding.getKeyStorePassword()); - Assert.assertNull(defaultBinding.getTrustStorePassword()); - Assert.assertNull(defaultBinding.getSniHostCheck()); - Assert.assertNull(defaultBinding.getSniRequired()); - Assert.assertNull(defaultBinding.getSslAutoReload()); + assertNull(defaultBinding.uri); + assertNull(defaultBinding.apps); + assertNull(defaultBinding.clientAuth); + assertNull(defaultBinding.passwordCodec); + assertNull(defaultBinding.keyStorePath); + assertNull(defaultBinding.trustStorePath); + assertNull(defaultBinding.getIncludedTLSProtocols()); + assertNull(defaultBinding.getExcludedTLSProtocols()); + assertNull(defaultBinding.getIncludedCipherSuites()); + assertNull(defaultBinding.getExcludedCipherSuites()); + assertNull(defaultBinding.getKeyStorePassword()); + assertNull(defaultBinding.getTrustStorePassword()); + assertNull(defaultBinding.getSniHostCheck()); + assertNull(defaultBinding.getSniRequired()); + assertNull(defaultBinding.getSslAutoReload()); } @Test @@ -57,10 +60,10 @@ public class WebServerDTOTest { WebServerDTO webServer = new WebServerDTO(); webServer.bind = "http://localhost:0"; - Assert.assertNotNull(webServer.getAllBindings()); - Assert.assertEquals(1, webServer.getAllBindings().size()); - Assert.assertNotNull(webServer.getDefaultBinding()); - Assert.assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); + assertNotNull(webServer.getAllBindings()); + assertEquals(1, webServer.getAllBindings().size()); + assertNotNull(webServer.getDefaultBinding()); + assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); } @Test @@ -71,10 +74,10 @@ public class WebServerDTOTest { WebServerDTO webServer = new WebServerDTO(); webServer.setBindings(Collections.singletonList(binding)); - Assert.assertNotNull(webServer.getAllBindings()); - Assert.assertEquals(1, webServer.getAllBindings().size()); - Assert.assertNotNull(webServer.getDefaultBinding()); - Assert.assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); + assertNotNull(webServer.getAllBindings()); + assertEquals(1, webServer.getAllBindings().size()); + assertNotNull(webServer.getDefaultBinding()); + assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); } @Test @@ -87,12 +90,12 @@ public class WebServerDTOTest { WebServerDTO webServer = new WebServerDTO(); webServer.setBindings(List.of(binding1, binding2)); - Assert.assertNotNull(webServer.getAllBindings()); - Assert.assertEquals(2, webServer.getAllBindings().size()); - Assert.assertNotNull(webServer.getDefaultBinding()); - Assert.assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); - Assert.assertEquals("http://localhost:0", webServer.getAllBindings().get(0).uri); - Assert.assertEquals("http://localhost:1", webServer.getAllBindings().get(1).uri); + assertNotNull(webServer.getAllBindings()); + assertEquals(2, webServer.getAllBindings().size()); + assertNotNull(webServer.getDefaultBinding()); + assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); + assertEquals("http://localhost:0", webServer.getAllBindings().get(0).uri); + assertEquals("http://localhost:1", webServer.getAllBindings().get(1).uri); } @Test @@ -104,10 +107,10 @@ public class WebServerDTOTest { webServer.bind = "http://localhost:1"; webServer.setBindings(Collections.singletonList(binding)); - Assert.assertNotNull(webServer.getAllBindings()); - Assert.assertEquals(1, webServer.getAllBindings().size()); - Assert.assertNotNull(webServer.getDefaultBinding()); - Assert.assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); + assertNotNull(webServer.getAllBindings()); + assertEquals(1, webServer.getAllBindings().size()); + assertNotNull(webServer.getDefaultBinding()); + assertEquals("http://localhost:0", webServer.getDefaultBinding().uri); } } diff --git a/artemis-image/pom.xml b/artemis-image/pom.xml index ae43d16a6a..3a056c40a1 100644 --- a/artemis-image/pom.xml +++ b/artemis-image/pom.xml @@ -47,9 +47,13 @@ pom - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/DelegateCallbackTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/DelegateCallbackTest.java index db7c15dbb1..53edcaba00 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/DelegateCallbackTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/DelegateCallbackTest.java @@ -16,12 +16,14 @@ */ package org.apache.activemq.artemis.core.io; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Collections; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class DelegateCallbackTest { @@ -57,8 +59,8 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(false); final DelegateCallback callback = DelegateCallback.wrap(Arrays.asList(countingIOCallback, countingIOCallback)); callback.done(); - Assert.assertEquals(2, countingIOCallback.done); - Assert.assertEquals(0, countingIOCallback.onError); + assertEquals(2, countingIOCallback.done); + assertEquals(0, countingIOCallback.onError); } @Test @@ -66,8 +68,8 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(false); final DelegateCallback callback = DelegateCallback.wrap(Arrays.asList(countingIOCallback, countingIOCallback)); callback.onError(0, "not a real error"); - Assert.assertEquals(0, countingIOCallback.done); - Assert.assertEquals(2, countingIOCallback.onError); + assertEquals(0, countingIOCallback.done); + assertEquals(2, countingIOCallback.onError); } @Test @@ -75,8 +77,8 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(true); final DelegateCallback callback = DelegateCallback.wrap(Arrays.asList(countingIOCallback, countingIOCallback)); callback.done(); - Assert.assertEquals(2, countingIOCallback.done); - Assert.assertEquals(0, countingIOCallback.onError); + assertEquals(2, countingIOCallback.done); + assertEquals(0, countingIOCallback.onError); } @Test @@ -84,8 +86,8 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(true); final DelegateCallback callback = DelegateCallback.wrap(Arrays.asList(countingIOCallback, countingIOCallback)); callback.onError(0, "not a real error"); - Assert.assertEquals(0, countingIOCallback.done); - Assert.assertEquals(2, countingIOCallback.onError); + assertEquals(0, countingIOCallback.done); + assertEquals(2, countingIOCallback.onError); } @Test @@ -94,7 +96,7 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(true); final DelegateCallback callback = DelegateCallback.wrap(Collections.singleton(countingIOCallback)); callback.done(); - Assert.assertTrue(loggerHandler.findText("AMQ142024")); + assertTrue(loggerHandler.findText("AMQ142024")); } } @@ -104,7 +106,7 @@ public class DelegateCallbackTest { final CountingIOCallback countingIOCallback = new CountingIOCallback(true); final DelegateCallback callback = DelegateCallback.wrap(Collections.singleton(countingIOCallback)); callback.onError(0, "not a real error"); - Assert.assertTrue(loggerHandler.findText("AMQ142025")); + assertTrue(loggerHandler.findText("AMQ142025")); } } diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java index 21451995f3..def8ed3813 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/CallbackOrderTest.java @@ -16,36 +16,33 @@ */ package org.apache.activemq.artemis.core.io.aio; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.io.IOCallback; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * This will emulate callbacks out of order from libaio */ public class CallbackOrderTest { - @Rule - public TemporaryFolder temporaryFolder; - - public CallbackOrderTest() { - File parent = new File("./target"); - parent.mkdirs(); - temporaryFolder = new TemporaryFolder(parent); - } + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File temporaryFolder; /** * This method will make sure callbacks will come back in order even when out order from libaio */ @Test public void testCallbackOutOfOrder() throws Exception { - AIOSequentialFileFactory factory = new AIOSequentialFileFactory(temporaryFolder.getRoot(), 100); + AIOSequentialFileFactory factory = new AIOSequentialFileFactory(temporaryFolder, 100); AIOSequentialFile file = (AIOSequentialFile) factory.createSequentialFile("test.bin"); final AtomicInteger count = new AtomicInteger(0); @@ -78,9 +75,9 @@ public class CallbackOrderTest { list.get(i).done(); } - Assert.assertEquals(N, count.get()); - Assert.assertEquals(0, file.pendingCallbackList.size()); - Assert.assertTrue(file.pendingCallbackList.isEmpty()); + assertEquals(N, count.get()); + assertEquals(0, file.pendingCallbackList.size()); + assertTrue(file.pendingCallbackList.isEmpty()); } factory.stop(); diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/FileIOUtilTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/FileIOUtilTest.java index 6e8685b6ab..b1b46bd4ac 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/FileIOUtilTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/aio/FileIOUtilTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.core.io.aio; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.File; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicInteger; @@ -25,22 +28,15 @@ import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.core.io.util.FileIOUtil; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class FileIOUtilTest { - @Rule - public TemporaryFolder temporaryFolder; - - public FileIOUtilTest() { - File parent = new File("./target"); - parent.mkdirs(); - temporaryFolder = new TemporaryFolder(parent); - } + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File temporaryFolder; /** Since the introduction of asynchronous close on AsyncIO journal there was a situation that if you open a file while it was pending to close @@ -49,10 +45,10 @@ public class FileIOUtilTest { */ @Test public void testOpenClose() throws Exception { - Assume.assumeTrue(LibaioContext.isLoaded()); + assumeTrue(LibaioContext.isLoaded()); AtomicInteger errors = new AtomicInteger(0); - SequentialFileFactory factory = new AIOSequentialFileFactory(temporaryFolder.getRoot(), (Throwable error, String message, String file) -> errors.incrementAndGet(), 4 * 1024); + SequentialFileFactory factory = new AIOSequentialFileFactory(temporaryFolder, (Throwable error, String message, String file) -> errors.incrementAndGet(), 4 * 1024); factory.start(); SequentialFile file = factory.createSequentialFile("fileAIO.bin"); @@ -86,13 +82,13 @@ public class FileIOUtilTest { factory.stop(); } - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } @Test public void testCopy() throws Exception { - SequentialFileFactory factory = new NIOSequentialFileFactory(temporaryFolder.getRoot(), 100); + SequentialFileFactory factory = new NIOSequentialFileFactory(temporaryFolder, 100); SequentialFile file = factory.createSequentialFile("file1.bin"); file.open(); @@ -119,8 +115,8 @@ public class FileIOUtilTest { SequentialFile newFile2 = factory.createSequentialFile("file2.cop"); FileIOUtil.copyData(file2, newFile2, buffer); - Assert.assertEquals(file.size(), newFile.size()); - Assert.assertEquals(file2.size(), newFile2.size()); + assertEquals(file.size(), newFile.size()); + assertEquals(file2.size(), newFile2.size()); newFile.close(); newFile2.close(); diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/util/ThreadLocalByteBufferPoolTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/util/ThreadLocalByteBufferPoolTest.java index abb6251720..f1dc12db49 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/util/ThreadLocalByteBufferPoolTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/io/util/ThreadLocalByteBufferPoolTest.java @@ -16,11 +16,14 @@ */ package org.apache.activemq.artemis.core.io.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.nio.ByteBuffer; import java.util.Arrays; @@ -30,13 +33,13 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.util.internal.PlatformDependent; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class ThreadLocalByteBufferPoolTest { //testing using heap buffers to avoid killing the test suite @@ -48,7 +51,7 @@ public class ThreadLocalByteBufferPoolTest { this.zeroed = zeroed; } - @Parameterized.Parameters(name = "zeroed={0}") + @Parameters(name = "zeroed={0}") public static Collection getParams() { return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); } @@ -59,26 +62,26 @@ public class ThreadLocalByteBufferPoolTest { bb.get(content); final byte[] zeroed = new byte[content.length]; Arrays.fill(zeroed, (byte) 0); - Assert.assertArrayEquals(zeroed, content); + assertArrayEquals(zeroed, content); } - @Test + @TestTemplate public void shouldBorrowOnlyBuffersOfTheCorrectType() { - Assert.assertEquals(isDirect, pool.borrow(0, zeroed).isDirect()); + assertEquals(isDirect, pool.borrow(0, zeroed).isDirect()); } - @Test + @TestTemplate public void shouldBorrowZeroedBuffer() { final int size = 32; final ByteBuffer buffer = pool.borrow(size, zeroed); - Assert.assertEquals(0, buffer.position()); - Assert.assertEquals(size, buffer.limit()); + assertEquals(0, buffer.position()); + assertEquals(size, buffer.limit()); if (zeroed) { assertZeroed(buffer); } } - @Test + @TestTemplate public void shouldBorrowTheSameBuffer() { final int size = 32; final ByteBuffer buffer = pool.borrow(size, zeroed); @@ -88,25 +91,25 @@ public class ThreadLocalByteBufferPoolTest { pool.release(buffer); final int newSize = size - 1; final ByteBuffer sameBuffer = pool.borrow(newSize, zeroed); - Assert.assertSame(buffer, sameBuffer); - Assert.assertEquals(0, sameBuffer.position()); - Assert.assertEquals(newSize, sameBuffer.limit()); + assertSame(buffer, sameBuffer); + assertEquals(0, sameBuffer.position()); + assertEquals(newSize, sameBuffer.limit()); if (zeroed) { assertZeroed(sameBuffer); } } - @Test + @TestTemplate public void shouldBorrowNewBufferIfExceedPooledCapacity() { final int size = 32; final ByteBuffer buffer = pool.borrow(size, zeroed); pool.release(buffer); final int newSize = buffer.capacity() + 1; final ByteBuffer differentBuffer = pool.borrow(newSize, zeroed); - Assert.assertNotSame(buffer, differentBuffer); + assertNotSame(buffer, differentBuffer); } - @Test + @TestTemplate public void shouldPoolTheBiggestBuffer() { final int size = 32; final ByteBuffer small = pool.borrow(size, zeroed); @@ -114,10 +117,10 @@ public class ThreadLocalByteBufferPoolTest { pool.release(small); big.limit(0); pool.release(big); - Assert.assertSame(big, pool.borrow(big.capacity(), zeroed)); + assertSame(big, pool.borrow(big.capacity(), zeroed)); } - @Test + @TestTemplate public void shouldNotPoolTheSmallestBuffer() { final int size = 32; final ByteBuffer small = pool.borrow(size, zeroed); @@ -125,16 +128,16 @@ public class ThreadLocalByteBufferPoolTest { big.limit(0); pool.release(big); pool.release(small); - Assert.assertSame(big, pool.borrow(big.capacity(), zeroed)); + assertSame(big, pool.borrow(big.capacity(), zeroed)); } - @Test + @TestTemplate public void shouldNotPoolBufferOfDifferentType() { final int size = 32; final ByteBuffer buffer = isDirect ? ByteBuffer.allocate(size) : ByteBuffer.allocateDirect(size); try { pool.release(buffer); - Assert.assertNotSame(buffer, pool.borrow(size, zeroed)); + assertNotSame(buffer, pool.borrow(size, zeroed)); } catch (Throwable t) { if (PlatformDependent.hasUnsafe()) { if (buffer.isDirect()) { @@ -144,46 +147,50 @@ public class ThreadLocalByteBufferPoolTest { } } - @Test + @TestTemplate public void shouldNotPoolReadOnlyBuffer() { final int size = 32; final ByteBuffer borrow = pool.borrow(size, zeroed); final ByteBuffer readOnlyBuffer = borrow.asReadOnlyBuffer(); pool.release(readOnlyBuffer); - Assert.assertNotSame(readOnlyBuffer, pool.borrow(size, zeroed)); + assertNotSame(readOnlyBuffer, pool.borrow(size, zeroed)); } - @Test(expected = NullPointerException.class) + @TestTemplate public void shouldFailPoolingNullBuffer() { - pool.release(null); + assertThrows(NullPointerException.class, () -> { + pool.release(null); + }); } - @Test(expected = NullPointerException.class) + @TestTemplate public void shouldFailPoolingNullBufferIfNotEmpty() { - final int size = 32; - pool.release(pool.borrow(size, zeroed)); - pool.release(null); + assertThrows(NullPointerException.class, () -> { + final int size = 32; + pool.release(pool.borrow(size, zeroed)); + pool.release(null); + }); } - @Test + @TestTemplate public void shouldBorrowOnlyThreadLocalBuffers() throws ExecutionException, InterruptedException { final int size = 32; final ByteBuffer buffer = pool.borrow(size, zeroed); pool.release(buffer); final ExecutorService executor = Executors.newSingleThreadExecutor(); try { - Assert.assertNotSame(buffer, executor.submit(() -> pool.borrow(size, zeroed)).get()); + assertNotSame(buffer, executor.submit(() -> pool.borrow(size, zeroed)).get()); } finally { executor.shutdown(); } } - @Test + @TestTemplate public void shouldResetReusedBufferLimitBeforeZeroing() throws Exception { doResetReusedBufferLimitBeforeZeroingTestImpl(true); } - @Test + @TestTemplate public void shouldResetReusedBufferLimitBeforeZeroingWithoutArray() throws Exception { doResetReusedBufferLimitBeforeZeroingTestImpl(false); } @@ -196,7 +203,7 @@ public class ThreadLocalByteBufferPoolTest { final int size = 32; final ByteBuffer buffer = pool.borrow(size, true); - assertEquals("Unexpected buffer limit", size, buffer.limit()); + assertEquals(size, buffer.limit(), "Unexpected buffer limit"); assertFalse(buffer.isDirect()); // Put a non-zero value at the first byte, updating the position @@ -204,9 +211,9 @@ public class ThreadLocalByteBufferPoolTest { // Put a non-zero value at the last byte, not updating the position buffer.put(size - 1, (byte) 5); - assertEquals("Unexpected buffer value at index 0", (byte) 4, buffer.get(0)); - assertEquals("Unexpected buffer value at index " + (size - 1), (byte) 5, buffer.get(size - 1)); - assertEquals("Unexpected buffer position", 1, buffer.position()); + assertEquals((byte) 4, buffer.get(0), "Unexpected buffer value at index 0"); + assertEquals((byte) 5, buffer.get(size - 1), "Unexpected buffer value at index " + (size - 1)); + assertEquals(1, buffer.position(), "Unexpected buffer position"); // Set the buffer limit to half its current size, making it less than we will // ask for the next time we borrow, ensuring it then needs to be zeroed @@ -221,7 +228,7 @@ public class ThreadLocalByteBufferPoolTest { spy = Mockito.spy(buffer); Mockito.doReturn(false).when(spy).hasArray(); - assertEquals("Unexpected buffer limit", size / 2, spy.limit()); + assertEquals(size / 2, spy.limit(), "Unexpected buffer limit"); pool.release(spy); } @@ -237,8 +244,8 @@ public class ThreadLocalByteBufferPoolTest { } // Verify position + limit, and content is zeroed - assertEquals("Unexpected buffer limit", size, buffer2.limit()); - assertEquals("Unexpected buffer position", 0, buffer2.position()); + assertEquals(size, buffer2.limit(), "Unexpected buffer limit"); + assertEquals(0, buffer2.position(), "Unexpected buffer position"); assertZeroed(buffer2); } } diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/JournalTransactionForgetTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/JournalTransactionForgetTest.java index d1a91e571d..e11da042f9 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/JournalTransactionForgetTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/JournalTransactionForgetTest.java @@ -17,7 +17,7 @@ package org.apache.activemq.artemis.core.journal.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class JournalTransactionForgetTest { diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/ObjIntIntArrayListTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/ObjIntIntArrayListTest.java index 0ccef10e03..7ad378fe41 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/ObjIntIntArrayListTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/ObjIntIntArrayListTest.java @@ -16,13 +16,17 @@ */ package org.apache.activemq.artemis.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; public class ObjIntIntArrayListTest { @@ -52,29 +56,35 @@ public class ObjIntIntArrayListTest { aList.add(a); bList.add(b); cList.add(c); - Assert.assertSame(expectedArg, arg); + assertSame(expectedArg, arg); }, expectedArg); assertEquals(expectedAList, aList); assertEquals(expectedBList, bList); assertEquals(expectedCList, cList); } - @Test(expected = NullPointerException.class) + @Test public void addShouldFailAppendNull() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.add(null, 1, 2); + assertThrows(NullPointerException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.add(null, 1, 2); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void addShouldFailAppendNegativeA() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.add(0, -1, 1); + assertThrows(IllegalArgumentException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.add(0, -1, 1); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void addShouldFailAppendNegativeB() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.add(0, 1, -1); + assertThrows(IllegalArgumentException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.add(0, 1, -1); + }); } @Test @@ -85,7 +95,7 @@ public class ObjIntIntArrayListTest { list.clear(); assertEquals(0, list.size()); list.forEach((a, b, c, ignored) -> { - Assert.fail("the list should be empty"); + fail("the list should be empty"); }, null); } @@ -94,11 +104,11 @@ public class ObjIntIntArrayListTest { ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); Integer e = 1; list.add(e, 2, 3); - Assert.assertFalse(list.addToIntsIfMatch(0, 2, 1, 1)); + assertFalse(list.addToIntsIfMatch(0, 2, 1, 1)); list.forEach((a, b, c, ignored) -> { - Assert.assertEquals(e, a); - Assert.assertEquals(2, b); - Assert.assertEquals(3, c); + assertEquals(e, a); + assertEquals(2, b); + assertEquals(3, c); }, null); } @@ -107,11 +117,11 @@ public class ObjIntIntArrayListTest { ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); Integer e = 1; list.add(e, Integer.MAX_VALUE, 3); - Assert.assertFalse(list.addToIntsIfMatch(0, e, Integer.MAX_VALUE, 1)); + assertFalse(list.addToIntsIfMatch(0, e, Integer.MAX_VALUE, 1)); list.forEach((a, b, c, ignored) -> { - Assert.assertEquals(e, a); - Assert.assertEquals(Integer.MAX_VALUE, b); - Assert.assertEquals(3, c); + assertEquals(e, a); + assertEquals(Integer.MAX_VALUE, b); + assertEquals(3, c); }, null); } @@ -120,47 +130,57 @@ public class ObjIntIntArrayListTest { ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); Integer e = 1; list.add(e, 2, Integer.MAX_VALUE); - Assert.assertFalse(list.addToIntsIfMatch(0, e, 1, Integer.MAX_VALUE)); + assertFalse(list.addToIntsIfMatch(0, e, 1, Integer.MAX_VALUE)); list.forEach((a, b, c, ignored) -> { - Assert.assertEquals(e, a); - Assert.assertEquals(2, b); - Assert.assertEquals(Integer.MAX_VALUE, c); + assertEquals(e, a); + assertEquals(2, b); + assertEquals(Integer.MAX_VALUE, c); }, null); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void updateIfMatchShouldFailOnNegativeIndex() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.addToIntsIfMatch(-1, 1, 1, 1); + assertThrows(IndexOutOfBoundsException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.addToIntsIfMatch(-1, 1, 1, 1); + }); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void updateIfMatchShouldFailBeyondSize() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.addToIntsIfMatch(0, 1, 1, 1); + assertThrows(IndexOutOfBoundsException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.addToIntsIfMatch(0, 1, 1, 1); + }); } - @Test(expected = NullPointerException.class) + @Test public void updateIfMatchShouldFailOnNull() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - list.add(1, 2, 3); - list.addToIntsIfMatch(0, null, 1, 1); + assertThrows(NullPointerException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + list.add(1, 2, 3); + list.addToIntsIfMatch(0, null, 1, 1); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void updateIfMatchShouldFailOnNegativeDeltaA() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - Integer e = 1; - list.add(1, 2, 3); - list.addToIntsIfMatch(0, e, -1, 1); + assertThrows(IllegalArgumentException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + Integer e = 1; + list.add(1, 2, 3); + list.addToIntsIfMatch(0, e, -1, 1); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void updateIfMatchShouldFailOnNegativeDeltaB() { - ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); - Integer e = 1; - list.add(e, 2, 3); - list.addToIntsIfMatch(0, e, 1, -1); + assertThrows(IllegalArgumentException.class, () -> { + ObjIntIntArrayList list = new ObjIntIntArrayList<>(0); + Integer e = 1; + list.add(e, 2, 3); + list.addToIntsIfMatch(0, e, 1, -1); + }); } @Test @@ -169,10 +189,10 @@ public class ObjIntIntArrayListTest { list.add(1, 2, 3); list.add(2, 3, 4); list.add(3, 4, 5); - Assert.assertTrue(list.addToIntsIfMatch(0, 1, 1, 1)); - Assert.assertTrue(list.addToIntsIfMatch(1, 2, 1, 1)); - Assert.assertTrue(list.addToIntsIfMatch(2, 3, 1, 1)); - Assert.assertEquals(3, list.size()); + assertTrue(list.addToIntsIfMatch(0, 1, 1, 1)); + assertTrue(list.addToIntsIfMatch(1, 2, 1, 1)); + assertTrue(list.addToIntsIfMatch(2, 3, 1, 1)); + assertEquals(3, list.size()); List eList = new ArrayList<>(); List aList = new ArrayList<>(); List bList = new ArrayList<>(); @@ -181,17 +201,17 @@ public class ObjIntIntArrayListTest { aList.add(a); bList.add(b); }, null); - Assert.assertEquals(3, eList.size()); - Assert.assertEquals(3, aList.size()); - Assert.assertEquals(3, bList.size()); + assertEquals(3, eList.size()); + assertEquals(3, aList.size()); + assertEquals(3, bList.size()); for (int i = 0; i < 3; i++) { final int index = i; final Integer expectedE = index + 1; final Integer expectedA = expectedE + 2; final Integer expectedB = expectedE + 3; - Assert.assertEquals(expectedE, eList.get(index)); - Assert.assertEquals(expectedA, aList.get(index)); - Assert.assertEquals(expectedB, bList.get(index)); + assertEquals(expectedE, eList.get(index)); + assertEquals(expectedA, aList.get(index)); + assertEquals(expectedB, bList.get(index)); } } diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/VerifyUpdateFactorSystemPropertyTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/VerifyUpdateFactorSystemPropertyTest.java index eae38b0bec..22e39942fd 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/VerifyUpdateFactorSystemPropertyTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/core/journal/impl/VerifyUpdateFactorSystemPropertyTest.java @@ -16,16 +16,17 @@ */ package org.apache.activemq.artemis.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.utils.SpawnedVMSupport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class VerifyUpdateFactorSystemPropertyTest { public static void main(String[] arg) { try { - Assert.assertEquals(33.0, JournalImpl.UPDATE_FACTOR, 0); + assertEquals(33.0, JournalImpl.UPDATE_FACTOR, 0); System.exit(0); } catch (Throwable e) { e.printStackTrace(); @@ -36,7 +37,7 @@ public class VerifyUpdateFactorSystemPropertyTest { @Test public void testValidateUpdateRecordProperty() throws Exception { Process process = SpawnedVMSupport.spawnVM(VerifyUpdateFactorSystemPropertyTest.class.getName(), new String[]{"-D" + JournalImpl.class.getName() + ".UPDATE_FACTOR=33.0"}, new String[]{}); - Assert.assertEquals(0, process.waitFor()); + assertEquals(0, process.waitFor()); } } diff --git a/artemis-journal/src/test/java/org/apache/activemq/artemis/journal/JournalLogBundlesTest.java b/artemis-journal/src/test/java/org/apache/activemq/artemis/journal/JournalLogBundlesTest.java index a33658c0cb..c010f5fa2a 100644 --- a/artemis-journal/src/test/java/org/apache/activemq/artemis/journal/JournalLogBundlesTest.java +++ b/artemis-journal/src/test/java/org/apache/activemq/artemis/journal/JournalLogBundlesTest.java @@ -16,27 +16,27 @@ */ package org.apache.activemq.artemis.journal; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.api.core.ActiveMQIOErrorException; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class JournalLogBundlesTest { private static final String LOGGER_NAME = ActiveMQJournalLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } @@ -56,8 +56,8 @@ public class JournalLogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ149000")); - assertTrue("unexpected message: " + message, message.contains(String.valueOf("oldFileNameBreadCrumb"))); - assertTrue("unexpected message: " + message, message.contains(String.valueOf("oldFileNameBreadCrumb"))); + assertTrue(message.startsWith("AMQ149000"), "unexpected message: " + message); + assertTrue(message.contains(String.valueOf("oldFileNameBreadCrumb")), "unexpected message: " + message); + assertTrue(message.contains(String.valueOf("oldFileNameBreadCrumb")), "unexpected message: " + message); } } diff --git a/artemis-lockmanager/artemis-lockmanager-ri/pom.xml b/artemis-lockmanager/artemis-lockmanager-ri/pom.xml index ca9f791986..26982bdb82 100644 --- a/artemis-lockmanager/artemis-lockmanager-ri/pom.xml +++ b/artemis-lockmanager/artemis-lockmanager-ri/pom.xml @@ -105,8 +105,13 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/DistributedLockTest.java b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/DistributedLockTest.java index 0e13198e90..632ffa372a 100644 --- a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/DistributedLockTest.java +++ b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/DistributedLockTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.lockmanager; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -26,16 +33,15 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; -import org.junit.After; -import org.junit.Assert; -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; public abstract class DistributedLockTest { private final ArrayList closeables = new ArrayList<>(); - @Before + @BeforeEach public void setupEnv() throws Throwable { } @@ -43,7 +49,7 @@ public abstract class DistributedLockTest { protected abstract String managerClassName(); - @After + @AfterEach public void tearDownEnv() throws Throwable { closeables.forEach(closeables -> { try { @@ -76,7 +82,7 @@ public abstract class DistributedLockTest { public void managerReturnsSameLockIfNotClosed() throws ExecutionException, InterruptedException, TimeoutException { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); - Assert.assertSame(manager.getDistributedLock("a"), manager.getDistributedLock("a")); + assertSame(manager.getDistributedLock("a"), manager.getDistributedLock("a")); } @Test @@ -85,7 +91,7 @@ public abstract class DistributedLockTest { manager.start(); DistributedLock closedLock = manager.getDistributedLock("a"); closedLock.close(); - Assert.assertNotSame(closedLock, manager.getDistributedLock("a")); + assertNotSame(closedLock, manager.getDistributedLock("a")); } @Test @@ -95,20 +101,24 @@ public abstract class DistributedLockTest { DistributedLock closedLock = manager.getDistributedLock("a"); manager.stop(); manager.start(); - Assert.assertNotSame(closedLock, manager.getDistributedLock("a")); + assertNotSame(closedLock, manager.getDistributedLock("a")); } - @Test(expected = IllegalStateException.class) + @Test public void managerCannotGetLockIfNotStarted() throws ExecutionException, InterruptedException, TimeoutException { - DistributedLockManager manager = createManagedDistributeManager(); - manager.getDistributedLock("a"); + assertThrows(IllegalStateException.class, () -> { + DistributedLockManager manager = createManagedDistributeManager(); + manager.getDistributedLock("a"); + }); } - @Test(expected = NullPointerException.class) + @Test public void managerCannotGetLockWithNullLockId() throws ExecutionException, InterruptedException, TimeoutException { - DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - manager.getDistributedLock(null); + assertThrows(NullPointerException.class, () -> { + DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + manager.getDistributedLock(null); + }); } @Test @@ -116,21 +126,21 @@ public abstract class DistributedLockTest { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock closedLock = manager.getDistributedLock("a"); - Assert.assertTrue(closedLock.tryLock()); + assertTrue(closedLock.tryLock()); closedLock.close(); - Assert.assertTrue(manager.getDistributedLock("a").tryLock()); + assertTrue(manager.getDistributedLock("a").tryLock()); } @Test public void managerStopUnlockLocks() throws ExecutionException, InterruptedException, TimeoutException, UnavailableStateException { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); - Assert.assertTrue(manager.getDistributedLock("a").tryLock()); - Assert.assertTrue(manager.getDistributedLock("b").tryLock()); + assertTrue(manager.getDistributedLock("a").tryLock()); + assertTrue(manager.getDistributedLock("b").tryLock()); manager.stop(); manager.start(); - Assert.assertFalse(manager.getDistributedLock("a").isHeldByCaller()); - Assert.assertFalse(manager.getDistributedLock("b").isHeldByCaller()); + assertFalse(manager.getDistributedLock("a").isHeldByCaller()); + assertFalse(manager.getDistributedLock("b").isHeldByCaller()); } @Test @@ -138,20 +148,22 @@ public abstract class DistributedLockTest { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertFalse(lock.isHeldByCaller()); - Assert.assertTrue(lock.tryLock()); - Assert.assertTrue(lock.isHeldByCaller()); + assertFalse(lock.isHeldByCaller()); + assertTrue(lock.tryLock()); + assertTrue(lock.isHeldByCaller()); lock.unlock(); - Assert.assertFalse(lock.isHeldByCaller()); + assertFalse(lock.isHeldByCaller()); } - @Test(expected = IllegalStateException.class) + @Test public void cannotAcquireSameLockTwice() throws ExecutionException, InterruptedException, TimeoutException, UnavailableStateException { - DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertTrue(lock.tryLock()); - lock.tryLock(); + assertThrows(IllegalStateException.class, () -> { + DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + DistributedLock lock = manager.getDistributedLock("a"); + assertTrue(lock.tryLock()); + lock.tryLock(); + }); } @Test @@ -160,9 +172,9 @@ public abstract class DistributedLockTest { DistributedLockManager observerManager = createManagedDistributeManager(); ownerManager.start(); observerManager.start(); - Assert.assertTrue(ownerManager.getDistributedLock("a").tryLock()); - Assert.assertTrue(ownerManager.getDistributedLock("a").isHeldByCaller()); - Assert.assertFalse(observerManager.getDistributedLock("a").isHeldByCaller()); + assertTrue(ownerManager.getDistributedLock("a").tryLock()); + assertTrue(ownerManager.getDistributedLock("a").isHeldByCaller()); + assertFalse(observerManager.getDistributedLock("a").isHeldByCaller()); } @Test @@ -171,11 +183,11 @@ public abstract class DistributedLockTest { DistributedLockManager observerManager = createManagedDistributeManager(); ownerManager.start(); observerManager.start(); - Assert.assertTrue(ownerManager.getDistributedLock("a").tryLock()); + assertTrue(ownerManager.getDistributedLock("a").tryLock()); ownerManager.getDistributedLock("a").unlock(); - Assert.assertFalse(observerManager.getDistributedLock("a").isHeldByCaller()); - Assert.assertFalse(ownerManager.getDistributedLock("a").isHeldByCaller()); - Assert.assertTrue(observerManager.getDistributedLock("a").tryLock()); + assertFalse(observerManager.getDistributedLock("a").isHeldByCaller()); + assertFalse(ownerManager.getDistributedLock("a").isHeldByCaller()); + assertTrue(observerManager.getDistributedLock("a").tryLock()); } @Test @@ -184,8 +196,8 @@ public abstract class DistributedLockTest { DistributedLockManager notOwnerManager = createManagedDistributeManager(); ownerManager.start(); notOwnerManager.start(); - Assert.assertTrue(ownerManager.getDistributedLock("a").tryLock()); - Assert.assertFalse(notOwnerManager.getDistributedLock("a").tryLock()); + assertTrue(ownerManager.getDistributedLock("a").tryLock()); + assertFalse(notOwnerManager.getDistributedLock("a").tryLock()); } @Test @@ -194,10 +206,10 @@ public abstract class DistributedLockTest { DistributedLockManager notOwnerManager = createManagedDistributeManager(); ownerManager.start(); notOwnerManager.start(); - Assert.assertTrue(ownerManager.getDistributedLock("a").tryLock()); + assertTrue(ownerManager.getDistributedLock("a").tryLock()); notOwnerManager.getDistributedLock("a").unlock(); - Assert.assertFalse(notOwnerManager.getDistributedLock("a").isHeldByCaller()); - Assert.assertTrue(ownerManager.getDistributedLock("a").isHeldByCaller()); + assertFalse(notOwnerManager.getDistributedLock("a").isHeldByCaller()); + assertTrue(ownerManager.getDistributedLock("a").isHeldByCaller()); } @Test @@ -205,7 +217,7 @@ public abstract class DistributedLockTest { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock backgroundLock = manager.getDistributedLock("a"); - Assert.assertTrue(backgroundLock.tryLock(1, TimeUnit.NANOSECONDS)); + assertTrue(backgroundLock.tryLock(1, TimeUnit.NANOSECONDS)); } @Test @@ -214,12 +226,12 @@ public abstract class DistributedLockTest { manager.start(); DistributedLockManager otherManager = createManagedDistributeManager(); otherManager.start(); - Assert.assertTrue(otherManager.getDistributedLock("a").tryLock()); + assertTrue(otherManager.getDistributedLock("a").tryLock()); final long start = System.nanoTime(); final long timeoutSec = 1; - Assert.assertFalse(manager.getDistributedLock("a").tryLock(timeoutSec, TimeUnit.SECONDS)); + assertFalse(manager.getDistributedLock("a").tryLock(timeoutSec, TimeUnit.SECONDS)); final long elapsed = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); - Assert.assertTrue(elapsed + " less than timeout of " + timeoutSec + " seconds", elapsed >= timeoutSec); + assertTrue(elapsed >= timeoutSec, elapsed + " less than timeout of " + timeoutSec + " seconds"); } @Test @@ -228,7 +240,7 @@ public abstract class DistributedLockTest { manager.start(); DistributedLockManager otherManager = createManagedDistributeManager(); otherManager.start(); - Assert.assertTrue(otherManager.getDistributedLock("a").tryLock()); + assertTrue(otherManager.getDistributedLock("a").tryLock()); DistributedLock backgroundLock = manager.getDistributedLock("a"); CompletableFuture acquired = new CompletableFuture<>(); CountDownLatch startedTry = new CountDownLatch(1); @@ -245,9 +257,9 @@ public abstract class DistributedLockTest { } }); tryLockThread.start(); - Assert.assertTrue(startedTry.await(10, TimeUnit.SECONDS)); + assertTrue(startedTry.await(10, TimeUnit.SECONDS)); otherManager.getDistributedLock("a").unlock(); - Assert.assertTrue(acquired.get(4, TimeUnit.SECONDS)); + assertTrue(acquired.get(4, TimeUnit.SECONDS)); } @Test @@ -256,7 +268,7 @@ public abstract class DistributedLockTest { manager.start(); DistributedLockManager otherManager = createManagedDistributeManager(); otherManager.start(); - Assert.assertTrue(otherManager.getDistributedLock("a").tryLock()); + assertTrue(otherManager.getDistributedLock("a").tryLock()); DistributedLock backgroundLock = manager.getDistributedLock("a"); CompletableFuture interrupted = new CompletableFuture<>(); CountDownLatch startedTry = new CountDownLatch(1); @@ -272,11 +284,11 @@ public abstract class DistributedLockTest { } }); tryLockThread.start(); - Assert.assertTrue(startedTry.await(10, TimeUnit.SECONDS)); + assertTrue(startedTry.await(10, TimeUnit.SECONDS)); // let background lock to perform some tries TimeUnit.SECONDS.sleep(1); tryLockThread.interrupt(); - Assert.assertTrue(interrupted.get(4, TimeUnit.SECONDS)); + assertTrue(interrupted.get(4, TimeUnit.SECONDS)); } @Test @@ -284,11 +296,11 @@ public abstract class DistributedLockTest { DistributedLockManager manager = createManagedDistributeManager(); manager.start(); final String id = "a"; - Assert.assertTrue(manager.getDistributedLock(id).tryLock()); - Assert.assertEquals(0, manager.getMutableLong(id).get()); + assertTrue(manager.getDistributedLock(id).tryLock()); + assertEquals(0, manager.getMutableLong(id).get()); manager.getMutableLong(id).set(1); - Assert.assertTrue(manager.getDistributedLock(id).isHeldByCaller()); - Assert.assertEquals(1, manager.getMutableLong(id).get()); + assertTrue(manager.getDistributedLock(id).isHeldByCaller()); + assertEquals(1, manager.getMutableLong(id).get()); } } diff --git a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/file/FileDistributedLockTest.java b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/file/FileDistributedLockTest.java index 953b028c97..bcddde5515 100644 --- a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/file/FileDistributedLockTest.java +++ b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/file/FileDistributedLockTest.java @@ -16,29 +16,33 @@ */ package org.apache.activemq.artemis.lockmanager.file; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Map; import org.apache.activemq.artemis.lockmanager.DistributedLockTest; import org.apache.activemq.artemis.lockmanager.DistributedLockManager; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class FileDistributedLockTest extends DistributedLockTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File tmpFolder; private File locksFolder; - @Before + @BeforeEach @Override public void setupEnv() throws Throwable { - locksFolder = tmpFolder.newFolder("locks-folder"); + locksFolder = newFolder(tmpFolder, "locks-folder"); super.setupEnv(); } @@ -57,14 +61,26 @@ public class FileDistributedLockTest extends DistributedLockTest { DistributedLockManager.newInstanceOf(managerClassName(), Collections.singletonMap("locks-folder", locksFolder.toString())); } - @Test(expected = InvocationTargetException.class) + @Test public void reflectiveManagerCreationFailWithoutLocksFolder() throws Exception { - DistributedLockManager.newInstanceOf(managerClassName(), Collections.emptyMap()); + assertThrows(InvocationTargetException.class, () -> { + DistributedLockManager.newInstanceOf(managerClassName(), Collections.emptyMap()); + }); } - @Test(expected = InvocationTargetException.class) + @Test public void reflectiveManagerCreationFailIfLocksFolderIsNotFolder() throws Exception { - DistributedLockManager.newInstanceOf(managerClassName(), Collections.singletonMap("locks-folder", tmpFolder.newFile().toString())); + assertThrows(InvocationTargetException.class, () -> { + DistributedLockManager.newInstanceOf(managerClassName(), Collections.singletonMap("locks-folder", File.createTempFile("junit", null, tmpFolder).toString())); + }); + } + + private static File newFolder(File root, String subFolder) throws IOException { + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; } } diff --git a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockManagerTest.java b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockManagerTest.java index 1b7070fc4a..fc40ea7059 100644 --- a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockManagerTest.java +++ b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockManagerTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.lockmanager.zookeeper; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -24,6 +28,8 @@ import java.util.Map; import java.util.function.Consumer; import org.apache.activemq.artemis.lockmanager.DistributedLockManager; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; +import org.apache.activemq.artemis.tests.util.ArtemisTestCase; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; @@ -31,14 +37,12 @@ import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class CuratorDistributedLockManagerTest { +public class CuratorDistributedLockManagerTest extends ArtemisTestCase { private final ArrayList autoCloseables = new ArrayList<>(); @@ -51,24 +55,25 @@ public class CuratorDistributedLockManagerTest { private static final int RETRIES = 1; public int nodes = 1; - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); private TestingCluster testingServer; private String connectString; + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File tmpFolder; - @Before + @BeforeEach public void setupEnv() throws Throwable { InstanceSpec[] clusterSpecs = new InstanceSpec[nodes]; for (int i = 0; i < nodes; i++) { - clusterSpecs[i] = new InstanceSpec(tmpFolder.newFolder(), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); + clusterSpecs[i] = new InstanceSpec(newFolder(tmpFolder, getTestMethodName() + "_node" + i), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); } testingServer = new TestingCluster(clusterSpecs); testingServer.start(); connectString = testingServer.getConnectString(); } - @After + @AfterEach public void tearDownEnv() throws Throwable { autoCloseables.forEach(closeables -> { try { @@ -110,15 +115,15 @@ public class CuratorDistributedLockManagerTest { public void verifyLayoutInZK() throws Exception { final DistributedLockManager manager = createManagedDistributeManager(config -> config.put("namespace", "activemq-artemis")); manager.start(); - Assert.assertTrue(manager.getDistributedLock("journal-identity-000-111").tryLock()); + assertTrue(manager.getDistributedLock("journal-identity-000-111").tryLock()); - Assert.assertTrue(manager.getMutableLong("journal-identity-000-111").compareAndSet(0, 1)); + assertTrue(manager.getMutableLong("journal-identity-000-111").compareAndSet(0, 1)); CuratorFramework curatorFramework = ((CuratorDistributedLockManager)manager).getCurator(); List entries = new LinkedList<>(); dumpZK(curatorFramework.getZookeeperClient().getZooKeeper(), "/", entries); - Assert.assertTrue(entries.get(2).contains("activation-sequence")); + assertTrue(entries.get(2).contains("activation-sequence")); for (String entry: entries) { System.err.println("ZK: " + entry); @@ -137,4 +142,12 @@ public class CuratorDistributedLockManagerTest { } } } + + private static File newFolder(File root, String subFolder) throws IOException { + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockTest.java b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockTest.java index 316d045353..1d219bf5f2 100644 --- a/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockTest.java +++ b/artemis-lockmanager/artemis-lockmanager-ri/src/test/java/org/apache/activemq/artemis/lockmanager/zookeeper/CuratorDistributedLockTest.java @@ -16,8 +16,15 @@ */ package org.apache.activemq.artemis.lockmanager.zookeeper; +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.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.File; import java.io.IOException; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -30,26 +37,23 @@ import java.util.concurrent.atomic.AtomicReference; import org.apache.activemq.artemis.lockmanager.DistributedLock; import org.apache.activemq.artemis.lockmanager.DistributedLockManager; +import org.apache.activemq.artemis.lockmanager.DistributedLockTest; import org.apache.activemq.artemis.lockmanager.UnavailableStateException; +import org.apache.activemq.artemis.tests.extensions.TargetTempDirFactory; import org.apache.activemq.artemis.utils.Wait; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; - -import org.apache.activemq.artemis.lockmanager.DistributedLockTest; import org.apache.curator.test.TestingZooKeeperServer; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import static java.lang.Boolean.TRUE; - -@RunWith(value = Parameterized.class) public class CuratorDistributedLockTest extends DistributedLockTest { + // fast-tests runs dont need to run 3 ZK nodes + private static final int ZK_NODES = Boolean.getBoolean("fast-tests") ? 1 : 3; + private static final int BASE_SERVER_PORT = 6666; private static final int CONNECTION_MS = 2000; // Beware: the server tick must be small enough that to let the session to be correctly expired @@ -58,26 +62,23 @@ public class CuratorDistributedLockTest extends DistributedLockTest { private static final int RETRIES_MS = 100; private static final int RETRIES = 1; - // fast-tests runs doesn't need to run 3 ZK nodes - private static final int ZK_NODES = Boolean.getBoolean("fast-tests") ? 1 : 3; - @Parameterized.Parameter public int zkNodes; - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); private TestingCluster testingServer; private InstanceSpec[] clusterSpecs; private String connectString; - @Parameterized.Parameters(name = "nodes={0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][]{{ZK_NODES}}); - } + // Temp folder at ./target/tmp// + @TempDir(factory = TargetTempDirFactory.class) + public File tmpFolder; + @BeforeEach @Override public void setupEnv() throws Throwable { + zkNodes = ZK_NODES; // The number of nodes to use, based on test profile. + clusterSpecs = new InstanceSpec[zkNodes]; for (int i = 0; i < zkNodes; i++) { - clusterSpecs[i] = new InstanceSpec(tmpFolder.newFolder(), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); + clusterSpecs[i] = new InstanceSpec(newFolder(tmpFolder, "node" + i), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); } testingServer = new TestingCluster(clusterSpecs); testingServer.start(); @@ -85,6 +86,7 @@ public class CuratorDistributedLockTest extends DistributedLockTest { super.setupEnv(); } + @AfterEach @Override public void tearDownEnv() throws Throwable { super.tearDownEnv(); @@ -105,9 +107,11 @@ public class CuratorDistributedLockTest extends DistributedLockTest { return CuratorDistributedLockManager.class.getName(); } - @Test(expected = RuntimeException.class) + @Test public void cannotCreateManagerWithNotValidParameterNames() { - final DistributedLockManager manager = createManagedDistributeManager(config -> config.put("_", "_")); + assertThrows(RuntimeException.class, () -> { + final DistributedLockManager manager = createManagedDistributeManager(config -> config.put("_", "_")); + }); } @Test @@ -116,78 +120,85 @@ public class CuratorDistributedLockTest extends DistributedLockTest { manager1.start(); final DistributedLockManager manager2 = createManagedDistributeManager(config -> config.put("namespace", "2")); manager2.start(); - Assert.assertTrue(manager1.getDistributedLock("a").tryLock()); - Assert.assertTrue(manager2.getDistributedLock("a").tryLock()); + assertTrue(manager1.getDistributedLock("a").tryLock()); + assertTrue(manager2.getDistributedLock("a").tryLock()); } @Test public void cannotStartManagerWithDisconnectedServer() throws IOException, ExecutionException, InterruptedException { final DistributedLockManager manager = createManagedDistributeManager(); testingServer.close(); - Assert.assertFalse(manager.start(1, TimeUnit.SECONDS)); + assertFalse(manager.start(1, TimeUnit.SECONDS)); } - @Test(expected = UnavailableStateException.class) + @Test public void cannotAcquireLockWithDisconnectedServer() throws IOException, ExecutionException, InterruptedException, TimeoutException, UnavailableStateException { - final DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - final DistributedLock lock = manager.getDistributedLock("a"); - final CountDownLatch notAvailable = new CountDownLatch(1); - final DistributedLock.UnavailableLockListener listener = notAvailable::countDown; - lock.addListener(listener); - testingServer.close(); - Assert.assertTrue(notAvailable.await(30, TimeUnit.SECONDS)); - lock.tryLock(); + assertThrows(UnavailableStateException.class, () -> { + final DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + final DistributedLock lock = manager.getDistributedLock("a"); + final CountDownLatch notAvailable = new CountDownLatch(1); + final DistributedLock.UnavailableLockListener listener = notAvailable::countDown; + lock.addListener(listener); + testingServer.close(); + assertTrue(notAvailable.await(30, TimeUnit.SECONDS)); + lock.tryLock(); + }); } - @Test(expected = UnavailableStateException.class) + @Test public void cannotTryLockWithDisconnectedServer() throws IOException, ExecutionException, InterruptedException, TimeoutException, UnavailableStateException { - final DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - final DistributedLock lock = manager.getDistributedLock("a"); - testingServer.close(); - lock.tryLock(); + assertThrows(UnavailableStateException.class, () -> { + final DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + final DistributedLock lock = manager.getDistributedLock("a"); + testingServer.close(); + lock.tryLock(); + }); } - @Test(expected = UnavailableStateException.class) + @Test public void cannotCheckLockStatusWithDisconnectedServer() throws IOException, ExecutionException, InterruptedException, TimeoutException, UnavailableStateException { - final DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - final DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertFalse(lock.isHeldByCaller()); - Assert.assertTrue(lock.tryLock()); - testingServer.close(); - lock.isHeldByCaller(); + assertThrows(UnavailableStateException.class, () -> { + final DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + final DistributedLock lock = manager.getDistributedLock("a"); + assertFalse(lock.isHeldByCaller()); + assertTrue(lock.tryLock()); + testingServer.close(); + lock.isHeldByCaller(); + }); } - @Test(expected = UnavailableStateException.class) public void looseLockAfterServerStop() throws ExecutionException, InterruptedException, TimeoutException, UnavailableStateException, IOException { - final DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - final DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertTrue(lock.tryLock()); - Assert.assertTrue(lock.isHeldByCaller()); - final CountDownLatch notAvailable = new CountDownLatch(1); - final DistributedLock.UnavailableLockListener listener = notAvailable::countDown; - lock.addListener(listener); - Assert.assertEquals(1, notAvailable.getCount()); - testingServer.close(); - Assert.assertTrue(notAvailable.await(30, TimeUnit.SECONDS)); - lock.isHeldByCaller(); + assertThrows(UnavailableStateException.class, () -> { + final DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + final DistributedLock lock = manager.getDistributedLock("a"); + assertTrue(lock.tryLock()); + assertTrue(lock.isHeldByCaller()); + final CountDownLatch notAvailable = new CountDownLatch(1); + final DistributedLock.UnavailableLockListener listener = notAvailable::countDown; + lock.addListener(listener); + assertEquals(1, notAvailable.getCount()); + testingServer.close(); + assertTrue(notAvailable.await(30, TimeUnit.SECONDS)); + lock.isHeldByCaller(); + }); } @Test public void canAcquireLockOnMajorityRestart() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); final DistributedLockManager manager = createManagedDistributeManager(); manager.start(); final DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertTrue(lock.tryLock()); - Assert.assertTrue(lock.isHeldByCaller()); + assertTrue(lock.tryLock()); + assertTrue(lock.isHeldByCaller()); final CountDownLatch notAvailable = new CountDownLatch(1); final DistributedLock.UnavailableLockListener listener = notAvailable::countDown; lock.addListener(listener); - Assert.assertEquals(1, notAvailable.getCount()); + assertEquals(1, notAvailable.getCount()); testingServer.stop(); notAvailable.await(); manager.stop(); @@ -196,31 +207,33 @@ public class CuratorDistributedLockTest extends DistributedLockTest { otherManager.start(); // await more then the expected value, that depends by how curator session expiration is configured TimeUnit.MILLISECONDS.sleep(SESSION_MS + SERVER_TICK_MS); - Assert.assertTrue(otherManager.getDistributedLock("a").tryLock()); + assertTrue(otherManager.getDistributedLock("a").tryLock()); } @Test public void cannotStartManagerWithoutQuorum() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); stopMajority(true); - Assert.assertFalse(manager.start(2, TimeUnit.SECONDS)); - Assert.assertFalse(manager.isStarted()); + assertFalse(manager.start(2, TimeUnit.SECONDS)); + assertFalse(manager.isStarted()); } - @Test(expected = UnavailableStateException.class) + @Test public void cannotAcquireLockWithoutQuorum() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); - DistributedLockManager manager = createManagedDistributeManager(); - manager.start(); - stopMajority(true); - DistributedLock lock = manager.getDistributedLock("a"); - lock.tryLock(); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); + assertThrows(UnavailableStateException.class, () -> { + DistributedLockManager manager = createManagedDistributeManager(); + manager.start(); + stopMajority(true); + DistributedLock lock = manager.getDistributedLock("a"); + lock.tryLock(); + }); } @Test public void cannotCheckLockWithoutQuorum() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); stopMajority(true); @@ -231,34 +244,34 @@ public class CuratorDistributedLockTest extends DistributedLockTest { } catch (UnavailableStateException expected) { return; } - Assert.assertFalse(held); + assertFalse(held); } @Test public void canGetLockWithoutQuorum() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); stopMajority(true); DistributedLock lock = manager.getDistributedLock("a"); - Assert.assertNotNull(lock); + assertNotNull(lock); } @Test public void notifiedAsUnavailableWhileLoosingQuorum() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock lock = manager.getDistributedLock("a"); CountDownLatch unavailable = new CountDownLatch(1); lock.addListener(unavailable::countDown); stopMajority(true); - Assert.assertTrue(unavailable.await(SESSION_MS + SERVER_TICK_MS, TimeUnit.MILLISECONDS)); + assertTrue(unavailable.await(SESSION_MS + SERVER_TICK_MS, TimeUnit.MILLISECONDS)); } @Test public void beNotifiedOnce() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock lock = manager.getDistributedLock("a"); @@ -268,13 +281,13 @@ public class CuratorDistributedLockTest extends DistributedLockTest { lock.addListener(unavailableLock::incrementAndGet); stopMajority(true); TimeUnit.MILLISECONDS.sleep(SESSION_MS + SERVER_TICK_MS + CONNECTION_MS); - Assert.assertEquals(1, unavailableLock.get()); - Assert.assertEquals(1, unavailableManager.get()); + assertEquals(1, unavailableLock.get()); + assertEquals(1, unavailableManager.get()); } @Test public void beNotifiedOfUnavailabilityWhileBlockedOnTimedLock() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); DistributedLock lock = manager.getDistributedLock("a"); @@ -284,7 +297,7 @@ public class CuratorDistributedLockTest extends DistributedLockTest { lock.addListener(unavailableLock::incrementAndGet); final DistributedLockManager otherManager = createManagedDistributeManager(); otherManager.start(); - Assert.assertTrue(otherManager.getDistributedLock("a").tryLock()); + assertTrue(otherManager.getDistributedLock("a").tryLock()); final CountDownLatch startedTimedLock = new CountDownLatch(1); final AtomicReference unavailableTimedLock = new AtomicReference<>(null); Thread timedLock = new Thread(() -> { @@ -299,18 +312,20 @@ public class CuratorDistributedLockTest extends DistributedLockTest { } }); timedLock.start(); - Assert.assertTrue(startedTimedLock.await(10, TimeUnit.SECONDS)); + assertTrue(startedTimedLock.await(10, TimeUnit.SECONDS)); TimeUnit.SECONDS.sleep(1); stopMajority(true); TimeUnit.MILLISECONDS.sleep(SESSION_MS + CONNECTION_MS); Wait.waitFor(() -> unavailableLock.get() > 0, SERVER_TICK_MS); - Assert.assertEquals(1, unavailableManager.get()); - Assert.assertEquals(TRUE, unavailableTimedLock.get()); + assertEquals(1, unavailableManager.get()); + Boolean result = unavailableTimedLock.get(); + assertNotNull(result); + assertTrue(result); } @Test public void beNotifiedOfAlreadyUnavailableManagerAfterAddingListener() throws Exception { - Assume.assumeTrue(zkNodes + " <= 1", zkNodes > 1); + assumeTrue(zkNodes > 1, zkNodes + " <= 1"); DistributedLockManager manager = createManagedDistributeManager(); manager.start(); final AtomicBoolean unavailable = new AtomicBoolean(false); @@ -318,17 +333,17 @@ public class CuratorDistributedLockTest extends DistributedLockTest { unavailable.set(true); }; manager.addUnavailableManagerListener(managerListener); - Assert.assertFalse(unavailable.get()); + assertFalse(unavailable.get()); stopMajority(true); Wait.waitFor(unavailable::get); manager.removeUnavailableManagerListener(managerListener); final AtomicInteger unavailableOnRegister = new AtomicInteger(); manager.addUnavailableManagerListener(unavailableOnRegister::incrementAndGet); - Assert.assertEquals(1, unavailableOnRegister.get()); + assertEquals(1, unavailableOnRegister.get()); unavailableOnRegister.set(0); try (DistributedLock lock = manager.getDistributedLock("a")) { lock.addListener(unavailableOnRegister::incrementAndGet); - Assert.assertEquals(1, unavailableOnRegister.get()); + assertEquals(1, unavailableOnRegister.get()); } } @@ -350,4 +365,12 @@ public class CuratorDistributedLockTest extends DistributedLockTest { } } } + + private static File newFolder(File root, String subFolder) throws IOException { + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/artemis-log-annotation-processor/pom.xml b/artemis-log-annotation-processor/pom.xml index 2d0f1456de..5424807d7f 100644 --- a/artemis-log-annotation-processor/pom.xml +++ b/artemis-log-annotation-processor/pom.xml @@ -49,10 +49,14 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test - diff --git a/artemis-log-annotation-processor/src/test/java/org/apache/activemq/artemis/logs/annotation/processor/SimpleBundleTest.java b/artemis-log-annotation-processor/src/test/java/org/apache/activemq/artemis/logs/annotation/processor/SimpleBundleTest.java index e46d4b56c2..351df4d9fe 100644 --- a/artemis-log-annotation-processor/src/test/java/org/apache/activemq/artemis/logs/annotation/processor/SimpleBundleTest.java +++ b/artemis-log-annotation-processor/src/test/java/org/apache/activemq/artemis/logs/annotation/processor/SimpleBundleTest.java @@ -16,42 +16,47 @@ */ package org.apache.activemq.artemis.logs.annotation.processor; +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 java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.UUID; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; public class SimpleBundleTest { @Test public void testSimple() { - Assert.assertEquals("TST1: Test", SimpleBundle.MESSAGES.simpleTest()); + assertEquals("TST1: Test", SimpleBundle.MESSAGES.simpleTest()); System.out.println(SimpleBundle.MESSAGES.simpleTest()); } @Test public void testParameters() { - Assert.assertEquals("TST2: V1-bb", SimpleBundle.MESSAGES.parameters(1, "bb")); + assertEquals("TST2: V1-bb", SimpleBundle.MESSAGES.parameters(1, "bb")); } @Test public void testException() { Exception ex = SimpleBundle.MESSAGES.someException(); - Assert.assertEquals("TST3: EX", ex.getMessage()); + assertEquals("TST3: EX", ex.getMessage()); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); ex.printStackTrace(writer); - Assert.assertEquals("The method name (someException) should not be part of the stack trace", -1, stringWriter.toString().lastIndexOf("someException")); + assertEquals(-1, stringWriter.toString().lastIndexOf("someException"), "The method name (someException) should not be part of the stack trace"); } @Test public void testSomeExceptionParameter() { String uuid = UUID.randomUUID().toString(); - Assert.assertEquals(new Exception("TST4: EX-" + uuid).toString(), SimpleBundle.MESSAGES.someExceptionParameter(uuid).toString()); + assertEquals(new Exception("TST4: EX-" + uuid).toString(), SimpleBundle.MESSAGES.someExceptionParameter(uuid).toString()); } @Test @@ -73,20 +78,20 @@ public class SimpleBundleTest { Exception myCause = new Exception("this is myCause"); String logRandomString = "" + System.currentTimeMillis(); MyException myException = SimpleBundle.MESSAGES.someExceptionWithCause(logRandomString, myCause); - Assert.assertEquals("TST8: EX" + logRandomString, myException.getMessage()); - Assert.assertSame(myCause, myException.getCause()); + assertEquals("TST8: EX" + logRandomString, myException.getMessage()); + assertSame(myCause, myException.getCause()); } @Test public void testABCD() { System.out.println(SimpleBundle.MESSAGES.abcd("A", "B", "C", "D")); - Assert.assertEquals("TST9: A B C D", SimpleBundle.MESSAGES.abcd("A", "B", "C", "D")); + assertEquals("TST9: A B C D", SimpleBundle.MESSAGES.abcd("A", "B", "C", "D")); } @Test public void testObjectsABCD() { System.out.println(SimpleBundle.MESSAGES.abcd("A", "B", "C", "D")); - Assert.assertEquals("TST10: A B C D", SimpleBundle.MESSAGES.objectsAbcd(new MyObject("A"), new MyObject("B"), new MyObject("C"), new MyObject("D"))); + assertEquals("TST10: A B C D", SimpleBundle.MESSAGES.objectsAbcd(new MyObject("A"), new MyObject("B"), new MyObject("C"), new MyObject("D"))); } @@ -100,12 +105,12 @@ public class SimpleBundleTest { public void longList() throws Exception { try (AssertionLoggerHandler logHandler = new AssertionLoggerHandler()) { SimpleBundle.MESSAGES.longParameters("1", "2", "3", "4", "5"); - Assert.assertTrue("parameter not found", logHandler.findText("p1")); - Assert.assertTrue("parameter not found", logHandler.findText("p2")); - Assert.assertTrue("parameter not found", logHandler.findText("p3")); - Assert.assertTrue("parameter not found", logHandler.findText("p4")); - Assert.assertTrue("parameter not found", logHandler.findText("p5")); - Assert.assertFalse("{}", logHandler.findText("{}")); + assertTrue(logHandler.findText("p1"), "parameter not found"); + assertTrue(logHandler.findText("p2"), "parameter not found"); + assertTrue(logHandler.findText("p3"), "parameter not found"); + assertTrue(logHandler.findText("p4"), "parameter not found"); + assertTrue(logHandler.findText("p5"), "parameter not found"); + assertFalse(logHandler.findText("{}"), "{}"); } } @@ -115,15 +120,15 @@ public class SimpleBundleTest { try (AssertionLoggerHandler logHandler = new AssertionLoggerHandler()) { SimpleBundle.MESSAGES.onlyException(createMyExceptionBreadcrumbMethod("MSG7777")); - Assert.assertTrue(logHandler.findText("TST14")); - Assert.assertFalse(logHandler.findText("MSG7777")); + assertTrue(logHandler.findText("TST14")); + assertFalse(logHandler.findText("MSG7777")); } try (AssertionLoggerHandler logHandler = new AssertionLoggerHandler(true)) { SimpleBundle.MESSAGES.onlyException(createMyExceptionBreadcrumbMethod("MSG7777")); - Assert.assertTrue(logHandler.findText("TST14")); - Assert.assertTrue(logHandler.findTrace("MSG7777")); - Assert.assertTrue(logHandler.findTrace("createMyExceptionBreadcrumbMethod")); + assertTrue(logHandler.findText("TST14")); + assertTrue(logHandler.findTrace("MSG7777")); + assertTrue(logHandler.findTrace("createMyExceptionBreadcrumbMethod")); } } @@ -136,6 +141,6 @@ public class SimpleBundleTest { @Test public void testGetLogger() { - Assert.assertNotNull(SimpleBundle.MESSAGES.getLogger()); + assertNotNull(SimpleBundle.MESSAGES.getLogger()); } } diff --git a/artemis-maven-plugin/pom.xml b/artemis-maven-plugin/pom.xml index d4927ae084..32cbd45b6f 100644 --- a/artemis-maven-plugin/pom.xml +++ b/artemis-maven-plugin/pom.xml @@ -43,6 +43,12 @@ org.apache.maven maven-project 2.2.1 + + + junit + junit + + org.apache.maven.resolver diff --git a/artemis-pom/pom.xml b/artemis-pom/pom.xml index 6a2db5ecf5..4b716463b4 100644 --- a/artemis-pom/pom.xml +++ b/artemis-pom/pom.xml @@ -43,26 +43,11 @@ - org.junit.jupiter - junit-jupiter-api - ${junit5.version} - - - - - - org.junit.jupiter - junit-jupiter-engine - ${junit5.version} - test - - - - - - org.junit.vintage - junit-vintage-engine + org.junit + junit-bom ${junit5.version} + pom + import @@ -140,6 +125,13 @@ test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + org.apache.hadoop diff --git a/artemis-protocols/artemis-amqp-protocol/pom.xml b/artemis-protocols/artemis-amqp-protocol/pom.xml index be83844b7e..4ecc6a3253 100644 --- a/artemis-protocols/artemis-amqp-protocol/pom.xml +++ b/artemis-protocols/artemis-amqp-protocol/pom.xml @@ -76,8 +76,13 @@ proton-j - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test @@ -101,6 +106,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + org.apache.activemq artemis-unit-test-support diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPConnectionCallbackTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPConnectionCallbackTest.java index 8f0f34756b..0cf0dcb49c 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPConnectionCallbackTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPConnectionCallbackTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.protocol.amqp.broker; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.ActiveMQSecurityException; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnection; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnection; @@ -27,15 +33,9 @@ import org.apache.activemq.artemis.protocol.amqp.sasl.GSSAPIServerSASL; import org.apache.activemq.artemis.protocol.amqp.sasl.PlainSASL; import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - public class AMQPConnectionCallbackTest { @Test @@ -47,7 +47,7 @@ public class AMQPConnectionCallbackTest { for (String mech: connectionCallback.getSaslMechanisms()) { assertNotNull(connectionCallback.getServerSASL(mech)); } - assertNull("can't get mechanism not in the list", connectionCallback.getServerSASL(GSSAPIServerSASL.NAME)); + assertNull(connectionCallback.getServerSASL(GSSAPIServerSASL.NAME), "can't get mechanism not in the list"); } @Test @@ -55,7 +55,7 @@ public class AMQPConnectionCallbackTest { ProtonProtocolManager protonProtocolManager = new ProtonProtocolManager(new ProtonProtocolManagerFactory(), null, null, null); protonProtocolManager.setSaslMechanisms(new String[]{}); AMQPConnectionCallback connectionCallback = new AMQPConnectionCallback(protonProtocolManager, null, null, new ActiveMQServerImpl()); - assertNotNull("can get anon with empty list", connectionCallback.getServerSASL(AnonymousServerSASL.NAME)); + assertNotNull(connectionCallback.getServerSASL(AnonymousServerSASL.NAME), "can get anon with empty list"); } @Test diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessageTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessageTest.java index b08646af7a..aceae67b25 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessageTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessageTest.java @@ -16,15 +16,15 @@ */ package org.apache.activemq.artemis.protocol.amqp.broker; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -82,9 +82,8 @@ import org.apache.qpid.proton.codec.ReadableBuffer; import org.apache.qpid.proton.codec.WritableBuffer; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import io.netty.buffer.ByteBuf; @@ -124,7 +123,7 @@ public class AMQPMessageTest { AMQPDefinedTypes.registerAllTypes(decoder, encoder); } - @Before + @BeforeEach public void setUp() { encodedProtonMessage = encodeMessage(createProtonMessage()); } @@ -150,7 +149,9 @@ public class AMQPMessageTest { public void testCreateMessageFromEncodedReadableBuffer() { AMQPStandardMessage decoded = new AMQPStandardMessage(0, ReadableBuffer.ByteBufferReader.wrap(encodedProtonMessage), null, null); - assertEquals(true, decoded.getHeader().getDurable()); + Boolean durable = decoded.getHeader().getDurable(); + assertNotNull(durable); + assertTrue(durable); assertEquals(TEST_TO_ADDRESS, decoded.getAddress()); } @@ -158,7 +159,9 @@ public class AMQPMessageTest { public void testCreateMessageFromEncodedByteArrayDataWithExtraProperties() { AMQPStandardMessage decoded = new AMQPStandardMessage(0, encodedProtonMessage, new TypedProperties(), null); - assertEquals(true, decoded.getHeader().getDurable()); + Boolean durable = decoded.getHeader().getDurable(); + assertNotNull(durable); + assertTrue(durable); assertEquals(TEST_TO_ADDRESS, decoded.getAddress()); assertNotNull(decoded.getExtraProperties()); } @@ -183,7 +186,9 @@ public class AMQPMessageTest { assertEquals(persistedSize, message.getPersistSize()); assertEquals(persistedSize - Integer.BYTES, message.getPersistentSize()); assertEquals(persistedSize - Integer.BYTES, message.getEncodeSize()); - assertEquals(true, message.getHeader().getDurable()); + Boolean durable = message.getHeader().getDurable(); + assertNotNull(durable); + assertTrue(durable); assertEquals(TEST_TO_ADDRESS, message.getAddress()); } @@ -202,20 +207,20 @@ public class AMQPMessageTest { } catch (NullPointerException npe) { } - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); // Now reload from encoded data message.reloadPersistence(encoded, null); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); assertTrue(message.hasScheduledDeliveryTime()); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); message.getHeader(); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); assertTrue(message.hasScheduledDeliveryTime()); } @@ -235,20 +240,20 @@ public class AMQPMessageTest { } catch (NullPointerException npe) { } - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); // Now reload from encoded data message.reloadPersistence(encoded, null); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); assertTrue(message.hasScheduledDeliveryTime()); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); message.getHeader(); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); assertTrue(message.hasScheduledDeliveryTime()); } @@ -265,20 +270,20 @@ public class AMQPMessageTest { } catch (NullPointerException npe) { } - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.NOT_SCANNED, message.getDataScanningStatus()); // Now reload from encoded data message.reloadPersistence(encoded, null); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); assertFalse(message.hasScheduledDeliveryTime()); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.RELOAD_PERSISTENCE, message.getDataScanningStatus()); message.getHeader(); - Assert.assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); + assertEquals(AMQPMessage.MessageDataScanningStatus.SCANNED, message.getDataScanningStatus()); assertFalse(message.hasScheduledDeliveryTime()); } @@ -344,10 +349,10 @@ public class AMQPMessageTest { latchAlign.countDown(); go.await(); - Assert.assertNotNull(decoded.getHeader()); + assertNotNull(decoded.getHeader()); // this is a method used by Core Converter decoded.getProtonMessage(); - Assert.assertNotNull(decoded.getHeader()); + assertNotNull(decoded.getHeader()); } catch (Throwable e) { e.printStackTrace(); @@ -361,15 +366,15 @@ public class AMQPMessageTest { threads[i].start(); } - Assert.assertTrue(latchAlign.await(10, TimeUnit.SECONDS)); + assertTrue(latchAlign.await(10, TimeUnit.SECONDS)); go.countDown(); for (Thread thread : threads) { thread.join(5000); - Assert.assertFalse(thread.isAlive()); + assertFalse(thread.isAlive()); } - Assert.assertEquals(0, failures.get()); + assertEquals(0, failures.get()); } } @@ -379,7 +384,7 @@ public class AMQPMessageTest { MessageImpl protonMessage = (MessageImpl) Message.Factory.create(); AMQPStandardMessage decoded = encodeAndDecodeMessage(protonMessage); - assertEquals(null, decoded.getConnectionID()); + assertNull(decoded.getConnectionID()); } @Test @@ -389,7 +394,7 @@ public class AMQPMessageTest { final String ID = UUID.randomUUID().toString(); - assertEquals(null, decoded.getConnectionID()); + assertNull(decoded.getConnectionID()); decoded.setConnectionID(ID); assertEquals(ID, decoded.getConnectionID()); } @@ -401,7 +406,7 @@ public class AMQPMessageTest { final String ID = UUID.randomUUID().toString(); - assertEquals(null, decoded.getConnectionID()); + assertNull(decoded.getConnectionID()); decoded.setConnectionID(ID); assertEquals(ID, decoded.getConnectionID()); assertEquals(ID, decoded.getStringProperty(MessageUtil.CONNECTION_ID_PROPERTY_NAME)); @@ -508,7 +513,7 @@ public class AMQPMessageTest { MessageImpl protonMessage = (MessageImpl) Message.Factory.create(); AMQPStandardMessage decoded = encodeAndDecodeMessage(protonMessage); - assertEquals(null, decoded.getDuplicateProperty()); + assertNull(decoded.getDuplicateProperty()); } //----- Test the getAddress methods ---------------------------------------// @@ -887,8 +892,8 @@ public class AMQPMessageTest { decoded.setReplyTo(null); decoded.reencode(); - assertEquals(null, decoded.getReplyTo()); - assertEquals(null, decoded.getProperties().getReplyTo()); + assertNull(decoded.getReplyTo()); + assertNull(decoded.getProperties().getReplyTo()); } //----- Test access to User ID --------------------------------------------// @@ -1610,15 +1615,15 @@ public class AMQPMessageTest { decoded.putExtraBytesProperty(name, original); ICoreMessage coreMessage = decoded.toCore(); - Assert.assertEquals(original, coreMessage.getBytesProperty(name)); + assertEquals(original, coreMessage.getBytesProperty(name)); ActiveMQBuffer buffer = ActiveMQBuffers.pooledBuffer(10 * 1024); try { decoded.getPersister().encode(buffer, decoded); - Assert.assertEquals(AMQPMessagePersisterV3.getInstance().getID(), buffer.readByte()); // the journal reader will read 1 byte to find the persister + assertEquals(AMQPMessagePersisterV3.getInstance().getID(), buffer.readByte()); // the journal reader will read 1 byte to find the persister AMQPStandardMessage readMessage = (AMQPStandardMessage)decoded.getPersister().decode(buffer, null, null); - Assert.assertEquals(33, readMessage.getMessageID()); - Assert.assertEquals("someAddress", readMessage.getAddress()); + assertEquals(33, readMessage.getMessageID()); + assertEquals("someAddress", readMessage.getAddress()); assertArrayEquals(original, readMessage.getExtraBytesProperty(name)); } finally { buffer.release(); @@ -1627,8 +1632,8 @@ public class AMQPMessageTest { { ICoreMessage embeddedMessage = EmbedMessageUtil.embedAsCoreMessage(decoded); AMQPStandardMessage readMessage = (AMQPStandardMessage) EmbedMessageUtil.extractEmbedded(embeddedMessage, null); - Assert.assertEquals(33, readMessage.getMessageID()); - Assert.assertEquals("someAddress", readMessage.getAddress()); + assertEquals(33, readMessage.getMessageID()); + assertEquals("someAddress", readMessage.getAddress()); assertArrayEquals(original, readMessage.getExtraBytesProperty(name)); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPPersisterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPPersisterTest.java index aa630b15b0..c2af7859ef 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPPersisterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPPersisterTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.protocol.amqp.broker; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; @@ -38,8 +40,7 @@ import org.apache.qpid.proton.amqp.messaging.Header; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.amqp.messaging.Properties; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AMQPPersisterTest { @@ -98,7 +99,7 @@ public class AMQPPersisterTest { ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024); persister.encode(buffer, message); - Assert.assertEquals(persister.getEncodeSize(message), buffer.writerIndex()); + assertEquals(persister.getEncodeSize(message), buffer.writerIndex()); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPSessionCallbackTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPSessionCallbackTest.java index 244a65baaf..439fe488da 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPSessionCallbackTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPSessionCallbackTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.protocol.amqp.broker; +import static org.apache.activemq.artemis.protocol.amqp.proton.AmqpSupport.AMQP_CREDITS_DEFAULT; +import static org.apache.activemq.artemis.protocol.amqp.proton.AmqpSupport.AMQP_LOW_CREDITS_DEFAULT; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.never; + import java.util.concurrent.Executor; import java.util.function.Consumer; @@ -29,28 +36,17 @@ import org.apache.activemq.artemis.protocol.amqp.proton.AMQPSessionContext; import org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerReceiverContext; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.qpid.proton.engine.Receiver; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +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.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.mockito.quality.Strictness; - -import static org.apache.activemq.artemis.protocol.amqp.proton.AmqpSupport.AMQP_CREDITS_DEFAULT; -import static org.apache.activemq.artemis.protocol.amqp.proton.AmqpSupport.AMQP_LOW_CREDITS_DEFAULT; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.never; +import org.mockito.junit.jupiter.MockitoExtension; +@ExtendWith(MockitoExtension.class) public class AMQPSessionCallbackTest { - @Rule - public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock private AMQPConnectionCallback protonSPI; @Mock @@ -73,7 +69,7 @@ public class AMQPSessionCallbackTest { private PagingStore pagingStore; - @Before + @BeforeEach public void setRule() { Mockito.when(connection.isHandler()).thenReturn(true); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/federation/AMQPFederationPolicySupportTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/federation/AMQPFederationPolicySupportTest.java index 4966fce7dd..e4a09e6b02 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/federation/AMQPFederationPolicySupportTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/federation/AMQPFederationPolicySupportTest.java @@ -33,11 +33,11 @@ import static org.apache.activemq.artemis.protocol.amqp.connect.federation.AMQPF import static org.apache.activemq.artemis.protocol.amqp.connect.federation.AMQPFederationConstants.QUEUE_INCLUDES; import static org.apache.activemq.artemis.protocol.amqp.connect.federation.AMQPFederationConstants.QUEUE_INCLUDE_FEDERATED; import static org.apache.activemq.artemis.protocol.amqp.connect.federation.AMQPFederationConstants.QUEUE_PRIORITY_ADJUSTMENT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; +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 java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; @@ -71,8 +71,7 @@ import org.apache.qpid.proton.amqp.messaging.Section; import org.apache.qpid.proton.codec.EncoderImpl; import org.apache.qpid.proton.codec.WritableBuffer; import org.jgroups.util.UUID; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/mirror/MirrorAddressFilterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/mirror/MirrorAddressFilterTest.java index 967b8cab3e..cfb2560207 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/mirror/MirrorAddressFilterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/connect/mirror/MirrorAddressFilterTest.java @@ -16,21 +16,23 @@ */ package org.apache.activemq.artemis.protocol.amqp.connect.mirror; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.SimpleString; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MirrorAddressFilterTest { @Test public void testAddressFilter() { - Assert.assertTrue(new MirrorAddressFilter("").match(new SimpleString("any"))); - Assert.assertTrue(new MirrorAddressFilter("test").match(new SimpleString("test123"))); - Assert.assertTrue(new MirrorAddressFilter("a,b").match(new SimpleString("b"))); - Assert.assertTrue(new MirrorAddressFilter("!c").match(new SimpleString("a"))); - Assert.assertTrue(new MirrorAddressFilter("!a,!").match(new SimpleString("b123"))); - Assert.assertFalse(new MirrorAddressFilter("a,b,!ab").match(new SimpleString("ab"))); - Assert.assertFalse(new MirrorAddressFilter("!a,!b").match(new SimpleString("b123"))); - Assert.assertFalse(new MirrorAddressFilter("a,").match(new SimpleString("b"))); + assertTrue(new MirrorAddressFilter("").match(new SimpleString("any"))); + assertTrue(new MirrorAddressFilter("test").match(new SimpleString("test123"))); + assertTrue(new MirrorAddressFilter("a,b").match(new SimpleString("b"))); + assertTrue(new MirrorAddressFilter("!c").match(new SimpleString("a"))); + assertTrue(new MirrorAddressFilter("!a,!").match(new SimpleString("b123"))); + assertFalse(new MirrorAddressFilter("a,b,!ab").match(new SimpleString("ab"))); + assertFalse(new MirrorAddressFilter("!a,!b").match(new SimpleString("b123"))); + assertFalse(new MirrorAddressFilter("a,").match(new SimpleString("b"))); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/AnnotationNameConveterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/AnnotationNameConveterTest.java index 81f80030e4..4f9b72af13 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/AnnotationNameConveterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/AnnotationNameConveterTest.java @@ -16,17 +16,18 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.Message; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AnnotationNameConveterTest { @Test public void testAnnotationName() { try { - Assert.assertEquals("x-opt-ORIG-QUEUE", AMQPMessageSupport.toAnnotationName(Message.HDR_ORIGINAL_QUEUE.toString())); - Assert.assertEquals("x-opt-ORIG-MESSAGE-ID", AMQPMessageSupport.toAnnotationName(Message.HDR_ORIG_MESSAGE_ID.toString())); + assertEquals("x-opt-ORIG-QUEUE", AMQPMessageSupport.toAnnotationName(Message.HDR_ORIGINAL_QUEUE.toString())); + assertEquals("x-opt-ORIG-MESSAGE-ID", AMQPMessageSupport.toAnnotationName(Message.HDR_ORIG_MESSAGE_ID.toString())); } catch (Exception e) { e.printStackTrace(); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/TestConversions.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/TestConversions.java index c937c7c441..a081b3e69b 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/TestConversions.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/TestConversions.java @@ -16,6 +16,19 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter; +import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.AMQP_NULL; +import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_DELIVERY_ANNOTATION_PREFIX; +import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_FOOTER_PREFIX; +import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_MESSAGE_ANNOTATION_PREFIX; +import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ORIGINAL_ENCODING; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.invoke.MethodHandles; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.LinkedHashMap; @@ -52,19 +65,11 @@ import org.apache.qpid.proton.codec.EncoderImpl; import org.apache.qpid.proton.codec.WritableBuffer; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.invoke.MethodHandles; -import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.AMQP_NULL; -import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_DELIVERY_ANNOTATION_PREFIX; -import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_FOOTER_PREFIX; -import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ENCODED_MESSAGE_ANNOTATION_PREFIX; -import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ORIGINAL_ENCODING; - -public class TestConversions extends Assert { +public class TestConversions { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -119,12 +124,12 @@ public class TestConversions extends Assert { bytesMessage.readBytes(newBodyBytes); - Assert.assertArrayEquals(bodyBytes, newBodyBytes); + assertArrayEquals(bodyBytes, newBodyBytes); } private void verifyProperties(CoreMessageWrapper message) throws Exception { - assertEquals(true, message.getBooleanProperty("true")); - assertEquals(false, message.getBooleanProperty("false")); + assertTrue(message.getBooleanProperty("true")); + assertFalse(message.getBooleanProperty("false")); assertEquals("bar", message.getStringProperty("foo")); } @@ -423,7 +428,7 @@ public class TestConversions extends Assert { encodedMessage.messageChanged(); AmqpValue value = (AmqpValue) encodedMessage.getProtonMessage().getBody(); - Assert.assertEquals(text, (String) value.getValue()); + assertEquals(text, (String) value.getValue()); // this line is needed to force a failure ICoreMessage coreMessage = encodedMessage.toCore(); @@ -455,7 +460,7 @@ public class TestConversions extends Assert { encodedMessage.messageChanged(); encodedMessage.reencode(); AmqpValue value = (AmqpValue) encodedMessage.getProtonMessage().getBody(); - Assert.assertEquals(text, (String) value.getValue()); + assertEquals(text, (String) value.getValue()); ICoreMessage coreMessage = encodedMessage.toCore(); logger.debug("Converted message: {}", coreMessage); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPContentTypeSupportTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPContentTypeSupportTest.java index 54a98e6e65..013f243c90 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPContentTypeSupportTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPContentTypeSupportTest.java @@ -16,42 +16,53 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter.message; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.apache.activemq.artemis.protocol.amqp.converter.AMQPContentTypeSupport; import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport; import org.apache.activemq.artemis.protocol.amqp.exceptions.ActiveMQAMQPInvalidContentTypeException; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.Test; public class AMQPContentTypeSupportTest { - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeWithOnlyType() throws Exception { - doParseContentTypeTestImpl("type", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("type", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeEndsWithSlash() throws Exception { - doParseContentTypeTestImpl("type/", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("type/", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeMissingSubtype() throws Exception { - doParseContentTypeTestImpl("type/;", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("type/;", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeEmptyString() throws Exception { - doParseContentTypeTestImpl("", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeNullString() throws Exception { - doParseContentTypeTestImpl(null, null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl(null, null); + }); } @Test @@ -95,24 +106,32 @@ public class AMQPContentTypeSupportTest { doParseContentTypeTestImpl("text/plain;charset=\"us-ascii\"", StandardCharsets.US_ASCII); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeWithCharsetQuotedEmpty() throws Exception { - doParseContentTypeTestImpl("text/plain;charset=\"\"", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("text/plain;charset=\"\"", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeWithCharsetQuoteNotClosed() throws Exception { - doParseContentTypeTestImpl("text/plain;charset=\"unclosed", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("text/plain;charset=\"unclosed", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeWithCharsetQuoteNotClosedEmpty() throws Exception { - doParseContentTypeTestImpl("text/plain;charset=\"", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("text/plain;charset=\"", null); + }); } - @Test(expected = ActiveMQAMQPInvalidContentTypeException.class) + @Test public void testParseContentTypeWithNoCharsetValue() throws Exception { - doParseContentTypeTestImpl("text/plain;charset=", null); + assertThrows(ActiveMQAMQPInvalidContentTypeException.class, () -> { + doParseContentTypeTestImpl("text/plain;charset=", null); + }); } @Test @@ -224,9 +243,9 @@ public class AMQPContentTypeSupportTest { private void doParseContentTypeTestImpl(String contentType, Charset expected) throws ActiveMQAMQPInvalidContentTypeException { Charset charset = AMQPContentTypeSupport.parseContentTypeForTextualCharset(contentType); if (expected == null) { - assertNull("Expected no charset, but got:" + charset, charset); + assertNull(charset, "Expected no charset, but got:" + charset); } else { - assertEquals("Charset not as expected", expected, charset); + assertEquals(expected, charset, "Charset not as expected"); } } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageIdHelperTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageIdHelperTest.java index dc9dc2e5ba..3ea496e070 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageIdHelperTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageIdHelperTest.java @@ -18,13 +18,13 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter.message; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.UUID; @@ -32,14 +32,14 @@ import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageIdHelper; import org.apache.activemq.artemis.protocol.amqp.exceptions.ActiveMQAMQPIllegalStateException; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.UnsignedLong; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class AMQPMessageIdHelperTest { private AMQPMessageIdHelper messageIdHelper; - @Before + @BeforeEach public void setUp() throws Exception { messageIdHelper = AMQPMessageIdHelper.INSTANCE; } @@ -51,7 +51,7 @@ public class AMQPMessageIdHelperTest { @Test public void testHasIdPrefixWithPrefix() { String myId = "ID:something"; - assertTrue("'ID:' prefix should have been identified", messageIdHelper.hasMessageIdPrefix(myId)); + assertTrue(messageIdHelper.hasMessageIdPrefix(myId), "'ID:' prefix should have been identified"); } /** @@ -61,7 +61,7 @@ public class AMQPMessageIdHelperTest { @Test public void testHasIdPrefixWithIDButNoColonPrefix() { String myIdNoColon = "IDsomething"; - assertFalse("'ID' prefix should not have been identified without trailing colon", messageIdHelper.hasMessageIdPrefix(myIdNoColon)); + assertFalse(messageIdHelper.hasMessageIdPrefix(myIdNoColon), "'ID' prefix should not have been identified without trailing colon"); } /** @@ -71,7 +71,7 @@ public class AMQPMessageIdHelperTest { @Test public void testHasIdPrefixWithNull() { String nullString = null; - assertFalse("null string should not result in identification as having the prefix", messageIdHelper.hasMessageIdPrefix(nullString)); + assertFalse(messageIdHelper.hasMessageIdPrefix(nullString), "null string should not result in identification as having the prefix"); } /** @@ -81,7 +81,7 @@ public class AMQPMessageIdHelperTest { @Test public void testHasIdPrefixWithoutPrefix() { String myNonId = "something"; - assertFalse("string without 'ID:' anywhere should not have been identified as having the prefix", messageIdHelper.hasMessageIdPrefix(myNonId)); + assertFalse(messageIdHelper.hasMessageIdPrefix(myNonId), "string without 'ID:' anywhere should not have been identified as having the prefix"); } /** @@ -91,7 +91,7 @@ public class AMQPMessageIdHelperTest { @Test public void testHasIdPrefixWithLowercaseID() { String myLowerCaseNonId = "id:something"; - assertFalse("lowercase 'id:' prefix should not result in identification as having 'ID:' prefix", messageIdHelper.hasMessageIdPrefix(myLowerCaseNonId)); + assertFalse(messageIdHelper.hasMessageIdPrefix(myLowerCaseNonId), "lowercase 'id:' prefix should not result in identification as having 'ID:' prefix"); } /** @@ -100,7 +100,7 @@ public class AMQPMessageIdHelperTest { */ @Test public void testToMessageIdStringWithNull() { - assertNull("null string should have been returned", messageIdHelper.toMessageIdString(null)); + assertNull(messageIdHelper.toMessageIdString(null), "null string should have been returned"); } /** @@ -119,8 +119,8 @@ public class AMQPMessageIdHelperTest { private void doToMessageIdTestImpl(Object idObject, String expected) { String idString = messageIdHelper.toMessageIdString(idObject); - assertNotNull("null string should not have been returned", idString); - assertEquals("expected id string was not returned", expected, idString); + assertNotNull(idString, "null string should not have been returned"); + assertEquals(expected, idString, "expected id string was not returned"); } /** @@ -326,7 +326,7 @@ public class AMQPMessageIdHelperTest { */ @Test public void testToCorrelationIdStringWithNull() { - assertNull("null string should have been returned", messageIdHelper.toCorrelationIdStringOrBytes(null)); + assertNull(messageIdHelper.toCorrelationIdStringOrBytes(null), "null string should have been returned"); } /** @@ -345,14 +345,14 @@ public class AMQPMessageIdHelperTest { private void doToCorrelationIDTestImpl(Object idObject, String expected) { String idString = (String) messageIdHelper.toCorrelationIdStringOrBytes(idObject); - assertNotNull("null string should not have been returned", idString); - assertEquals("expected id string was not returned", expected, idString); + assertNotNull(idString, "null string should not have been returned"); + assertEquals(expected, idString, "expected id string was not returned"); } private void doToCorrelationIDBytesTestImpl(Object idObject, byte[] expected) { byte[] idBytes = (byte[]) messageIdHelper.toCorrelationIdStringOrBytes(idObject); - assertNotNull("null byte[] should not have been returned", idBytes); - assertArrayEquals("expected id byte[] was not returned", expected, idBytes); + assertNotNull(idBytes, "null byte[] should not have been returned"); + assertArrayEquals(expected, idBytes, "expected id byte[] was not returned"); } /** @@ -556,8 +556,8 @@ public class AMQPMessageIdHelperTest { private void doToIdObjectTestImpl(String idString, Object expected) throws ActiveMQAMQPIllegalStateException { Object idObject = messageIdHelper.toIdObject(idString); - assertNotNull("null object should not have been returned", idObject); - assertEquals("expected id object was not returned", expected, idObject); + assertNotNull(idObject, "null object should not have been returned"); + assertEquals(expected, idObject, "expected id object was not returned"); } /** @@ -602,7 +602,7 @@ public class AMQPMessageIdHelperTest { */ @Test public void testToIdObjectWithNull() throws Exception { - assertNull("null object should have been returned", messageIdHelper.toIdObject(null)); + assertNull(messageIdHelper.toIdObject(null), "null object should have been returned"); } /** @@ -734,7 +734,7 @@ public class AMQPMessageIdHelperTest { } catch (ActiveMQAMQPIllegalStateException iae) { // expected String msg = iae.getMessage(); - assertTrue("Message was not as expected: " + msg, msg.contains("even length")); + assertTrue(msg.contains("even length"), "Message was not as expected: " + msg); } } @@ -757,7 +757,7 @@ public class AMQPMessageIdHelperTest { } catch (ActiveMQAMQPIllegalStateException ice) { // expected String msg = ice.getMessage(); - assertTrue("Message was not as expected: " + msg, msg.contains("non-hex")); + assertTrue(msg.contains("non-hex"), "Message was not as expected: " + msg); } // char after '9', before 'A' @@ -770,7 +770,7 @@ public class AMQPMessageIdHelperTest { } catch (ActiveMQAMQPIllegalStateException iae) { // expected String msg = iae.getMessage(); - assertTrue("Message was not as expected: " + msg, msg.contains("non-hex")); + assertTrue(msg.contains("non-hex"), "Message was not as expected: " + msg); } // char after 'F', before 'a' @@ -783,7 +783,7 @@ public class AMQPMessageIdHelperTest { } catch (ActiveMQAMQPIllegalStateException iae) { // expected String msg = iae.getMessage(); - assertTrue("Message was not as expected: " + msg, msg.contains("non-hex")); + assertTrue(msg.contains("non-hex"), "Message was not as expected: " + msg); } // char after 'f' @@ -796,7 +796,7 @@ public class AMQPMessageIdHelperTest { } catch (ActiveMQAMQPIllegalStateException ice) { // expected String msg = ice.getMessage(); - assertTrue("Message was not as expected: " + msg, msg.contains("non-hex")); + assertTrue(msg.contains("non-hex"), "Message was not as expected: " + msg); } } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageSupportTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageSupportTest.java index 6aeb4dcdae..1258c8cbe6 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageSupportTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/AMQPMessageSupportTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter.message; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -24,12 +29,7 @@ import org.apache.qpid.proton.Proton; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.message.Message; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class AMQPMessageSupportTest { diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/DirectConvertTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/DirectConvertTest.java index 1be184c125..2352ebf809 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/DirectConvertTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/DirectConvertTest.java @@ -17,14 +17,15 @@ package org.apache.activemq.artemis.protocol.amqp.converter.message; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.ICoreMessage; import org.apache.activemq.artemis.core.message.impl.CoreMessage; import org.apache.activemq.artemis.core.persistence.impl.nullpm.NullStorageManager; import org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage; import org.apache.activemq.artemis.protocol.amqp.broker.AMQPStandardMessage; import org.apache.activemq.artemis.protocol.amqp.converter.CoreAmqpConverter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class DirectConvertTest { @@ -38,7 +39,7 @@ public class DirectConvertTest { ICoreMessage coreMessage = standardMessage.toCore(); - Assert.assertEquals((Long)deliveryTime, coreMessage.getScheduledDeliveryTime()); + assertEquals((Long)deliveryTime, coreMessage.getScheduledDeliveryTime()); } @@ -52,7 +53,7 @@ public class DirectConvertTest { ICoreMessage coreMessage = standardMessage.toCore(); - Assert.assertEquals(time, coreMessage.getExpiration()); + assertEquals(time, coreMessage.getExpiration()); } @Test @@ -63,7 +64,7 @@ public class DirectConvertTest { coreMessage.initBuffer(1024); AMQPMessage amqpMessage = CoreAmqpConverter.fromCore(coreMessage, new NullStorageManager()); - Assert.assertEquals((Long)deliveryTime, amqpMessage.getScheduledDeliveryTime()); + assertEquals((Long)deliveryTime, amqpMessage.getScheduledDeliveryTime()); } @Test @@ -74,6 +75,6 @@ public class DirectConvertTest { coreMessage.initBuffer(1024); AMQPMessage amqpMessage = CoreAmqpConverter.fromCore(coreMessage, new NullStorageManager()); - Assert.assertEquals(time, amqpMessage.getExpiration()); + assertEquals(time, amqpMessage.getExpiration()); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingInboundTransformerTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingInboundTransformerTest.java index 6278710087..236536a34f 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingInboundTransformerTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingInboundTransformerTest.java @@ -16,10 +16,10 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -29,7 +29,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; - import org.apache.activemq.artemis.api.core.ICoreMessage; import org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage; import org.apache.activemq.artemis.protocol.amqp.broker.AMQPStandardMessage; @@ -43,21 +42,21 @@ import org.apache.activemq.artemis.protocol.amqp.converter.coreWrapper.CoreTextM import org.apache.activemq.artemis.protocol.amqp.util.NettyReadable; import org.apache.activemq.artemis.protocol.amqp.util.NettyWritable; import org.apache.qpid.proton.amqp.Binary; +import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.amqp.messaging.Data; +import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import io.netty.buffer.Unpooled; -import org.apache.qpid.proton.amqp.Symbol; -import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; public class JMSMappingInboundTransformerTest { - @Before + @BeforeEach public void setUp() { } @@ -81,8 +80,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(coreMessage); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -98,8 +97,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } @Test @@ -109,8 +108,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreTextMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreTextMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } // ----- Data Body Section ------------------------------------------------// @@ -133,8 +132,8 @@ public class JMSMappingInboundTransformerTest { AMQPStandardMessage amqp = encodeAndCreateAMQPMessage(message); CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(amqp.toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -154,8 +153,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -175,8 +174,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } @Test @@ -188,8 +187,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreObjectMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreObjectMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } @Test @@ -288,11 +287,11 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); + assertNotNull(jmsMessage, "Message should not be null"); if (StandardCharsets.UTF_8.equals(expectedCharset)) { - assertEquals("Unexpected message class type", CoreTextMessageWrapper.class, jmsMessage.getClass()); + assertEquals(CoreTextMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } else { - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } } @@ -312,8 +311,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreTextMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreTextMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -330,8 +329,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreTextMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreTextMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -350,8 +349,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreObjectMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreObjectMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -369,8 +368,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreMapMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreMapMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -388,8 +387,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreStreamMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreStreamMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -407,8 +406,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreStreamMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreStreamMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -426,8 +425,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } /** @@ -445,8 +444,8 @@ public class JMSMappingInboundTransformerTest { CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertNotNull("Message should not be null", jmsMessage); - assertEquals("Unexpected message class type", CoreBytesMessageWrapper.class, jmsMessage.getClass()); + assertNotNull(jmsMessage, "Message should not be null"); + assertEquals(CoreBytesMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); } @Test @@ -458,8 +457,8 @@ public class JMSMappingInboundTransformerTest { CoreTextMessageWrapper jmsMessage = (CoreTextMessageWrapper) CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); jmsMessage.decode(); - assertTrue("Expected TextMessage", jmsMessage instanceof CoreTextMessageWrapper); - assertEquals("Unexpected message class type", CoreTextMessageWrapper.class, jmsMessage.getClass()); + assertTrue(jmsMessage instanceof CoreTextMessageWrapper, "Expected TextMessage"); + assertEquals(CoreTextMessageWrapper.class, jmsMessage.getClass(), "Unexpected message class type"); CoreTextMessageWrapper textMessage = jmsMessage; @@ -509,7 +508,7 @@ public class JMSMappingInboundTransformerTest { } CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertTrue("Expected ServerJMSTextMessage", jmsMessage instanceof CoreTextMessageWrapper); + assertTrue(jmsMessage instanceof CoreTextMessageWrapper, "Expected ServerJMSTextMessage"); } // ----- ReplyTo Conversions ----------------------------------------------// @@ -555,7 +554,7 @@ public class JMSMappingInboundTransformerTest { } CoreMessageWrapper jmsMessage = CoreMessageWrapper.wrap(encodeAndCreateAMQPMessage(message).toCore()); - assertTrue("Expected TextMessage", jmsMessage instanceof CoreTextMessageWrapper); + assertTrue(jmsMessage instanceof CoreTextMessageWrapper, "Expected TextMessage"); } private AMQPStandardMessage encodeAndCreateAMQPMessage(MessageImpl message) { diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingOutboundTransformerTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingOutboundTransformerTest.java index beff7c9c9d..780c751d3f 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingOutboundTransformerTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSMappingOutboundTransformerTest.java @@ -23,12 +23,12 @@ import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSup import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.AMQP_VALUE_BINARY; import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.AMQP_VALUE_LIST; import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.JMS_AMQP_ORIGINAL_ENCODING; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -42,7 +42,6 @@ import java.util.UUID; import org.apache.activemq.artemis.core.buffers.impl.ResetLimitWrappedActiveMQBuffer; import org.apache.activemq.artemis.core.message.impl.CoreMessage; - import org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage; import org.apache.activemq.artemis.protocol.amqp.converter.AMQPConverter; import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport; @@ -59,7 +58,7 @@ import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.amqp.messaging.Data; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JMSMappingOutboundTransformerTest { @@ -479,13 +478,13 @@ public class JMSMappingOutboundTransformerTest { Map maMap = ma == null ? null : ma.getValue(); if (maMap != null) { Object actualValue = maMap.get(AMQPMessageSupport.JMS_DEST_TYPE_MSG_ANNOTATION); - assertEquals("Unexpected annotation value", expectedAnnotationValue, actualValue); + assertEquals(expectedAnnotationValue, actualValue, "Unexpected annotation value"); } else if (expectedAnnotationValue != null) { fail("Expected annotation value, but there were no annotations"); } if (jmsDestination != null) { - assertEquals("Unexpected 'to' address", jmsDestination, amqp.getAddress()); + assertEquals(jmsDestination, amqp.getAddress(), "Unexpected 'to' address"); } } @@ -512,13 +511,13 @@ public class JMSMappingOutboundTransformerTest { Map maMap = ma == null ? null : ma.getValue(); if (maMap != null) { Object actualValue = maMap.get(AMQPMessageSupport.JMS_REPLY_TO_TYPE_MSG_ANNOTATION); - assertEquals("Unexpected annotation value", expectedAnnotationValue, actualValue); + assertEquals(expectedAnnotationValue, actualValue, "Unexpected annotation value"); } else if (expectedAnnotationValue != null) { fail("Expected annotation value, but there were no annotations"); } if (jmsReplyTo != null) { - assertEquals("Unexpected 'reply-to' address", jmsReplyTo, amqp.getReplyTo().toString()); + assertEquals(jmsReplyTo, amqp.getReplyTo().toString(), "Unexpected 'reply-to' address"); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSTransformationSpeedComparisonTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSTransformationSpeedComparisonTest.java index b92dfdcf29..95585c9d53 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSTransformationSpeedComparisonTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/JMSTransformationSpeedComparisonTest.java @@ -33,11 +33,10 @@ import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.amqp.messaging.ApplicationProperties; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; @@ -46,17 +45,17 @@ import io.netty.buffer.Unpooled; /** * Some simple performance tests for the Message Transformers. */ -@Ignore("Useful for profiling but slow and not meant as a unit test") +@Disabled("Useful for profiling but slow and not meant as a unit test") public class JMSTransformationSpeedComparisonTest { - @Rule - public TestName test = new TestName(); + public String test; private final int WARM_CYCLES = 1000; private final int PROFILE_CYCLES = 1000000; - @Before - public void setUp() { + @BeforeEach + public void setUp(TestInfo testInfo) { + this.test = testInfo.getTestMethod().get().getName(); } @Test @@ -293,7 +292,7 @@ public class JMSTransformationSpeedComparisonTest { private void LOG_RESULTS(long duration) { String result = "[JMS] Total time for " + PROFILE_CYCLES + " cycles of transforms = " + TimeUnit.NANOSECONDS.toMillis(duration) + " ms -> " - + test.getMethodName(); + + test; System.out.println(result); } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/MessageTransformationTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/MessageTransformationTest.java index f89e0d7f65..0918d558ce 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/MessageTransformationTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/converter/message/MessageTransformationTest.java @@ -16,10 +16,10 @@ */ package org.apache.activemq.artemis.protocol.amqp.converter.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.util.HashMap; @@ -38,9 +38,7 @@ import org.apache.qpid.proton.amqp.messaging.ApplicationProperties; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.amqp.messaging.Section; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.Test; import io.netty.buffer.Unpooled; @@ -49,9 +47,6 @@ import io.netty.buffer.Unpooled; */ public class MessageTransformationTest { - @Rule - public TestName test = new TestName(); - @Test public void testBodyOnlyEncodeDecode() throws Exception { MessageImpl incomingMessage = (MessageImpl) Proton.message(); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/logger/AMQPLogBundlesTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/logger/AMQPLogBundlesTest.java index 03029bbd02..2317c079de 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/logger/AMQPLogBundlesTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/logger/AMQPLogBundlesTest.java @@ -16,27 +16,27 @@ */ package org.apache.activemq.artemis.protocol.amqp.logger; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; import org.apache.activemq.artemis.protocol.amqp.exceptions.ActiveMQAMQPInternalErrorException; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class AMQPLogBundlesTest { private static final String LOGGER_NAME = ActiveMQAMQPProtocolLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } @@ -56,7 +56,7 @@ public class AMQPLogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ119005")); - assertTrue("unexpected message: " + message, message.contains("messageBreadCrumb")); + assertTrue(message.startsWith("AMQ119005"), "unexpected message: " + message); + assertTrue(message.contains("messageBreadCrumb"), "unexpected message: " + message); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContextTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContextTest.java index 13b0258d2f..983008f4f5 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContextTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContextTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.protocol.amqp.proton; +import static org.junit.jupiter.api.Assertions.assertEquals; + import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; import io.netty.channel.EventLoop; @@ -28,8 +30,7 @@ import org.apache.activemq.artemis.protocol.amqp.broker.ProtonProtocolManager; import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; import org.apache.qpid.proton.engine.Connection; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.HashMap; @@ -81,6 +82,6 @@ public class AMQPConnectionContextTest { connectionContext.close(null); - Assert.assertEquals(0, scheduledPool.getQueue().size()); + assertEquals(0, scheduledPool.getQueue().size()); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPLargeMessageWriterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPLargeMessageWriterTest.java index 2122fd3200..c1a6b4ce88 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPLargeMessageWriterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPLargeMessageWriterTest.java @@ -17,7 +17,7 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atLeastOnce; @@ -40,8 +40,8 @@ import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.engine.Session; import org.apache.qpid.proton.engine.impl.TransportImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -97,7 +97,7 @@ public class AMQPLargeMessageWriterTest { @Spy NullStorageManager nullStoreManager = new NullStorageManager(); - @Before + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageReaderTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageReaderTest.java index 68b74b30d8..253f434616 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageReaderTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageReaderTest.java @@ -17,11 +17,11 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; @@ -47,8 +47,8 @@ import org.apache.qpid.proton.codec.ReadableBuffer; import org.apache.qpid.proton.codec.WritableBuffer; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.Receiver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -80,7 +80,7 @@ public class AMQPTunneledCoreLargeMessageReaderTest { @Spy NullStorageManager nullStoreManager = new NullStorageManager(); - @Before + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageWriterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageWriterTest.java index c686a59384..8ec31f3dba 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageWriterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreLargeMessageWriterTest.java @@ -17,9 +17,9 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertEquals; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atLeastOnce; @@ -50,8 +50,8 @@ import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.engine.Session; import org.apache.qpid.proton.engine.impl.TransportImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -111,7 +111,7 @@ public class AMQPTunneledCoreLargeMessageWriterTest { @Captor ArgumentCaptor tunneledCaptor; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageReaderTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageReaderTest.java index 348b92bd2c..8618180bb3 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageReaderTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageReaderTest.java @@ -17,12 +17,12 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; import java.util.HashMap; @@ -50,8 +50,8 @@ import org.apache.qpid.proton.codec.ReadableBuffer; import org.apache.qpid.proton.codec.WritableBuffer; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.Receiver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -80,7 +80,7 @@ public class AMQPTunneledCoreMessageReaderTest { @Spy NullStorageManager nullStoreManager = new NullStorageManager(); - @Before + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageWriterTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageWriterTest.java index 7a09c0911b..e63d06da6e 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageWriterTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPTunneledCoreMessageWriterTest.java @@ -17,9 +17,9 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertEquals; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doAnswer; @@ -47,8 +47,8 @@ import org.apache.qpid.proton.codec.WritableBuffer; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Sender; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -93,7 +93,7 @@ public class AMQPTunneledCoreMessageWriterTest { @Captor ArgumentCaptor tunneledCaptor; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpSupportTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpSupportTest.java index 852d44d4f2..7246648a60 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpSupportTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpSupportTest.java @@ -17,15 +17,15 @@ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.engine.Link; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpTransferTagGeneratorTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpTransferTagGeneratorTest.java index 0ed1ffbb31..d5656e1268 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpTransferTagGeneratorTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/AmqpTransferTagGeneratorTest.java @@ -16,11 +16,11 @@ */ package org.apache.activemq.artemis.protocol.amqp.proton; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -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.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.DataInputStream; @@ -29,8 +29,8 @@ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests for the AMQP Transfer Tag Generator @@ -165,7 +165,7 @@ public class AmqpTransferTagGeneratorTest { } } - @Ignore("Used to test performance") + @Disabled("Used to test performance") @Test public void testTagGeneratorOverTime() { final AmqpTransferTagGenerator tagGen = new AmqpTransferTagGenerator(true); diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonHandlerAfterRunTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonHandlerAfterRunTest.java index 971f6eae04..7502fa5fd9 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonHandlerAfterRunTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonHandlerAfterRunTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.protocol.amqp.proton; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -36,8 +38,7 @@ import io.netty.util.concurrent.ProgressivePromise; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.ScheduledFuture; import org.apache.activemq.artemis.protocol.amqp.proton.handler.ProtonHandler; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ProtonHandlerAfterRunTest { @@ -222,18 +223,18 @@ public class ProtonHandlerAfterRunTest { handler.afterFlush(run); handler.runAfterFlush(); - Assert.assertEquals(1, value.get()); - Assert.assertEquals(0, value2.get()); + assertEquals(1, value.get()); + assertEquals(0, value2.get()); handler.runAfterFlush(); - Assert.assertEquals(1, value.get()); - Assert.assertEquals(0, value2.get()); + assertEquals(1, value.get()); + assertEquals(0, value2.get()); handler.afterFlush(run); handler.runAfterFlush(); - Assert.assertEquals(2, value.get()); - Assert.assertEquals(0, value2.get()); + assertEquals(2, value.get()); + assertEquals(0, value2.get()); handler.afterFlush(run); handler.afterFlush(run); @@ -247,21 +248,21 @@ public class ProtonHandlerAfterRunTest { handler.afterFlush(run); handler.runAfterFlush(); - Assert.assertEquals(3, value.get()); - Assert.assertEquals(1, value2.get()); + assertEquals(3, value.get()); + assertEquals(1, value2.get()); handler.runAfterFlush(); - Assert.assertEquals(3, value.get()); - Assert.assertEquals(1, value2.get()); + assertEquals(3, value.get()); + assertEquals(1, value2.get()); handler.afterFlush(run2); handler.runAfterFlush(); - Assert.assertEquals(3, value.get()); - Assert.assertEquals(2, value2.get()); + assertEquals(3, value.get()); + assertEquals(2, value2.get()); handler.runAfterFlush(); - Assert.assertEquals(3, value.get()); - Assert.assertEquals(2, value2.get()); + assertEquals(3, value.get()); + assertEquals(2, value2.get()); } @Test diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerReceiverContextTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerReceiverContextTest.java index 88294f6f96..8b327041a7 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerReceiverContextTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerReceiverContextTest.java @@ -18,6 +18,9 @@ package org.apache.activemq.artemis.protocol.amqp.proton; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; @@ -58,8 +61,7 @@ import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.message.impl.MessageImpl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -146,7 +148,7 @@ public class ProtonServerReceiverContextTest { verify(mockReceiver, times(1)).current(); verify(mockReceiver, times(1)).advance(); - Assert.assertTrue(clearLargeMessage.get() > 0); + assertTrue(clearLargeMessage.get() > 0); } private void doOnMessageWithAbortedDeliveryTestImpl(boolean drain) throws ActiveMQAMQPException { @@ -190,7 +192,7 @@ public class ProtonServerReceiverContextTest { } verifyNoMoreInteractions(mockReceiver); - Assert.assertTrue(clearLargeMessage.get() > 0); + assertTrue(clearLargeMessage.get() > 0); } private void doOnMessageWithDeliveryException(List sourceSymbols, @@ -248,11 +250,11 @@ public class ProtonServerReceiverContextTest { @Test public void calculateFlowControl() { - Assert.assertFalse(ProtonServerReceiverContext.isBellowThreshold(1000, 100, 1000)); - Assert.assertTrue(ProtonServerReceiverContext.isBellowThreshold(1000, 0, 1000)); + assertFalse(ProtonServerReceiverContext.isBellowThreshold(1000, 100, 1000)); + assertTrue(ProtonServerReceiverContext.isBellowThreshold(1000, 0, 1000)); - Assert.assertEquals(1000, ProtonServerReceiverContext.calculatedUpdateRefill(2000, 1000, 0)); - Assert.assertEquals(900, ProtonServerReceiverContext.calculatedUpdateRefill(2000, 1000, 100)); + assertEquals(1000, ProtonServerReceiverContext.calculatedUpdateRefill(2000, 1000, 0)); + assertEquals(900, ProtonServerReceiverContext.calculatedUpdateRefill(2000, 1000, 100)); } private ReadableBuffer createAMQPMessageBuffer() { diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerSenderContextTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerSenderContextTest.java index 50f5b59188..28ca326896 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerSenderContextTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/proton/ProtonServerSenderContextTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.protocol.amqp.proton; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.AddressQueryResult; import org.apache.activemq.artemis.protocol.amqp.broker.AMQPSessionCallback; @@ -26,48 +32,44 @@ import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.engine.Connection; import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Sender; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class ProtonServerSenderContextTest { - @Test(expected = ActiveMQAMQPNotFoundException.class) + @Test public void testAcceptsNullSourceAddressWhenInitialising() throws Exception { - ProtonProtocolManager mock = mock(ProtonProtocolManager.class); - when(mock.getServer()).thenReturn(mock(ActiveMQServer.class)); - Sender mockSender = mock(Sender.class); - AMQPConnectionContext mockConnContext = mock(AMQPConnectionContext.class); + assertThrows(ActiveMQAMQPNotFoundException.class, () -> { + ProtonProtocolManager mock = mock(ProtonProtocolManager.class); + when(mock.getServer()).thenReturn(mock(ActiveMQServer.class)); + Sender mockSender = mock(Sender.class); + AMQPConnectionContext mockConnContext = mock(AMQPConnectionContext.class); - ProtonHandler handler = mock(ProtonHandler.class); - Connection connection = mock(Connection.class); - when(connection.getRemoteState()).thenReturn(EndpointState.ACTIVE); - when(mockConnContext.getHandler()).thenReturn(handler); - when(handler.getConnection()).thenReturn(connection); + ProtonHandler handler = mock(ProtonHandler.class); + Connection connection = mock(Connection.class); + when(connection.getRemoteState()).thenReturn(EndpointState.ACTIVE); + when(mockConnContext.getHandler()).thenReturn(handler); + when(handler.getConnection()).thenReturn(connection); - when(mockConnContext.getProtocolManager()).thenReturn(mock); + when(mockConnContext.getProtocolManager()).thenReturn(mock); - AMQPSessionCallback mockSessionCallback = mock(AMQPSessionCallback.class); + AMQPSessionCallback mockSessionCallback = mock(AMQPSessionCallback.class); - AMQPSessionContext mockSessionContext = mock(AMQPSessionContext.class); - when(mockSessionContext.getSessionSPI()).thenReturn(mockSessionCallback); - when(mockSessionContext.getAMQPConnectionContext()).thenReturn(mockConnContext); + AMQPSessionContext mockSessionContext = mock(AMQPSessionContext.class); + when(mockSessionContext.getSessionSPI()).thenReturn(mockSessionCallback); + when(mockSessionContext.getAMQPConnectionContext()).thenReturn(mockConnContext); - AddressQueryResult queryResult = new AddressQueryResult(null, Collections.emptySet(), 0, false, false, false, false, 0); - when(mockSessionCallback.addressQuery(any(), any(), anyBoolean())).thenReturn(queryResult); - ProtonServerSenderContext sc = new ProtonServerSenderContext( - mockConnContext, mockSender, mockSessionContext, mockSessionCallback); + AddressQueryResult queryResult = new AddressQueryResult(null, Collections.emptySet(), 0, false, false, false, false, 0); + when(mockSessionCallback.addressQuery(any(), any(), anyBoolean())).thenReturn(queryResult); + ProtonServerSenderContext sc = new ProtonServerSenderContext( + mockConnContext, mockSender, mockSessionContext, mockSessionCallback); - Source source = new Source(); - source.setAddress(null); - when(mockSender.getRemoteSource()).thenReturn(source); + Source source = new Source(); + source.setAddress(null); + when(mockSender.getRemoteSource()).thenReturn(source); - sc.initialize(); + sc.initialize(); + }); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/PlainSASLTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/PlainSASLTest.java index 9a2a0a28ce..1d08d48876 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/PlainSASLTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/PlainSASLTest.java @@ -16,8 +16,9 @@ */ package org.apache.activemq.artemis.protocol.amqp.sasl; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; public class PlainSASLTest { @@ -29,7 +30,7 @@ public class PlainSASLTest { ServerSASLPlain serverSASLPlain = new ServerSASLPlain(); serverSASLPlain.processSASL(bytesResult); PlainSASLResult result = (PlainSASLResult) serverSASLPlain.result(); - Assert.assertEquals("user-me", result.getUser()); - Assert.assertEquals("password-secret", result.getPassword()); + assertEquals("user-me", result.getUser()); + assertEquals("password-secret", result.getPassword()); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/SCRAMTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/SCRAMTest.java index 1136dea1cf..62f9df5352 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/SCRAMTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/sasl/SCRAMTest.java @@ -16,11 +16,12 @@ */ package org.apache.activemq.artemis.protocol.amqp.sasl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -38,16 +39,16 @@ import org.apache.activemq.artemis.spi.core.security.scram.SCRAM; import org.apache.activemq.artemis.spi.core.security.scram.ScramException; import org.apache.activemq.artemis.spi.core.security.scram.ScramUtils; import org.apache.activemq.artemis.spi.core.security.scram.UserData; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.qpid.proton.codec.DecodeException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; /** * test cases for the SASL-SCRAM */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SCRAMTest { /** @@ -73,7 +74,7 @@ public class SCRAMTest { this.mechanism = mechanism; } - @Test + @TestTemplate public void testSuccess() throws NoSuchAlgorithmException { TestSCRAMServerSASL serverSASL = new TestSCRAMServerSASL(mechanism, USERNAME, PASSWORD); TestSCRAMClientSASL clientSASL = new TestSCRAMClientSASL(mechanism, USERNAME, PASSWORD); @@ -97,7 +98,7 @@ public class SCRAMTest { assertTrue(clientCheck.length == 0); } - @Test + @TestTemplate public void testWrongClientPassword() throws NoSuchAlgorithmException { TestSCRAMServerSASL serverSASL = new TestSCRAMServerSASL(mechanism, USERNAME, PASSWORD); TestSCRAMClientSASL clientSASL = new TestSCRAMClientSASL(mechanism, USERNAME, "xyz"); @@ -113,25 +114,27 @@ public class SCRAMTest { assertNull(serverFinal); assertNotNull(serverSASL.result()); assertFalse(serverSASL.result().isSuccess()); - assertTrue(serverSASL.exception + " is not an instance of ScramException", serverSASL.exception instanceof ScramException); + assertTrue(serverSASL.exception instanceof ScramException, serverSASL.exception + " is not an instance of ScramException"); } - @Test(expected = DecodeException.class) + @TestTemplate public void testServerTryTrickClient() throws NoSuchAlgorithmException, ScramException { - TestSCRAMClientSASL clientSASL = new TestSCRAMClientSASL(mechanism, USERNAME, PASSWORD); - ScramServerFunctionalityImpl bad = - new ScramServerFunctionalityImpl(mechanism.getDigest(), mechanism.getHmac(), SNONCE); - byte[] clientFirst = clientSASL.getInitialResponse(); - assertNotNull(clientFirst); - bad.handleClientFirstMessage(new String(clientFirst, StandardCharsets.US_ASCII)); - byte[] serverFirst = - bad.prepareFirstMessage(generateUserData(mechanism, "bad")).getBytes(StandardCharsets.US_ASCII); - byte[] clientFinal = clientSASL.getResponse(serverFirst); - assertNotNull(clientFinal); - assertFalse(clientFinal.length == 0); - byte[] serverFinal = bad.prepareFinalMessageUnchecked(new String(clientFinal, StandardCharsets.US_ASCII)) - .getBytes(StandardCharsets.US_ASCII); - clientSASL.getResponse(serverFinal); + assertThrows(DecodeException.class, () -> { + TestSCRAMClientSASL clientSASL = new TestSCRAMClientSASL(mechanism, USERNAME, PASSWORD); + ScramServerFunctionalityImpl bad = + new ScramServerFunctionalityImpl(mechanism.getDigest(), mechanism.getHmac(), SNONCE); + byte[] clientFirst = clientSASL.getInitialResponse(); + assertNotNull(clientFirst); + bad.handleClientFirstMessage(new String(clientFirst, StandardCharsets.US_ASCII)); + byte[] serverFirst = + bad.prepareFirstMessage(generateUserData(mechanism, "bad")).getBytes(StandardCharsets.US_ASCII); + byte[] clientFinal = clientSASL.getResponse(serverFirst); + assertNotNull(clientFinal); + assertFalse(clientFinal.length == 0); + byte[] serverFinal = bad.prepareFinalMessageUnchecked(new String(clientFinal, StandardCharsets.US_ASCII)) + .getBytes(StandardCharsets.US_ASCII); + clientSASL.getResponse(serverFinal); + }); } private static UserData generateUserData(SCRAM mechanism, String password) throws NoSuchAlgorithmException, diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/CreditsSemaphoreTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/CreditsSemaphoreTest.java index dd74d4cea8..e622a5a8f4 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/CreditsSemaphoreTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/CreditsSemaphoreTest.java @@ -16,12 +16,15 @@ */ package org.apache.activemq.artemis.protocol.amqp.util; +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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CreditsSemaphoreTest { @@ -56,9 +59,9 @@ public class CreditsSemaphoreTest { thread.start(); // 5 seconds would be an eternity here - Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS)); + assertTrue(waiting.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, semaphore.getCredits()); + assertEquals(0, semaphore.getCredits()); validateQueuedThreads(); @@ -66,9 +69,9 @@ public class CreditsSemaphoreTest { thread.join(); - Assert.assertEquals(12, acquired.get()); + assertEquals(12, acquired.get()); - Assert.assertFalse(semaphore.hasQueuedThreads()); + assertFalse(semaphore.hasQueuedThreads()); } private void validateQueuedThreads() throws InterruptedException { @@ -83,7 +86,7 @@ public class CreditsSemaphoreTest { Thread.sleep(10); } - Assert.assertTrue(hasQueueThreads); + assertTrue(hasQueueThreads); } @Test @@ -91,9 +94,9 @@ public class CreditsSemaphoreTest { thread.start(); // 5 seconds would be an eternity here - Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS)); + assertTrue(waiting.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, semaphore.getCredits()); + assertEquals(0, semaphore.getCredits()); // TODO: Wait.assertTrue is not available at this package. So, this is making what we would be doing with a Wait Clause // we could replace this next block with a Wait clause on hasQueuedThreads @@ -102,15 +105,15 @@ public class CreditsSemaphoreTest { Thread.sleep(10); } - Assert.assertTrue(i < 1000); + assertTrue(i < 1000); semaphore.release(2); thread.join(); - Assert.assertEquals(12, acquired.get()); + assertEquals(12, acquired.get()); - Assert.assertFalse(semaphore.hasQueuedThreads()); + assertFalse(semaphore.hasQueuedThreads()); } @Test @@ -120,21 +123,21 @@ public class CreditsSemaphoreTest { thread.start(); // 5 seconds would be an eternity here - Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS)); + assertTrue(waiting.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, semaphore.getCredits()); + assertEquals(0, semaphore.getCredits()); validateQueuedThreads(); - Assert.assertEquals(0, acquired.get()); + assertEquals(0, acquired.get()); semaphore.setCredits(12); thread.join(); - Assert.assertEquals(12, acquired.get()); + assertEquals(12, acquired.get()); - Assert.assertFalse(semaphore.hasQueuedThreads()); + assertFalse(semaphore.hasQueuedThreads()); } } diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyReadableTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyReadableTest.java index c3d473b288..8fc9b4de75 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyReadableTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyReadableTest.java @@ -16,20 +16,19 @@ */ package org.apache.activemq.artemis.protocol.amqp.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import org.apache.qpid.proton.codec.ReadableBuffer; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; diff --git a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java index 3e03753ebf..3f693fc2a8 100644 --- a/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java +++ b/artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java @@ -16,17 +16,16 @@ */ package org.apache.activemq.artemis.protocol.amqp.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.qpid.proton.codec.ReadableBuffer; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -159,9 +158,9 @@ public class NettyWritableTest { ReadableBuffer input = new ReadableBuffer.ByteBufferReader(buf); if (readOnly) { - assertFalse("Expected buffer not to hasArray()", input.hasArray()); + assertFalse(input.hasArray(), "Expected buffer not to hasArray()"); } else { - assertTrue("Expected buffer to hasArray()", input.hasArray()); + assertTrue(input.hasArray(), "Expected buffer to hasArray()"); } ByteBuf buffer = Unpooled.buffer(1024); diff --git a/artemis-protocols/artemis-hornetq-protocol/pom.xml b/artemis-protocols/artemis-hornetq-protocol/pom.xml index 0b524d4498..e776a1eb02 100644 --- a/artemis-protocols/artemis-hornetq-protocol/pom.xml +++ b/artemis-protocols/artemis-hornetq-protocol/pom.xml @@ -71,8 +71,13 @@ osgi.cmpn - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-hornetq-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/PropertiesConversionTest.java b/artemis-protocols/artemis-hornetq-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/PropertiesConversionTest.java index 9094d03ca5..949ecb6401 100644 --- a/artemis-protocols/artemis-hornetq-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/PropertiesConversionTest.java +++ b/artemis-protocols/artemis-hornetq-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/PropertiesConversionTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.core.protocol.hornetq; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -30,8 +33,7 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.MessagePac import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveMessage_1X; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PropertiesConversionTest { @@ -105,8 +107,8 @@ public class PropertiesConversionTest { // I only validate half of the messages // to give it a chance of Races and Exceptions // that could happen from reusing the same message on these conversions - Assert.assertNotSame(packetRec.getMessage(), coreMessage); - Assert.assertNotSame(packetSend.getMessage(), coreMessage); + assertNotSame(packetRec.getMessage(), coreMessage); + assertNotSame(packetSend.getMessage(), coreMessage); } } } catch (Throwable e) { @@ -122,9 +124,9 @@ public class PropertiesConversionTest { thread.join(); } - Assert.assertEquals(threads * conversions, counts.get()); + assertEquals(threads * conversions, counts.get()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } @@ -196,9 +198,9 @@ public class PropertiesConversionTest { thread.join(); } - Assert.assertEquals(threads * conversions, counts.get()); + assertEquals(threads * conversions, counts.get()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } diff --git a/artemis-protocols/artemis-hqclient-protocol/pom.xml b/artemis-protocols/artemis-hqclient-protocol/pom.xml index 18c5ef7f79..f0e488c558 100644 --- a/artemis-protocols/artemis-hqclient-protocol/pom.xml +++ b/artemis-protocols/artemis-hqclient-protocol/pom.xml @@ -49,8 +49,13 @@ osgi.cmpn - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-hqclient-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/SelectorTranslatorTest.java b/artemis-protocols/artemis-hqclient-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/SelectorTranslatorTest.java index 48269eec50..17442ccb2e 100644 --- a/artemis-protocols/artemis-hqclient-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/SelectorTranslatorTest.java +++ b/artemis-protocols/artemis-hqclient-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/hornetq/SelectorTranslatorTest.java @@ -16,39 +16,40 @@ */ package org.apache.activemq.artemis.core.protocol.hornetq; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; public class SelectorTranslatorTest { @Test public void testConvertHQFilterString() { String selector = "HQUserID = 'ID:AMQ-12435678'"; - Assert.assertEquals("AMQUserID = 'ID:AMQ-12435678'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQUserID = 'ID:AMQ-12435678'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQUserID = 'HQUserID'"; - Assert.assertEquals("AMQUserID = 'HQUserID'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQUserID = 'HQUserID'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQUserID = 'ID:AMQ-12435678'"; - Assert.assertEquals("AMQUserID = 'ID:AMQ-12435678'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQUserID = 'ID:AMQ-12435678'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQDurable='NON_DURABLE'"; - Assert.assertEquals("AMQDurable='NON_DURABLE'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQDurable='NON_DURABLE'", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQPriority=5"; - Assert.assertEquals("AMQPriority=5", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQPriority=5", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQTimestamp=12345678"; - Assert.assertEquals("AMQTimestamp=12345678", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQTimestamp=12345678", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); selector = "HQExpiration=12345678"; - Assert.assertEquals("AMQExpiration=12345678", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); + assertEquals("AMQExpiration=12345678", HQFilterConversionInterceptor.convertHQToActiveMQFilterString(selector)); } } diff --git a/artemis-protocols/artemis-jakarta-openwire-protocol/pom.xml b/artemis-protocols/artemis-jakarta-openwire-protocol/pom.xml index 995579efce..12e742d0f3 100644 --- a/artemis-protocols/artemis-jakarta-openwire-protocol/pom.xml +++ b/artemis-protocols/artemis-jakarta-openwire-protocol/pom.xml @@ -99,8 +99,13 @@ osgi.cmpn - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-mqtt-protocol/pom.xml b/artemis-protocols/artemis-mqtt-protocol/pom.xml index e316ca1ff2..927cf4bd3f 100644 --- a/artemis-protocols/artemis-mqtt-protocol/pom.xml +++ b/artemis-protocols/artemis-mqtt-protocol/pom.xml @@ -98,8 +98,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogBundleTest.java b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogBundleTest.java index 10e933dd7f..4288a9b893 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogBundleTest.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTLogBundleTest.java @@ -16,25 +16,25 @@ */ package org.apache.activemq.artemis.core.protocol.mqtt; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class MQTTLogBundleTest { private static final String LOGGER_NAME = MQTTLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } diff --git a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtilTest.java b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtilTest.java index d24666e842..f1e9dfce01 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtilTest.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/MQTTUtilTest.java @@ -17,13 +17,13 @@ package org.apache.activemq.artemis.core.protocol.mqtt; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.core.config.WildcardConfiguration; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; public class MQTTUtilTest { @Test diff --git a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/StateSerDeTest.java b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/StateSerDeTest.java index 51b6ad5845..2f3fee14f3 100644 --- a/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/StateSerDeTest.java +++ b/artemis-protocols/artemis-mqtt-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/mqtt/StateSerDeTest.java @@ -17,20 +17,24 @@ package org.apache.activemq.artemis.core.protocol.mqtt; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.TimeUnit; + import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttSubscriptionOption; import io.netty.handler.codec.mqtt.MqttTopicSubscription; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.core.message.impl.CoreMessage; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class StateSerDeTest { - @Test(timeout = 30000) + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) public void testSerDe() throws Exception { for (int i = 0; i < 500; i++) { String clientId = RandomUtil.randomString(); diff --git a/artemis-protocols/artemis-openwire-protocol/pom.xml b/artemis-protocols/artemis-openwire-protocol/pom.xml index bffe3b19bf..5d8231c406 100644 --- a/artemis-protocols/artemis-openwire-protocol/pom.xml +++ b/artemis-protocols/artemis-openwire-protocol/pom.xml @@ -105,8 +105,13 @@ osgi.cmpn - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverterTest.java b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverterTest.java index 0624bc35f4..d3d7f8a894 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverterTest.java +++ b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/OpenWireMessageConverterTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.core.protocol.openwire; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.charset.StandardCharsets; import org.apache.activemq.ActiveMQMessageAuditNoSync; @@ -43,14 +48,9 @@ import org.apache.activemq.command.ProducerId; import org.apache.activemq.openwire.OpenWireFormatFactory; import org.apache.activemq.util.ByteSequence; import org.apache.activemq.wireformat.WireFormat; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - public class OpenWireMessageConverterTest { final OpenWireFormatFactory formatFactory = new OpenWireFormatFactory(); diff --git a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerTest.java b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerTest.java index 7992c4f040..c302f98aff 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerTest.java +++ b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerTest.java @@ -16,7 +16,9 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; -import static org.junit.Assert.assertEquals; +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.concurrent.ScheduledExecutorService; @@ -43,8 +45,7 @@ import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.openwire.OpenWireFormatFactory; import org.apache.activemq.wireformat.WireFormat; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -114,14 +115,14 @@ public class AMQConsumerTest { ICoreMessage message = new CoreMessage(1, 0); MessageReference reference = Mockito.mock(MessageReference.class); - Assert.assertTrue(consumer.hasCredits()); + assertTrue(consumer.hasCredits()); consumer.handleDeliver(reference, message); - Assert.assertFalse(consumer.hasCredits()); + assertFalse(consumer.hasCredits()); consumer.acquireCredit(1, true); - Assert.assertTrue(consumer.hasCredits()); + assertTrue(consumer.hasCredits()); } } diff --git a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireConnectionTest.java b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireConnectionTest.java index 9071c755a5..839b884c4b 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireConnectionTest.java +++ b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireConnectionTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.core.protocol.openwire.amq; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; @@ -45,11 +47,9 @@ import org.apache.activemq.command.SessionInfo; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.openwire.OpenWireFormat; import org.apache.activemq.util.ByteSequence; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertTrue; - public class OpenWireConnectionTest { @Test @@ -148,11 +148,11 @@ public class OpenWireConnectionTest { openWireConnection.bufferReceived(openWireConnection, sessionInfoBuffer); openWireConnection.bufferReceived(openWireConnection, producerInfoBuffer); - assertTrue("fail on ok response check, iteration: " + i, okResponses.await(10, TimeUnit.SECONDS)); + assertTrue(okResponses.await(10, TimeUnit.SECONDS), "fail on ok response check, iteration: " + i); openWireConnection.bufferReceived(openWireConnection, removeInfoBuffer); - assertTrue("fail on ok response check with remove, iteration: " + i, okResponsesWithRemove.await(10, TimeUnit.SECONDS)); + assertTrue(okResponsesWithRemove.await(10, TimeUnit.SECONDS), "fail on ok response check with remove, iteration: " + i); wireFormatInfoBuffer.resetReaderIndex(); connectionInfoBuffer.resetReaderIndex(); diff --git a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireProtocolManagerTest.java b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireProtocolManagerTest.java index 45b52f8a84..723694587f 100644 --- a/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireProtocolManagerTest.java +++ b/artemis-protocols/artemis-openwire-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/openwire/amq/OpenWireProtocolManagerTest.java @@ -36,7 +36,7 @@ import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionInfo; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class OpenWireProtocolManagerTest { diff --git a/artemis-protocols/artemis-stomp-protocol/pom.xml b/artemis-protocols/artemis-stomp-protocol/pom.xml index dea7736f40..25287c5754 100644 --- a/artemis-protocols/artemis-stomp-protocol/pom.xml +++ b/artemis-protocols/artemis-stomp-protocol/pom.xml @@ -81,8 +81,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-protocols/artemis-stomp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/stomp/StompLogBundlesTest.java b/artemis-protocols/artemis-stomp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/stomp/StompLogBundlesTest.java index 6d0350ffa5..39eb588247 100644 --- a/artemis-protocols/artemis-stomp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/stomp/StompLogBundlesTest.java +++ b/artemis-protocols/artemis-stomp-protocol/src/test/java/org/apache/activemq/artemis/core/protocol/stomp/StompLogBundlesTest.java @@ -16,26 +16,26 @@ */ package org.apache.activemq.artemis.core.protocol.stomp; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class StompLogBundlesTest { private static final String LOGGER_NAME = ActiveMQStompProtocolLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } @@ -55,7 +55,7 @@ public class StompLogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ339001")); - assertTrue("unexpected message: " + message, message.contains("destinationBreadcrumb")); + assertTrue(message.startsWith("AMQ339001"), "unexpected message: " + message); + assertTrue(message.contains("destinationBreadcrumb"), "unexpected message: " + message); } } diff --git a/artemis-ra/pom.xml b/artemis-ra/pom.xml index 3f2f9c88ad..f0794b4452 100644 --- a/artemis-ra/pom.xml +++ b/artemis-ra/pom.xml @@ -90,8 +90,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-ra/src/test/java/org/apache/activemq/artemis/ra/RALogBundlesTest.java b/artemis-ra/src/test/java/org/apache/activemq/artemis/ra/RALogBundlesTest.java index 35b9bb770a..c1dbf24c31 100644 --- a/artemis-ra/src/test/java/org/apache/activemq/artemis/ra/RALogBundlesTest.java +++ b/artemis-ra/src/test/java/org/apache/activemq/artemis/ra/RALogBundlesTest.java @@ -16,28 +16,28 @@ */ package org.apache.activemq.artemis.ra; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import javax.jms.JMSRuntimeException; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class RALogBundlesTest { private static final String LOGGER_NAME = ActiveMQRALogger.class.getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } @@ -58,7 +58,7 @@ public class RALogBundlesTest { String message = e.getMessage(); assertNotNull(message); - assertTrue("unexpected message: " + message, message.startsWith("AMQ159006")); - assertTrue("unexpected message: " + message, message.contains(String.valueOf(invalidAckMode))); + assertTrue(message.startsWith("AMQ159006"), "unexpected message: " + message); + assertTrue(message.contains(String.valueOf(invalidAckMode)), "unexpected message: " + message); } } diff --git a/artemis-selector/pom.xml b/artemis-selector/pom.xml index 21bfdd2b82..fc391b51b3 100644 --- a/artemis-selector/pom.xml +++ b/artemis-selector/pom.xml @@ -34,8 +34,13 @@ artemis-commons - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java index 2ad042797d..e77d363f43 100755 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorParserTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.selector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.selector.filter.BooleanExpression; import org.apache.activemq.artemis.selector.filter.ComparisonExpression; import org.apache.activemq.artemis.selector.filter.Expression; @@ -23,10 +26,10 @@ import org.apache.activemq.artemis.selector.filter.LogicExpression; import org.apache.activemq.artemis.selector.filter.PropertyExpression; import org.apache.activemq.artemis.selector.filter.XPathExpression; import org.apache.activemq.artemis.selector.impl.SelectorParser; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import java.lang.invoke.MethodHandles; public class SelectorParserTest { @@ -40,7 +43,7 @@ public class SelectorParserTest { @Test public void testParseXPath() throws Exception { BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'"); - Assert.assertTrue("Created XPath expression", filter instanceof XPathExpression); + assertTrue(filter instanceof XPathExpression, "Created XPath expression"); info("Expression: " + filter); } @@ -53,13 +56,13 @@ public class SelectorParserTest { info("Parsing: " + value); BooleanExpression andExpression = parse(value); - Assert.assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression); + assertTrue(andExpression instanceof LogicExpression, "Created LogicExpression expression"); LogicExpression logicExpression = (LogicExpression) andExpression; Expression left = logicExpression.getLeft(); Expression right = logicExpression.getRight(); - Assert.assertTrue("Left is a binary filter", left instanceof ComparisonExpression); - Assert.assertTrue("Right is a binary filter", right instanceof ComparisonExpression); + assertTrue(left instanceof ComparisonExpression, "Left is a binary filter"); + assertTrue(right instanceof ComparisonExpression, "Right is a binary filter"); ComparisonExpression leftCompare = (ComparisonExpression) left; ComparisonExpression rightCompare = (ComparisonExpression) right; assertPropertyExpression("left", leftCompare.getLeft(), "x"); @@ -68,9 +71,9 @@ public class SelectorParserTest { } protected void assertPropertyExpression(String message, Expression expression, String expected) { - Assert.assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression); + assertTrue(expression instanceof PropertyExpression, message + ". Must be PropertyExpression"); PropertyExpression propExp = (PropertyExpression) expression; - Assert.assertEquals(message + ". Property name", expected, propExp.getName()); + assertEquals(expected, propExp.getName(), message + ". Property name"); } protected BooleanExpression parse(String text) throws Exception { diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java index 9e2f5303a3..0e2971f002 100755 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/SelectorTest.java @@ -16,11 +16,14 @@ */ package org.apache.activemq.artemis.selector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.activemq.artemis.selector.filter.BooleanExpression; import org.apache.activemq.artemis.selector.filter.FilterException; import org.apache.activemq.artemis.selector.impl.SelectorParser; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SelectorTest { @@ -419,16 +422,16 @@ public class SelectorTest { protected void assertInvalidSelector(MockMessage message, String text) { try { SelectorParser.parse(text); - Assert.fail("Created a valid selector"); + fail("Created a valid selector"); } catch (FilterException e) { } } protected void assertSelector(MockMessage message, String text, boolean expected) throws FilterException { BooleanExpression selector = SelectorParser.parse(text); - Assert.assertTrue("Created a valid selector", selector != null); + assertTrue(selector != null, "Created a valid selector"); boolean value = selector.matches(message); - Assert.assertEquals("Selector for: " + text, expected, value); + assertEquals(expected, value, "Selector for: " + text); } protected MockMessage createMessage(String subject) { diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/UnknownHandlingSelectorTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/UnknownHandlingSelectorTest.java index fa5a08565b..335facbbb1 100644 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/UnknownHandlingSelectorTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/UnknownHandlingSelectorTest.java @@ -16,18 +16,20 @@ */ package org.apache.activemq.artemis.selector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.selector.filter.BooleanExpression; import org.apache.activemq.artemis.selector.filter.FilterException; import org.apache.activemq.artemis.selector.impl.SelectorParser; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class UnknownHandlingSelectorTest { private MockMessage message; - @Before + @BeforeEach public void setUp() throws Exception { message = new MockMessage(); message.setDestination("FOO.BAR"); @@ -164,9 +166,9 @@ public class UnknownHandlingSelectorTest { protected void assertSelector(String text, boolean expected) throws FilterException { BooleanExpression selector = SelectorParser.parse(text); - Assert.assertTrue("Created a valid selector", selector != null); + assertTrue(selector != null, "Created a valid selector"); boolean value = selector.matches(message); - Assert.assertEquals("Selector for: " + text, expected, value); + assertEquals(expected, value, "Selector for: " + text); } private static String not(String selector) { diff --git a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/filter/UnaryExpressionTest.java b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/filter/UnaryExpressionTest.java index 8f1b1a19bc..e5b72732e2 100755 --- a/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/filter/UnaryExpressionTest.java +++ b/artemis-selector/src/test/java/org/apache/activemq/artemis/selector/filter/UnaryExpressionTest.java @@ -16,11 +16,13 @@ */ package org.apache.activemq.artemis.selector.filter; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Collections; import org.apache.activemq.artemis.selector.impl.SelectorParser; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class UnaryExpressionTest { @@ -28,17 +30,17 @@ public class UnaryExpressionTest { public void testEquals() throws Exception { BooleanExpression expr1 = UnaryExpression.createNOT(SelectorParser.parse("x = 1")); BooleanExpression expr2 = UnaryExpression.createNOT(SelectorParser.parse("x = 1")); - Assert.assertTrue("Created unary expression 1", expr1 instanceof UnaryExpression); - Assert.assertTrue("Created unary expression 2", expr2 instanceof UnaryExpression); - Assert.assertEquals("Unary expressions are equal", expr1, expr2); + assertTrue(expr1 instanceof UnaryExpression, "Created unary expression 1"); + assertTrue(expr2 instanceof UnaryExpression, "Created unary expression 2"); + assertEquals(expr1, expr2, "Unary expressions are equal"); } @Test public void testInExpressionToString() throws Exception { BooleanExpression expr; expr = UnaryExpression.createInExpression(new PropertyExpression("foo"), Collections.singletonList("bar"), false); - Assert.assertTrue(expr.toString().matches("foo\\s+IN\\s+.*bar.*")); + assertTrue(expr.toString().matches("foo\\s+IN\\s+.*bar.*")); expr = UnaryExpression.createInExpression(new PropertyExpression("foo"), Collections.emptyList(), false); - Assert.assertTrue(expr.toString().matches("foo\\s+IN\\s+.*")); + assertTrue(expr.toString().matches("foo\\s+IN\\s+.*")); } } diff --git a/artemis-server-osgi/pom.xml b/artemis-server-osgi/pom.xml index 29605dc93a..6a25db5244 100644 --- a/artemis-server-osgi/pom.xml +++ b/artemis-server-osgi/pom.xml @@ -83,8 +83,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/OsgiLogBundleTest.java b/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/OsgiLogBundleTest.java index 6db373dc26..1719ef68bd 100644 --- a/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/OsgiLogBundleTest.java +++ b/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/OsgiLogBundleTest.java @@ -16,25 +16,25 @@ */ package org.apache.activemq.artemis.osgi; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.logs.AssertionLoggerHandler.LogLevel; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class OsgiLogBundleTest { private static final String LOGGER_NAME = ActiveMQOsgiLogger.class.getPackage().getName(); private static LogLevel origLevel; - @BeforeClass + @BeforeAll public static void setLogLevel() { origLevel = AssertionLoggerHandler.setLevel(LOGGER_NAME, LogLevel.INFO); } - @AfterClass + @AfterAll public static void restoreLogLevel() throws Exception { AssertionLoggerHandler.setLevel(LOGGER_NAME, origLevel); } diff --git a/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/ProtocolTrackerTest.java b/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/ProtocolTrackerTest.java index 97ee3ad910..b9fbf1fe24 100644 --- a/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/ProtocolTrackerTest.java +++ b/artemis-server-osgi/src/test/java/org/apache/activemq/artemis/osgi/ProtocolTrackerTest.java @@ -20,7 +20,7 @@ import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManagerFactory; import org.easymock.EasyMock; import org.easymock.IMocksControl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; diff --git a/artemis-server/pom.xml b/artemis-server/pom.xml index 092c424555..f37fcc8ea7 100644 --- a/artemis-server/pom.xml +++ b/artemis-server/pom.xml @@ -168,8 +168,18 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.vintage + junit-vintage-engine test @@ -237,6 +247,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/AbstractLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/AbstractLeakTest.java index 48f2f90c03..c2046a7106 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/AbstractLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/AbstractLeakTest.java @@ -23,11 +23,11 @@ import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.actors.OrderedExecutor; -import org.junit.AfterClass; +import org.junit.jupiter.api.AfterAll; public abstract class AbstractLeakTest extends ActiveMQTestBase { - @AfterClass + @AfterAll public static void clearStatus() throws Exception { ServerStatus.clear(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ClientLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ClientLeakTest.java index d7d0f1ed3a..0c862de1ef 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ClientLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ClientLeakTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -33,17 +38,13 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.qpid.proton.engine.impl.ReceiverImpl; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; - // This test spawns the server as a separate VM // as we need to count exclusively client objects from qpid-proton public class ClientLeakTest extends AbstractLeakTest { @@ -68,13 +69,13 @@ public class ClientLeakTest extends AbstractLeakTest { } - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } @Override - @Before + @BeforeEach public void setUp() throws Exception { serverProcess = SpawnedVMSupport.spawnVM(ClientLeakTest.class.getName()); runAfter(serverProcess::destroyForcibly); @@ -96,10 +97,10 @@ public class ClientLeakTest extends AbstractLeakTest { } while (success == false && System.currentTimeMillis() < time); - Assert.assertTrue(success); + assertTrue(success); } - @After + @AfterEach public void stopServer() throws Exception { serverProcess.destroyForcibly(); } @@ -124,7 +125,7 @@ public class ClientLeakTest extends AbstractLeakTest { MessageConsumer consumer = session.createConsumer(session.createQueue("test")); connection.start(); Message message = consumer.receive(1000); - Assert.assertNotNull(message); + assertNotNull(message); session.commit(); // consumer.close(); // uncomment this and the test will pass. session.close(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionDroppedLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionDroppedLeakTest.java index 54ce77cc2d..f617fa1984 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionDroppedLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionDroppedLeakTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -41,18 +46,13 @@ import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.AddressInfo; import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.tests.util.CFUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; - public class ConnectionDroppedLeakTest extends AbstractLeakTest { private ConnectionFactory createConnectionFactory(String protocol) { @@ -71,12 +71,12 @@ public class ConnectionDroppedLeakTest extends AbstractLeakTest { Queue serverQueue; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @After + @AfterEach public void validateServer() throws Exception { CheckLeak checkLeak = new CheckLeak(); @@ -96,7 +96,7 @@ public class ConnectionDroppedLeakTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { server = createServer(true, createDefaultConfig(1, true)); server.getConfiguration().setJournalPoolFiles(4).setJournalMinFiles(2); @@ -185,13 +185,13 @@ public class ConnectionDroppedLeakTest extends AbstractLeakTest { } }); - Assert.assertTrue(latchReceived.await(10, TimeUnit.SECONDS)); + assertTrue(latchReceived.await(10, TimeUnit.SECONDS)); server.getRemotingService().getConnections().forEach(r -> { r.fail(new ActiveMQException("it's a simulation")); }); - Assert.assertTrue(latchDone.await(30, TimeUnit.SECONDS)); + assertTrue(latchDone.await(30, TimeUnit.SECONDS)); running.set(false); serverQueue.deleteAllReferences(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionExitTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionExitTest.java index a7ac9273ef..41575f3b20 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionExitTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionExitTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; @@ -43,17 +47,13 @@ import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; - public class ConnectionExitTest extends AbstractLeakTest { private static final String EXIT_TEXT = "EXIT"; @@ -70,12 +70,12 @@ public class ConnectionExitTest extends AbstractLeakTest { Queue serverQueue; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @After + @AfterEach public void validateServer() throws Exception { CheckLeak checkLeak = new CheckLeak(); @@ -95,7 +95,7 @@ public class ConnectionExitTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { server = createServer(false, createDefaultConfig(1, true)); server.getConfiguration().clearAcceptorConfigurations(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionLeakTest.java index 9084581dd1..bd7ed2c274 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ConnectionLeakTest.java @@ -16,6 +16,14 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -47,18 +55,13 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.collections.LinkedListImpl; import org.apache.qpid.proton.engine.impl.DeliveryImpl; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; - public class ConnectionLeakTest extends AbstractLeakTest { private ConnectionFactory createConnectionFactory(String protocol) { @@ -73,12 +76,12 @@ public class ConnectionLeakTest extends AbstractLeakTest { ActiveMQServer server; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @After + @AfterEach public void validateServer() throws Exception { CheckLeak checkLeak = new CheckLeak(); @@ -97,7 +100,7 @@ public class ConnectionLeakTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { server = createServer(true, createDefaultConfig(1, true)); server.getConfiguration().setJournalPoolFiles(4).setJournalMinFiles(2); @@ -169,12 +172,12 @@ public class ConnectionLeakTest extends AbstractLeakTest { for (int msg = 0; msg < MESSAGES; msg++) { TextMessage m = (TextMessage) sourceConsumer.receive(5000); - Assert.assertNotNull(m); - Assert.assertEquals("hello " + msg, m.getText()); - Assert.assertEquals(msg, m.getIntProperty("i")); + assertNotNull(m); + assertEquals("hello " + msg, m.getText()); + assertEquals(msg, m.getIntProperty("i")); targetProducer.send(m); } - Assert.assertNull(sourceConsumer.receiveNoWait()); + assertNull(sourceConsumer.receiveNoWait()); consumerSession.commit(); Wait.assertTrue(() -> validateClosedConsumers(checkLeak)); @@ -192,10 +195,10 @@ public class ConnectionLeakTest extends AbstractLeakTest { targetConnection.start(); for (int msgI = 0; msgI < REPEATS * MESSAGES; msgI++) { - Assert.assertNotNull(consumer.receive(5000)); + assertNotNull(consumer.receive(5000)); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); assertMemory(new CheckLeak(), 0, DeliveryImpl.class.getName()); Wait.assertTrue(() -> validateClosedConsumers(checkLeak)); consumer = null; @@ -304,8 +307,8 @@ public class ConnectionLeakTest extends AbstractLeakTest { }); } - Assert.assertTrue(done.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, errors.get()); + assertTrue(done.await(10, TimeUnit.SECONDS)); + assertEquals(0, errors.get()); Wait.assertEquals(0, serverQueue::getMessageCount); assertMemory(checkLeak, 0, 5, 1, AMQPStandardMessage.class.getName()); assertMemory(checkLeak, 0, 5, 1, DeliveryImpl.class.getName()); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/CoreClientLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/CoreClientLeakTest.java index 8db99753e1..746e9a6daa 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/CoreClientLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/CoreClientLeakTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import io.github.checkleak.core.CheckLeak; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; @@ -30,24 +33,22 @@ import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.actors.OrderedExecutor; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class CoreClientLeakTest extends AbstractLeakTest { ActiveMQServer server; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @AfterClass + @AfterAll public static void afterClass() throws Exception { ServerStatus.clear(); MemoryAssertions.assertMemory(new CheckLeak(), 0, ActiveMQServerImpl.class.getName()); @@ -56,7 +57,7 @@ public class CoreClientLeakTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); server = createServer(true, createDefaultConfig(1, true)); @@ -65,7 +66,7 @@ public class CoreClientLeakTest extends AbstractLeakTest { } @Override - @After + @AfterEach public void tearDown() throws Exception { super.tearDown(); server.stop(); @@ -109,7 +110,7 @@ public class CoreClientLeakTest extends AbstractLeakTest { // I am allowing extra 50 strings created elsewhere. it should not happen at the time I created this test but I am allowing this just in case if (lastNumberOfSimpleStrings > initialSimpleString + 50) { - Assert.fail("There are " + lastNumberOfSimpleStrings + " while there was " + initialSimpleString + " SimpleString objects initially"); + fail("There are " + lastNumberOfSimpleStrings + " while there was " + initialSimpleString + " SimpleString objects initially"); } } finally { diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/HandlerBaseLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/HandlerBaseLeakTest.java index 752cc9d00c..5e55faa15b 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/HandlerBaseLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/HandlerBaseLeakTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.invoke.MethodHandles; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; @@ -27,8 +29,7 @@ import java.util.concurrent.TimeUnit; import io.github.checkleak.core.CheckLeak; import org.apache.activemq.artemis.utils.actors.OrderedExecutor; import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +54,7 @@ public class HandlerBaseLeakTest extends AbstractLeakTest { CountDownLatch latch = new CountDownLatch(1); Executor executor = factory.getExecutor(); executor.execute(latch::countDown); - Assert.assertTrue(latch.await(1, TimeUnit.MINUTES)); + assertTrue(latch.await(1, TimeUnit.MINUTES)); } } diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/JournalLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/JournalLeakTest.java index 1e413d8798..366e8f9770 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/JournalLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/JournalLeakTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -39,18 +46,13 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.tests.util.CFUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; - /* at the time this test was written JournalFileImpl was leaking through JournalFileImpl::negative creating a linked list (or leaked-list, pun intended) */ public class JournalLeakTest extends AbstractLeakTest { @@ -58,12 +60,12 @@ public class JournalLeakTest extends AbstractLeakTest { ActiveMQServer server; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @After + @AfterEach public void validateServer() throws Exception { CheckLeak checkLeak = new CheckLeak(); @@ -82,7 +84,7 @@ public class JournalLeakTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { server = createServer(true, createDefaultConfig(1, true)); server.getConfiguration().setJournalPoolFiles(4).setJournalMinFiles(2); @@ -126,8 +128,8 @@ public class JournalLeakTest extends AbstractLeakTest { for (int i = 0; i < MESSAGES; i++) { Message message = consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(i, message.getIntProperty("i")); + assertNotNull(message); + assertEquals(i, message.getIntProperty("i")); if (i > 0 && i % 100 == 0) { session.commit(); } @@ -168,8 +170,8 @@ public class JournalLeakTest extends AbstractLeakTest { } }); - Assert.assertTrue(done.await(1, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(done.await(1, TimeUnit.MINUTES)); + assertEquals(0, errors.get()); basicMemoryAsserts(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/LinkedListMemoryTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/LinkedListMemoryTest.java index 0c13cb8cf3..7420b33540 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/LinkedListMemoryTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/LinkedListMemoryTest.java @@ -24,7 +24,7 @@ import java.util.Random; import io.github.checkleak.core.CheckLeak; import org.apache.activemq.artemis.utils.collections.LinkedListImpl; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MemoryAssertions.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MemoryAssertions.java index e31ce56ef3..a8449c13d8 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MemoryAssertions.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MemoryAssertions.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.PrintWriter; import java.io.StringWriter; import java.lang.invoke.MethodHandles; @@ -37,7 +40,6 @@ import org.apache.activemq.artemis.protocol.amqp.proton.AMQPSessionContext; import org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerReceiverContext; import org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerSenderContext; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,7 +85,7 @@ public class MemoryAssertions { String report = checkLeak.exploreObjectReferences(maxLevel, maxObjects, true, objects); logger.info(report); - Assert.fail("Class " + clazz + " has leaked " + objects.length + " objects\n" + report); + fail("Class " + clazz + " has leaked " + objects.length + " objects\n" + report); } } @@ -108,7 +110,7 @@ public class MemoryAssertions { } } - Assert.assertFalse(stringWriter.toString(), failed); + assertFalse(failed, stringWriter.toString()); } private static List getClassList(Class clazz) { diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MessageReferenceLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MessageReferenceLeakTest.java index d93012a7b2..a086e049cb 100755 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MessageReferenceLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/MessageReferenceLeakTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import io.github.checkleak.core.CheckLeak; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.QueueConfiguration; @@ -31,10 +36,10 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,13 +57,13 @@ public class MessageReferenceLeakTest extends AbstractLeakTest { server.start(); } - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } @Override - @Before + @BeforeEach public void setUp() throws Exception { startServer(); ServerLocator locator = addServerLocator(createInVMNonHALocator().setBlockOnNonDurableSend(true).setConsumerWindowSize(0)); @@ -67,6 +72,7 @@ public class MessageReferenceLeakTest extends AbstractLeakTest { session.start(); } + @AfterEach @Override public void tearDown() throws Exception { super.tearDown(); diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/PagingLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/PagingLeakTest.java index 74653be380..8eabd4d4f2 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/PagingLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/PagingLeakTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; +import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -41,18 +47,13 @@ import org.apache.activemq.artemis.core.server.impl.AddressInfo; import org.apache.activemq.artemis.core.server.impl.ServerStatus; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory; -import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.basicMemoryAsserts; - /* at the time this test was written JournalFileImpl was leaking through JournalFileImpl::negative creating a linked list (or leaked-list, pun intended) */ public class PagingLeakTest extends AbstractLeakTest { @@ -60,12 +61,12 @@ public class PagingLeakTest extends AbstractLeakTest { ActiveMQServer server; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } - @After + @AfterEach public void validateServer() throws Exception { CheckLeak checkLeak = new CheckLeak(); @@ -84,7 +85,7 @@ public class PagingLeakTest extends AbstractLeakTest { } @Override - @Before + @BeforeEach public void setUp() throws Exception { server = createServer(true, createDefaultConfig(1, true)); server.getConfiguration().setJournalPoolFiles(4).setJournalMinFiles(2); @@ -146,7 +147,7 @@ public class PagingLeakTest extends AbstractLeakTest { CheckLeak checkLeak = new CheckLeak(); // no acks done, no PagePosition recorded - Assert.assertEquals(0, checkLeak.getAllObjects(PagePositionImpl.class).length); + assertEquals(0, checkLeak.getAllObjects(PagePositionImpl.class).length); serverQueue.getPagingStore().disableCleanup(); @@ -157,7 +158,7 @@ public class PagingLeakTest extends AbstractLeakTest { for (int i = 0; i < MESSAGES; i++) { Message message = consumer.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); if (i > 0 && i % COMMIT_INTERVAL == 0) { session.commit(); } diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ProducerBlockedLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ProducerBlockedLeakTest.java index d843e6fdee..3535aa88ba 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ProducerBlockedLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/ProducerBlockedLeakTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; @@ -41,11 +44,9 @@ import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,13 +59,13 @@ public class ProducerBlockedLeakTest extends AbstractLeakTest { ActiveMQServer server; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); server = createServer(true, createDefaultConfig(1, true)); @@ -113,7 +114,7 @@ public class ProducerBlockedLeakTest extends AbstractLeakTest { Wait.assertTrue(() -> loggerHandler.findText("AMQ222183"), 5000, 10); process.destroyForcibly(); - Assert.assertTrue(process.waitFor(10, TimeUnit.SECONDS)); + assertTrue(process.waitFor(10, TimeUnit.SECONDS)); // Making sure there are no connections anywhere in Acceptors or RemotingService. // Just to speed up the test especially in OpenWire diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RedistributorLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RedistributorLeakTest.java index 10b9381c99..5632935e3e 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RedistributorLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RedistributorLeakTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -37,11 +41,10 @@ import org.apache.activemq.artemis.core.server.impl.QueueImpl; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.collections.LinkedListImpl; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,17 +59,18 @@ public class RedistributorLeakTest extends AbstractLeakTest { server.start(); } - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - Assume.assumeTrue(CheckLeak.isLoaded()); + assumeTrue(CheckLeak.isLoaded()); } @Override - @Before + @BeforeEach public void setUp() throws Exception { startServer(); } + @AfterEach @Override public void tearDown() throws Exception { super.tearDown(); @@ -102,7 +106,7 @@ public class RedistributorLeakTest extends AbstractLeakTest { for (int i = 0; i < NUMBER_OF_MESSAGES / 10; i++) { MessageConsumer consumer = session.createConsumer(jmsQueue); Message message = consumer.receive(1000); - Assert.assertNotNull(message); + assertNotNull(message); queue.flushExecutor(); consumer.close(); } @@ -110,7 +114,7 @@ public class RedistributorLeakTest extends AbstractLeakTest { } int numberOfIterators = checkLeak.getAllObjects(LinkedListImpl.Iterator.class).length; - Assert.assertEquals(0, numberOfIterators); + assertEquals(0, numberOfIterators); // Adding and cancelling a few redistributors for (int i = 0; i < 10; i++) { @@ -121,7 +125,7 @@ public class RedistributorLeakTest extends AbstractLeakTest { } numberOfIterators = checkLeak.getAllObjects(LinkedListImpl.Iterator.class).length; - Assert.assertEquals("Redistributors are leaking " + LinkedListImpl.Iterator.class.getName(), 0, numberOfIterators); + assertEquals(0, numberOfIterators, "Redistributors are leaking " + LinkedListImpl.Iterator.class.getName()); try (Connection connection = factory.createConnection()) { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); @@ -130,14 +134,14 @@ public class RedistributorLeakTest extends AbstractLeakTest { MessageConsumer consumer = session.createConsumer(destination); for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("hello " + i, message.getText()); + assertNotNull(message); + assertEquals("hello " + i, message.getText()); } session.commit(); } - Assert.assertEquals(0, checkLeak.getAllObjects(MessageReferenceImpl.class).length); - Assert.assertEquals(0, checkLeak.getAllObjects(CoreMessage.class).length); + assertEquals(0, checkLeak.getAllObjects(MessageReferenceImpl.class).length); + assertEquals(0, checkLeak.getAllObjects(CoreMessage.class).length); } } \ No newline at end of file diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RefCountMessageLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RefCountMessageLeakTest.java index 0971accad9..ebf1ee3bce 100644 --- a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RefCountMessageLeakTest.java +++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/RefCountMessageLeakTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.leak; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.TimeUnit; import io.github.checkleak.core.CheckLeak; @@ -24,8 +28,7 @@ import org.apache.activemq.artemis.api.core.RefCountMessage; import org.apache.activemq.artemis.api.core.RefCountMessageAccessor; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.ReusableLatch; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RefCountMessageLeakTest extends AbstractLeakTest { @@ -59,10 +62,10 @@ public class RefCountMessageLeakTest extends AbstractLeakTest { RefCountMessageAccessor.setRunOnLeak(message, latchLeaked::countDown); message = null; // I know it's null, I'm just doing this to make sure there are no optimizations from the JVM delaying the GC cleanup - Assert.assertNull(message); + assertNull(message); MemoryAssertions.assertMemory(new CheckLeak(), 0, RefCountMessage.class.getName()); - Assert.assertTrue(latchLeaked.await(1, TimeUnit.SECONDS)); + assertTrue(latchLeaked.await(1, TimeUnit.SECONDS)); DebugMessage message2 = new DebugMessage(strMessageFired); message2.refUp(); @@ -72,9 +75,9 @@ public class RefCountMessageLeakTest extends AbstractLeakTest { message2.fired(); message2 = null; // I know it's null, I'm just doing this to make sure there are no optimizations from the JVM delaying the GC cleanup - Assert.assertNull(message2); + assertNull(message2); MemoryAssertions.assertMemory(new CheckLeak(), 0, RefCountMessage.class.getName()); - Assert.assertFalse(latchLeaked.await(100, TimeUnit.MILLISECONDS)); + assertFalse(latchLeaked.await(100, TimeUnit.MILLISECONDS)); } } \ No newline at end of file diff --git a/tests/performance-tests/pom.xml b/tests/performance-tests/pom.xml index b93ed72902..c2bd82f83f 100644 --- a/tests/performance-tests/pom.xml +++ b/tests/performance-tests/pom.xml @@ -62,8 +62,14 @@ artemis-jms-client - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test @@ -87,6 +93,7 @@ ${project.version} test + diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java index 9bcb5dc2bb..5a76d1302a 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/JournalImplTestUnit.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.performance.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import org.apache.activemq.artemis.core.journal.Journal; @@ -25,9 +27,8 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.unit.core.journal.impl.JournalImplTestBase; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -37,11 +38,11 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override - @After + @AfterEach public void tearDown() throws Exception { super.tearDown(); - Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); + assertEquals(0, LibaioContext.getTotalMaxIO()); } @Test @@ -164,7 +165,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase { startJournal(); journal.load(new ArrayList(), new ArrayList(), null); - Assert.assertEquals(NUMBER_OF_RECORDS / 2, journal.getIDMapSize()); + assertEquals(NUMBER_OF_RECORDS / 2, journal.getIDMapSize()); stopJournal(); } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java index ded60cd9e9..3763c501e8 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/journal/RealJournalImplAIOTest.java @@ -20,8 +20,8 @@ import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -30,13 +30,13 @@ public class RealJournalImplAIOTest extends JournalImplTestUnit { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @BeforeClass + @BeforeAll public static void hasAIO() { - org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); + org.junit.jupiter.api.Assumptions.assumeTrue(AIOSequentialFileFactory.isSupported(), "Test case needs AIO to run"); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java index b0b52a5b60..4892ff5ef2 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/paging/MeasurePagingMultiThreadTest.java @@ -30,7 +30,7 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MeasurePagingMultiThreadTest extends ActiveMQTestBase { diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java index f939eaaac2..b1251a0875 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/AbstractSendReceivePerfTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.performance.sends; +import static org.junit.jupiter.api.Assertions.assertFalse; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; @@ -35,8 +37,7 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.JMSTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; /** * Client-ack time @@ -49,7 +50,7 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase { protected AtomicBoolean running = new AtomicBoolean(true); @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -74,8 +75,8 @@ public abstract class AbstractSendReceivePerfTest extends JMSTestBase { private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(AbstractSendReceivePerfTest.class.getName()); - @Test - public void testSendReceive() throws Exception { + // Subclasses can add a test which calls this + protected void doSendReceiveTestImpl() throws Exception { long numberOfSamples = Long.getLong("HORNETQ_TEST_SAMPLES", 1000); MessageReceiver receiver = new MessageReceiver(Q_NAME, numberOfSamples); diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java index cd37e2dc19..68ac808964 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/ClientACKPerf.java @@ -25,13 +25,15 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class ClientACKPerf extends AbstractSendReceivePerfTest { - @Parameterized.Parameters(name = "batchSize={0}") + @Parameters(name = "batchSize={0}") public static Collection data() { List list = Arrays.asList(new Object[][]{{1}, {2000}}); @@ -103,4 +105,8 @@ public class ClientACKPerf extends AbstractSendReceivePerfTest { } + @TestTemplate + public void testSendReceive() throws Exception { + super.doSendReceiveTestImpl(); + } } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java index 8b02c56e49..519627949b 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/MeasureCommitPerfTest.java @@ -20,6 +20,8 @@ import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; +import org.junit.jupiter.api.Test; + public class MeasureCommitPerfTest extends AbstractSendReceivePerfTest { @Override @@ -65,4 +67,8 @@ public class MeasureCommitPerfTest extends AbstractSendReceivePerfTest { } + @Test + public void testSendReceive() throws Exception { + super.doSendReceiveTestImpl(); + } } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java index 9a389ef337..04183a7b28 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/sends/PreACKPerf.java @@ -23,6 +23,7 @@ import javax.jms.Queue; import javax.jms.Session; import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants; +import org.junit.jupiter.api.Test; public class PreACKPerf extends AbstractSendReceivePerfTest { @@ -74,4 +75,8 @@ public class PreACKPerf extends AbstractSendReceivePerfTest { } + @Test + public void testSendReceive() throws Exception { + super.doSendReceiveTestImpl(); + } } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/PersistMultiThreadTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/PersistMultiThreadTest.java index e588dd7e6e..0a9c593270 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/PersistMultiThreadTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/PersistMultiThreadTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.performance.storage; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import java.util.Collection; import java.util.concurrent.CountDownLatch; @@ -47,8 +49,7 @@ import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; import org.apache.activemq.artemis.utils.runnables.AtomicRunnable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PersistMultiThreadTest extends ActiveMQTestBase { @@ -112,11 +113,11 @@ public class PersistMultiThreadTest extends ActiveMQTestBase { for (MyThread t : threads) { t.join(); - Assert.assertEquals(0, t.errors.get()); + assertEquals(0, t.errors.get()); } deleteThread.join(); - Assert.assertEquals(0, deleteThread.errors.get()); + assertEquals(0, deleteThread.errors.get()); } diff --git a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/SendReceiveMultiThreadTest.java b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/SendReceiveMultiThreadTest.java index b65712a3eb..a394707856 100644 --- a/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/SendReceiveMultiThreadTest.java +++ b/tests/performance-tests/src/test/java/org/apache/activemq/artemis/tests/performance/storage/SendReceiveMultiThreadTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.performance.storage; +import static org.junit.jupiter.api.Assertions.assertEquals; + import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -38,8 +40,7 @@ import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.DefaultConnectionProperties; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SendReceiveMultiThreadTest extends ActiveMQTestBase { @@ -150,7 +151,7 @@ public class SendReceiveMultiThreadTest extends ActiveMQTestBase { t.start(); } - Assert.assertEquals(NUMBER_OF_THREADS, queue.getConsumerCount()); + assertEquals(NUMBER_OF_THREADS, queue.getConsumerCount()); alignFlag.await(); @@ -167,12 +168,12 @@ public class SendReceiveMultiThreadTest extends ActiveMQTestBase { for (ConsumerThread t : cthreads) { t.join(); - Assert.assertEquals(0, t.errors); + assertEquals(0, t.errors); } for (MyThread t : threads) { t.join(); - Assert.assertEquals(0, t.errors.get()); + assertEquals(0, t.errors.get()); } slowSending.interrupt(); diff --git a/tests/smoke-tests/pom.xml b/tests/smoke-tests/pom.xml index a87172629f..8e80cb9d65 100644 --- a/tests/smoke-tests/pom.xml +++ b/tests/smoke-tests/pom.xml @@ -82,8 +82,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/bridgeTransfer/BridgeTransferingTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/bridgeTransfer/BridgeTransferingTest.java index a3b47701bd..b75590c421 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/bridgeTransfer/BridgeTransferingTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/bridgeTransfer/BridgeTransferingTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.bridgeTransfer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -29,25 +33,25 @@ import java.util.Arrays; import java.util.Collection; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class BridgeTransferingTest extends SmokeTestBase { - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -96,12 +100,12 @@ public class BridgeTransferingTest extends SmokeTestBase { this.minlargeMessageSize = minlargeMessageSize; } - @Parameterized.Parameters(name = "protocol={0}, commitInterval={1}, killInterval={2}, numberOfMessages={3}, messageSize={4}, minLargeMessageSize={5}, KillBothServers={6}") + @Parameters(name = "protocol={0}, commitInterval={1}, killInterval={2}, numberOfMessages={3}, messageSize={4}, minLargeMessageSize={5}, KillBothServers={6}") public static Collection parameters() { return Arrays.asList(new Object[][]{{"CORE", 200, 1000, 10000, 15_000, 5000, true}, {"CORE", 200, 1000, 10000, 15_000, 5000, false}}); } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -110,13 +114,13 @@ public class BridgeTransferingTest extends SmokeTestBase { serverProcess2 = startServer(SERVER_NAME_1, 1, 30000); } - @After + @AfterEach public void stopServers() throws Exception { serverProcess2.destroyForcibly(); serverProcess.destroyForcibly(); } - @Test + @TestTemplate public void testTransfer() throws Exception { ConnectionFactory cf = CFUtil.createConnectionFactory(theprotocol, "tcp://localhost:61616"); ((ActiveMQConnectionFactory) cf).setMinLargeMessageSize(minlargeMessageSize); @@ -189,11 +193,11 @@ public class BridgeTransferingTest extends SmokeTestBase { logger.debug("consuming {}", i); } TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(body + " " + i, message.getText()); + assertNotNull(message); + assertEquals(body + " " + i, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionBridgeSecurityTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionBridgeSecurityTest.java index 4df25fad55..d7554a0c97 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionBridgeSecurityTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionBridgeSecurityTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -30,15 +34,14 @@ import java.io.File; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.apache.activemq.artemis.tests.util.CFUtil; public class BrokerConnectionBridgeSecurityTest extends SmokeTestBase { - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -63,7 +66,7 @@ public class BrokerConnectionBridgeSecurityTest extends SmokeTestBase { public static final String SERVER_NAME_A = "brokerConnect/bridgeSecurityA"; public static final String SERVER_NAME_B = "brokerConnect/bridgeSecurityB"; - @Before + @BeforeEach public void before() throws Exception { // no need to cleanup, these servers don't have persistence // start serverB first, after all ServerA needs it alive to create connections @@ -96,25 +99,25 @@ public class BrokerConnectionBridgeSecurityTest extends SmokeTestBase { for (int i = 0; i < 10; i++) { TextMessage message = (TextMessage) consumerB.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("toB", message.getText()); + assertNotNull(message); + assertEquals("toB", message.getText()); } MessageProducer producerB = sessionB.createProducer(queueToA); for (int i = 0; i < 10; i++) { producerB.send(sessionA.createTextMessage("toA")); } - Assert.assertNull(consumerB.receiveNoWait()); + assertNull(consumerB.receiveNoWait()); connectionA.start(); MessageConsumer consumerA = sessionA.createConsumer(queueToA); for (int i = 0; i < 10; i++) { TextMessage message = (TextMessage) consumerA.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("toA", message.getText()); + assertNotNull(message); + assertEquals("toA", message.getText()); } - Assert.assertNull(consumerA.receiveNoWait()); + assertNull(consumerA.receiveNoWait()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionMirrorSecurityTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionMirrorSecurityTest.java index d63ff35a4c..31e91adb78 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionMirrorSecurityTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/BrokerConnectionMirrorSecurityTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -31,17 +34,16 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class BrokerConnectionMirrorSecurityTest extends SmokeTestBase { public static final String SERVER_NAME_A = "brokerConnect/mirrorSecurityA"; public static final String SERVER_NAME_B = "brokerConnect/mirrorSecurityB"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -63,7 +65,7 @@ public class BrokerConnectionMirrorSecurityTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { // no need to cleanup, these servers don't have persistence // start serverB first, after all ServerA needs it alive to create connections @@ -95,8 +97,8 @@ public class BrokerConnectionMirrorSecurityTest extends SmokeTestBase { for (int i = 0; i < 10; i++) { TextMessage message = (TextMessage) consumerB.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("message", message.getText()); + assertNotNull(message); + assertEquals("message", message.getText()); } } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualFederationTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualFederationTest.java index 1a51467de8..4cbb27f163 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualFederationTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualFederationTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -32,16 +34,16 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class DualFederationTest extends SmokeTestBase { public static final String SERVER_NAME_A = "brokerConnect/federationA"; public static final String SERVER_NAME_B = "brokerConnect/federationB"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -66,7 +68,7 @@ public class DualFederationTest extends SmokeTestBase { Process processB; Process processA; - @Before + @BeforeEach public void beforeClass() throws Exception { cleanupData(SERVER_NAME_A); cleanupData(SERVER_NAME_B); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualMirrorNoContainerTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualMirrorNoContainerTest.java index b2d53de4bc..e342119a1b 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualMirrorNoContainerTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/DualMirrorNoContainerTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; @@ -36,10 +41,9 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class DualMirrorNoContainerTest extends SmokeTestBase { @@ -52,7 +56,7 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { Process processB; Process processA; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -73,7 +77,7 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { } } - @Before + @BeforeEach public void beforeClass() throws Exception { cleanupData(SERVER_NAME_A); cleanupData(SERVER_NAME_B); @@ -168,7 +172,7 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { connectionB.start(); receiveMessages(tx, sessionB, consumerB, 5, 9); - Assert.assertNull(consumerB.receiveNoWait()); + assertNull(consumerB.receiveNoWait()); sendMessages(tx, sessionB, producerB, 0, 19); receiveMessages(tx, sessionB, consumerB, 0, 9); @@ -182,7 +186,7 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { receiveMessages(tx, sessionA, consumerA, 10, 19); - Assert.assertNull(consumerA.receiveNoWait()); + assertNull(consumerA.receiveNoWait()); } } @@ -255,10 +259,10 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage)consumerB.receive(5_000); - Assert.assertNotNull("expected message at " + i, message); - Assert.assertEquals("message " + i + largeBuffer, message.getText()); + assertNotNull(message, "expected message at " + i); + assertEquals("message " + i + largeBuffer, message.getText()); } - Assert.assertNull(consumerB.receiveNoWait()); + assertNull(consumerB.receiveNoWait()); sessionB.rollback(); } @@ -278,15 +282,15 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i += 2) { //System.out.println("Received message on i=" + i); TextMessage message = (TextMessage)consumerB.receive(5_000); - Assert.assertNotNull("expected message at " + i, message); - Assert.assertEquals("message " + i + largeBuffer, message.getText()); + assertNotNull(message, "expected message at " + i); + assertEquals("message " + i + largeBuffer, message.getText()); if (op++ > 0 && op % FAILURE_INTERVAL == 0) { restartA(++restarted); } } - Assert.assertNull(consumerB.receiveNoWait()); + assertNull(consumerB.receiveNoWait()); } System.out.println("Restarted serverA " + restarted + " times"); @@ -305,15 +309,15 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { for (int i = 1; i < NUMBER_OF_MESSAGES; i += 2) { TextMessage message = (TextMessage)consumerA.receive(5_000); - Assert.assertNotNull("expected message at " + i, message); + assertNotNull(message, "expected message at " + i); // We should only have red left - Assert.assertEquals("Unexpected message at " + i + " with i=" + message.getIntProperty("i"), "red", message.getStringProperty("color")); - Assert.assertEquals("message " + i + largeBuffer, message.getText()); + assertEquals("red", message.getStringProperty("color"), "Unexpected message at " + i + " with i=" + message.getIntProperty("i")); + assertEquals("message " + i + largeBuffer, message.getText()); } sessionA.commit(); - Assert.assertNull(consumerA.receiveNoWait()); + assertNull(consumerA.receiveNoWait()); } Thread.sleep(5000); @@ -331,7 +335,7 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { TextMessage message = (TextMessage)consumerB.receiveNoWait(); if (message != null) { - Assert.fail("was expected null, however received " + message.getText()); + fail("was expected null, however received " + message.getText()); } } @@ -374,8 +378,8 @@ public class DualMirrorNoContainerTest extends SmokeTestBase { private void receiveMessages(boolean tx, Session session, MessageConsumer consumer, int start, int end) throws JMSException { for (int i = start; i <= end; i++) { TextMessage message = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("message " + i, message.getText()); + assertNotNull(message); + assertEquals("message " + i, message.getText()); } if (tx) session.commit(); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/MirroredSubscriptionTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/MirroredSubscriptionTest.java index 485229d69b..18cb5925ed 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/MirroredSubscriptionTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/MirroredSubscriptionTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; @@ -39,10 +43,9 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,7 +55,7 @@ public class MirroredSubscriptionTest extends SmokeTestBase { public static final String SERVER_NAME_B = "mirrored-subscriptions/broker2"; private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -77,7 +80,7 @@ public class MirroredSubscriptionTest extends SmokeTestBase { Process processB; Process processA; - @Before + @BeforeEach public void beforeClass() throws Exception { startServers(); @@ -150,7 +153,7 @@ public class MirroredSubscriptionTest extends SmokeTestBase { TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subscription" + clientID); for (int messageI = 0; messageI < NUMBER_OF_MESSAGES; messageI++) { TextMessage message = (TextMessage) subscriber.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); if (messageI % COMMIT_INTERVAL == 0) { session.commit(); logger.info("Received {} messages on receiver {}", messageI, clientID); @@ -169,7 +172,7 @@ public class MirroredSubscriptionTest extends SmokeTestBase { if (clientID == 0) { // The first execution will block until finished, we will then kill all the servers and make sure // all the counters are preserved. - Assert.assertTrue(threadDone.await(300, TimeUnit.SECONDS)); + assertTrue(threadDone.await(300, TimeUnit.SECONDS)); processA.destroyForcibly(); processB.destroyForcibly(); Wait.assertFalse(processA::isAlive); @@ -185,8 +188,8 @@ public class MirroredSubscriptionTest extends SmokeTestBase { } } - Assert.assertTrue(done.await(300, TimeUnit.SECONDS)); - Assert.assertEquals(0, errors.get()); + assertTrue(done.await(300, TimeUnit.SECONDS)); + assertEquals(0, errors.get()); checkMessages(0, CLIENTS, mainURI, secondURI); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/PagedMirrorSmokeTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/PagedMirrorSmokeTest.java index 3d68d63246..1a432a9197 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/PagedMirrorSmokeTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/brokerConnection/PagedMirrorSmokeTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.smoke.brokerConnection; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -34,10 +39,9 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class PagedMirrorSmokeTest extends SmokeTestBase { @@ -47,7 +51,7 @@ public class PagedMirrorSmokeTest extends SmokeTestBase { public static final String SERVER_NAME_A = "brokerConnect/pagedA"; public static final String SERVER_NAME_B = "brokerConnect/pagedB"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -72,7 +76,7 @@ public class PagedMirrorSmokeTest extends SmokeTestBase { Process processB; Process processA; - @Before + @BeforeEach public void beforeClass() throws Exception { cleanupData(SERVER_NAME_A); cleanupData(SERVER_NAME_B); @@ -91,7 +95,7 @@ public class PagedMirrorSmokeTest extends SmokeTestBase { File countJournalLocation = new File(getServerLocation(SERVER_NAME_A), "data/journal"); File countJournalLocationB = new File(getServerLocation(SERVER_NAME_B), "data/journal"); - Assert.assertTrue(countJournalLocation.exists() && countJournalLocation.isDirectory()); + assertTrue(countJournalLocation.exists() && countJournalLocation.isDirectory()); String protocol = "amqp"; ConnectionFactory sendCF = CFUtil.createConnectionFactory(protocol, sendURI); @@ -135,7 +139,7 @@ public class PagedMirrorSmokeTest extends SmokeTestBase { message.acknowledge(); } } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } Wait.assertEquals(1, () -> acksCount(countJournalLocation), 5000, 1000); Wait.assertEquals(1, () -> acksCount(countJournalLocationB), 5000, 1000); @@ -148,10 +152,10 @@ public class PagedMirrorSmokeTest extends SmokeTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES - 1; i++) { TextMessage message = (TextMessage) consumer.receive(6000); - Assert.assertNotNull(message); - Assert.assertNotEquals(ACK_I, message.getIntProperty("i")); + assertNotNull(message); + assertNotEquals(ACK_I, message.getIntProperty("i")); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/checkTest/CheckTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/checkTest/CheckTest.java index e0b5bbdae7..ec9727debb 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/checkTest/CheckTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/checkTest/CheckTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.checkTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; @@ -24,6 +28,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import java.io.File; import java.lang.invoke.MethodHandles; +import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; @@ -43,10 +48,10 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,7 +64,7 @@ public class CheckTest extends SmokeTestBase { private static final String SERVER_NAME_1 = "check-test/live"; private static final String SERVER_NAME_2 = "check-test/backup"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_1); @@ -83,7 +88,7 @@ public class CheckTest extends SmokeTestBase { Process primaryProcess; Process backupProcess; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_1); cleanupData(SERVER_NAME_2); @@ -94,7 +99,8 @@ public class CheckTest extends SmokeTestBase { disableCheckThread(); } - @Test(timeout = 60_000L) + @Test + @Timeout(value = 60_000L, unit = TimeUnit.MILLISECONDS) public void testNodeCheckActions() throws Exception { primaryProcess = startServer(SERVER_NAME_1, 0, 0); ServerUtil.waitForServerToStart("tcp://localhost:61616", 5_000); @@ -102,25 +108,25 @@ public class CheckTest extends SmokeTestBase { NodeCheck nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setUp(true); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setDiskUsage(-1); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setDiskUsage(90); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); try { nodeCheck = new NodeCheck(); @@ -129,16 +135,16 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setDiskUsage(0); nodeCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setMemoryUsage(90); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); try { nodeCheck = new NodeCheck(); @@ -147,13 +153,14 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setMemoryUsage(-1); nodeCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } } - @Test(timeout = 60_000L) + @Test + @Timeout(value = 60_000L, unit = TimeUnit.MILLISECONDS) public void testCheckTopology() throws Exception { primaryProcess = startServer(SERVER_NAME_1, 0, 0); ServerUtil.waitForServerToStart("tcp://localhost:61616", 5_000); @@ -162,7 +169,7 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setPrimary(true); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); try { nodeCheck = new NodeCheck(); @@ -171,16 +178,16 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setBackup(true); nodeCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } nodeCheck = new NodeCheck(); nodeCheck.setUser("admin"); nodeCheck.setPassword("admin"); nodeCheck.setPrimary(true); - Assert.assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(1, nodeCheck.execute(ACTION_CONTEXT)); try { nodeCheck = new NodeCheck(); @@ -189,9 +196,9 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setBackup(true); nodeCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } backupProcess = startServer(SERVER_NAME_2, 0, 0); @@ -204,7 +211,7 @@ public class CheckTest extends SmokeTestBase { nodeCheck.setPrimary(true); nodeCheck.setBackup(true); nodeCheck.setPeers(2); - Assert.assertEquals(3, nodeCheck.execute(ACTION_CONTEXT)); + assertEquals(3, nodeCheck.execute(ACTION_CONTEXT)); } public boolean hasBackup(SimpleManagement simpleManagement) { @@ -222,7 +229,8 @@ public class CheckTest extends SmokeTestBase { return false; } - @Test(timeout = 60_000L) + @Test + @Timeout(value = 60_000L, unit = TimeUnit.MILLISECONDS) public void testQueueCheckUp() throws Exception { primaryProcess = startServer(SERVER_NAME_1, 0, 0); ServerUtil.waitForServerToStart("tcp://localhost:61616", 5_000); @@ -240,9 +248,9 @@ public class CheckTest extends SmokeTestBase { queueCheck.setName(queueName); queueCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); @@ -259,9 +267,9 @@ public class CheckTest extends SmokeTestBase { queueCheck.setTimeout(100); queueCheck.execute(ACTION_CONTEXT); - Assert.fail("CLIException expected."); + fail("CLIException expected."); } catch (Exception e) { - Assert.assertTrue("CLIException expected.", e instanceof CLIException); + assertTrue(e instanceof CLIException, "CLIException expected."); } @@ -269,14 +277,14 @@ public class CheckTest extends SmokeTestBase { queueCheck.setUser("admin"); queueCheck.setPassword("admin"); queueCheck.setName(queueName); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); queueCheck = new QueueCheck(); queueCheck.setUser("admin"); queueCheck.setPassword("admin"); queueCheck.setUp(true); queueCheck.setName(queueName); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); ConnectionFactory cf = CFUtil.createConnectionFactory("core", "tcp://localhost:61616"); @@ -287,7 +295,7 @@ public class CheckTest extends SmokeTestBase { queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setBrowse(null); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); queueCheck = new QueueCheck(); @@ -295,7 +303,7 @@ public class CheckTest extends SmokeTestBase { queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setConsume(null); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); try (Connection connection = cf.createConnection(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) { @@ -315,21 +323,21 @@ public class CheckTest extends SmokeTestBase { queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setBrowse(messages); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); queueCheck = new QueueCheck(); queueCheck.setUser("admin"); queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setConsume(messages); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); queueCheck = new QueueCheck(); queueCheck.setUser("admin"); queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setProduce(messages); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); Wait.assertEquals(messages, () -> getMessageCount(simpleManagement, queueName), 1_000); @@ -339,7 +347,7 @@ public class CheckTest extends SmokeTestBase { queueCheck.setPassword("admin"); queueCheck.setName(queueName); queueCheck.setConsume(messages); - Assert.assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(1, queueCheck.execute(ACTION_CONTEXT)); Wait.assertEquals(0, () -> getMessageCount(simpleManagement, queueName), 1_000); @@ -350,7 +358,7 @@ public class CheckTest extends SmokeTestBase { queueCheck.setProduce(messages); queueCheck.setBrowse(messages); queueCheck.setConsume(messages); - Assert.assertEquals(3, queueCheck.execute(ACTION_CONTEXT)); + assertEquals(3, queueCheck.execute(ACTION_CONTEXT)); Wait.assertEquals(0, () -> getMessageCount(simpleManagement, queueName), 1_000); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/clusteredLargeMessage/ClusteredLargeMessageTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/clusteredLargeMessage/ClusteredLargeMessageTest.java index 0aa330d5b1..56e4f4a050 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/clusteredLargeMessage/ClusteredLargeMessageTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/clusteredLargeMessage/ClusteredLargeMessageTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.clusteredLargeMessage; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -33,14 +36,13 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class ClusteredLargeMessageTest extends SmokeTestBase { - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -72,7 +74,7 @@ public class ClusteredLargeMessageTest extends SmokeTestBase { Process server0Process; Process server1Process; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -132,8 +134,8 @@ public class ClusteredLargeMessageTest extends SmokeTestBase { for (int i = 0; i < 10; i++) { TextMessage message = (TextMessage) consumer2.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(largeBody, message.getText()); + assertNotNull(message); + assertEquals(largeBody, message.getText()); } connection1.close(); @@ -207,8 +209,8 @@ public class ClusteredLargeMessageTest extends SmokeTestBase { for (int i = 0; i < NMESSAGES; i++) { TextMessage message = (TextMessage) consumer2.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(largeBody, message.getText()); + assertNotNull(message); + assertEquals(largeBody, message.getText()); } } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleMutualSSLTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleMutualSSLTest.java index c25ba780cc..c28662d550 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleMutualSSLTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleMutualSSLTest.java @@ -19,31 +19,26 @@ package org.apache.activemq.artemis.tests.smoke.console; import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.ssl.SSLContexts; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; -import org.apache.activemq.artemis.utils.RetryRule; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.net.ssl.SSLContext; import java.io.File; public class ConsoleMutualSSLTest extends SmokeTestBase { - @Rule - public RetryRule retryRule = new RetryRule(2); - protected static final String SERVER_NAME = "console-mutual-ssl"; protected static final String SERVER_ADMIN_USERNAME = "admin"; protected static final String SERVER_ADMIN_PASSWORD = "admin"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME); deleteDirectory(server0Location); @@ -67,7 +62,7 @@ public class ConsoleMutualSSLTest extends SmokeTestBase { cliCreateServer.createServer(); } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME); disableCheckThread(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleTest.java index 67d55c4c7e..e1b637b2e7 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/ConsoleTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.smoke.console; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.File; import java.lang.invoke.MethodHandles; import java.net.URL; @@ -27,15 +29,13 @@ import java.util.function.BiConsumer; import java.util.function.Function; import org.apache.activemq.artemis.cli.commands.Create; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; -import org.apache.activemq.artemis.utils.RetryRule; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; @@ -51,12 +51,9 @@ import org.testcontainers.containers.BrowserWebDriverContainer; import org.testcontainers.shaded.org.apache.commons.io.FileUtils; /** The server for ConsoleTest is created on the pom as there are some properties that are passed by argument on the CI */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public abstract class ConsoleTest extends SmokeTestBase { - @Rule - public RetryRule retryRule = new RetryRule(2); - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); protected static final String SERVER_NAME = "console"; @@ -70,7 +67,7 @@ public abstract class ConsoleTest extends SmokeTestBase { protected String webServerUrl; private BrowserWebDriverContainer browserWebDriverContainer; - @Parameterized.Parameters(name = "browserOptions={0}") + @Parameters(name = "browserOptions={0}") public static Collection getParameters() { return Arrays.asList(new Object[][]{{new ChromeOptions()}, {new FirefoxOptions()}}); } @@ -80,7 +77,7 @@ public abstract class ConsoleTest extends SmokeTestBase { this.webServerUrl = String.format("%s://%s:%d", "http", System.getProperty("sts-http-host", "localhost"), 8161); } - @Before + @BeforeEach public void before() throws Exception { File jolokiaAccessFile = Paths.get(getServerLocation(SERVER_NAME), "etc", Create.ETC_JOLOKIA_ACCESS_XML).toFile(); String jolokiaAccessContent = FileUtils.readFileToString(jolokiaAccessFile, "UTF-8"); @@ -157,7 +154,7 @@ public abstract class ConsoleTest extends SmokeTestBase { driver = browserWebDriverContainer.getWebDriver(); } } catch (Exception e) { - Assume.assumeNoException("Error on loading the web driver", e); + assumeTrue(false, "Error on loading the web driver: " + e.getMessage()); } // Wait for server console @@ -175,7 +172,7 @@ public abstract class ConsoleTest extends SmokeTestBase { }); } - @After + @AfterEach public void stopWebDriver() { if (browserWebDriverContainer != null) { browserWebDriverContainer.stop(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/LoginTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/LoginTest.java index e857eb164f..c7880199e2 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/LoginTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/LoginTest.java @@ -16,31 +16,32 @@ */ package org.apache.activemq.artemis.tests.smoke.console; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.activemq.artemis.tests.smoke.console.pages.LoginPage; -import org.apache.activemq.artemis.utils.RetryRule; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.MutableCapabilities; +//Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class LoginTest extends ConsoleTest { - @Rule - public RetryRule retryRule = new RetryRule(2); - private static final String DEFAULT_CONSOLE_LOGIN_BRAND_IMAGE = "/activemq-branding/plugin/img/activemq.png"; public LoginTest(MutableCapabilities browserOptions) { super(browserOptions); } - @Test + @TestTemplate public void testLogin() { driver.get(webServerUrl + "/console"); LoginPage loginPage = new LoginPage(driver); loginPage.loginValidUser(SERVER_ADMIN_USERNAME, SERVER_ADMIN_PASSWORD, DEFAULT_TIMEOUT); } - @Test + @TestTemplate public void testLoginBrand() { String expectedBrandImage = webServerUrl + System.getProperty( "artemis.console.login.brand.image", DEFAULT_CONSOLE_LOGIN_BRAND_IMAGE); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/QueuesTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/QueuesTest.java index a1cb199f69..bb10de1f4f 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/QueuesTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/QueuesTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.console; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; @@ -23,34 +26,29 @@ import org.apache.activemq.artemis.cli.commands.ActionContext; import org.apache.activemq.artemis.cli.commands.messages.Consumer; import org.apache.activemq.artemis.cli.commands.messages.Producer; import org.apache.activemq.artemis.cli.commands.queue.CreateQueue; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.activemq.artemis.tests.smoke.console.pages.LoginPage; import org.apache.activemq.artemis.tests.smoke.console.pages.MessagePage; import org.apache.activemq.artemis.tests.smoke.console.pages.QueuePage; import org.apache.activemq.artemis.tests.smoke.console.pages.QueuesPage; import org.apache.activemq.artemis.tests.smoke.console.pages.SendMessagePage; import org.apache.activemq.artemis.tests.smoke.console.pages.StatusPage; -import org.apache.activemq.artemis.utils.RetryRule; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.MutableCapabilities; import javax.management.ObjectName; -@RunWith(Parameterized.class) +// Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class QueuesTest extends ConsoleTest { - @Rule - public RetryRule retryRule = new RetryRule(2); - public QueuesTest(MutableCapabilities browserOptions) { super(browserOptions); } - @Test + @TestTemplate public void testDefaultQueues() throws Exception { driver.get(webServerUrl + "/console"); LoginPage loginPage = new LoginPage(driver); @@ -65,7 +63,7 @@ public class QueuesTest extends ConsoleTest { assertEquals(0, queuesPage.getMessagesCount("ExpiryQueue")); } - @Test + @TestTemplate public void testAutoCreatedQueue() throws Exception { final long messages = 1; final String queueName = "TEST"; @@ -114,12 +112,12 @@ public class QueuesTest extends ConsoleTest { Wait.assertEquals(0, () -> afterQueuesPage.getMessagesCount(queueName)); } - @Test + @TestTemplate public void testDefaultExpiryQueue() throws Exception { testExpiryQueue("TEST", "ExpiryQueue"); } - @Test + @TestTemplate public void testCustomExpiryQueue() throws Exception { final ObjectNameBuilder objectNameBuilder = ObjectNameBuilder.create(null, "0.0.0.0", true); final ObjectName activeMQServerObjectName = objectNameBuilder.getActiveMQServerObjectName(); @@ -129,10 +127,10 @@ public class QueuesTest extends ConsoleTest { StatusPage statusPage = loginPage.loginValidUser( SERVER_ADMIN_USERNAME, SERVER_ADMIN_PASSWORD, DEFAULT_TIMEOUT); - Assert.assertTrue(statusPage.postJolokiaExecRequest(activeMQServerObjectName.getCanonicalName(), + assertTrue(statusPage.postJolokiaExecRequest(activeMQServerObjectName.getCanonicalName(), "createQueue(java.lang.String,java.lang.String,java.lang.String)", "\"foo\",\"foo\",\"ANYCAST\"").toString().contains("\"status\":200")); - Assert.assertTrue(statusPage.postJolokiaExecRequest(activeMQServerObjectName.getCanonicalName(), + assertTrue(statusPage.postJolokiaExecRequest(activeMQServerObjectName.getCanonicalName(), "addAddressSettings(java.lang.String,java.lang.String,java.lang.String,long,boolean,int,long,int,int,long,double,long,long,boolean,java.lang.String,long,long,java.lang.String,boolean,boolean,boolean,boolean)", "\"bar\",\"DLA\",\"foo\",-1,false,0,0,0,0,0,\"0\",0,0,false,\"\",-1,0,\"\",false,false,false,false").toString().contains("\"status\":200")); @@ -157,7 +155,7 @@ public class QueuesTest extends ConsoleTest { LoginPage loginPage = new LoginPage(driver); StatusPage statusPage = loginPage.loginValidUser( SERVER_ADMIN_USERNAME, SERVER_ADMIN_PASSWORD, DEFAULT_TIMEOUT); - Assert.assertTrue(statusPage.postJolokiaExecRequest(expiryQueueObjectName.getCanonicalName(), + assertTrue(statusPage.postJolokiaExecRequest(expiryQueueObjectName.getCanonicalName(), "removeAllMessages()", "").toString().contains("\"status\":200")); QueuesPage beforeQueuesPage = statusPage.getQueuesPage(DEFAULT_TIMEOUT); @@ -185,9 +183,9 @@ public class QueuesTest extends ConsoleTest { sendMessagePage.sendMessage(); QueuePage queuePage = sendMessagePage.getQueuesPage(DEFAULT_TIMEOUT).getQueuePage(queueName, DEFAULT_TIMEOUT); - Assert.assertTrue(queuePage.postJolokiaExecRequest(testQueueObjectName.getCanonicalName(), "expireMessage(long)", + assertTrue(queuePage.postJolokiaExecRequest(testQueueObjectName.getCanonicalName(), "expireMessage(long)", String.valueOf(queuePage.getMessageId(0))).toString().contains("\"status\":200")); - Assert.assertTrue(queuePage.postJolokiaExecRequest(testQueueObjectName.getCanonicalName(), "expireMessage(long)", + assertTrue(queuePage.postJolokiaExecRequest(testQueueObjectName.getCanonicalName(), "expireMessage(long)", String.valueOf(queuePage.getMessageId(1))).toString().contains("\"status\":200")); QueuesPage afterQueuesPage = queuePage.getQueuesPage(DEFAULT_TIMEOUT); @@ -201,7 +199,7 @@ public class QueuesTest extends ConsoleTest { assertEquals(queueName, expiryPage.getMessageOriginalQueue(1)); } - @Test + @TestTemplate public void testSendMessageUsingCurrentLogonUser() throws Exception { final String queueName = "TEST"; final String messageText = "TEST"; diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/RootTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/RootTest.java index ab695a615a..3f0fbc67a9 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/RootTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/RootTest.java @@ -16,24 +16,24 @@ */ package org.apache.activemq.artemis.tests.smoke.console; -import org.apache.activemq.artemis.utils.RetryRule; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.MutableCapabilities; +//Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class RootTest extends ConsoleTest { - @Rule - public RetryRule retryRule = new RetryRule(2); - public RootTest(MutableCapabilities browserOptions) { super(browserOptions); } - @Test + @TestTemplate public void testRedirect() { driver.get(webServerUrl); - Assert.assertTrue(driver.getCurrentUrl().startsWith(webServerUrl + "/console")); + assertTrue(driver.getCurrentUrl().startsWith(webServerUrl + "/console")); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/TabsTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/TabsTest.java index f0feaf30fb..d548c7fadb 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/TabsTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/console/TabsTest.java @@ -16,52 +16,50 @@ */ package org.apache.activemq.artemis.tests.smoke.console; +import static org.junit.jupiter.api.Assertions.fail; + +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.activemq.artemis.tests.smoke.console.pages.LoginPage; -import org.apache.activemq.artemis.utils.RetryRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.By; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.NoSuchElementException; -@RunWith(Parameterized.class) +//Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class TabsTest extends ConsoleTest { - @Rule - public RetryRule retryRule = new RetryRule(2); - public TabsTest(MutableCapabilities browserOptions) { super(browserOptions); } - @Test + @TestTemplate public void testConnectionsTab() { testTab("connections", "Connections"); } - @Test + @TestTemplate public void testSessionsTab() { testTab("sessions", "Sessions"); } - @Test + @TestTemplate public void testConsumersTab() { testTab("consumers", "Consumers"); } - @Test + @TestTemplate public void testProducersTab() { testTab("producers", "Producers"); } - @Test + @TestTemplate public void testAddressesTab() { testTab("addresses", "Addresses"); } - @Test + @TestTemplate public void testQueuesTab() { testTab("queues", "Queues"); } @@ -72,37 +70,37 @@ public class TabsTest extends ConsoleTest { driver.findElement(By.xpath("//a[contains(text(),'" + tab + "')]")); } - @Test + @TestTemplate public void testConnectionsTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("queues", "Connections"); } - @Test + @TestTemplate public void testSessionsTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("connections", "Sessions"); } - @Test + @TestTemplate public void testConsumersTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("connections", "Consumers"); } - @Test + @TestTemplate public void testProducersTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("connections", "roducers"); } - @Test + @TestTemplate public void testAddressesTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("connections", "Addresses"); } - @Test + @TestTemplate public void testQueuesTabNegative() { // use credentials for a valid user who cannot see the tab testTabNegative("connections", "Queues"); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/crossprotocol/MultiThreadConvertTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/crossprotocol/MultiThreadConvertTest.java index b1e0b450c5..24230cbacd 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/crossprotocol/MultiThreadConvertTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/crossprotocol/MultiThreadConvertTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.crossprotocol; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.IllegalStateException; @@ -42,10 +45,11 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.qpid.jms.JmsConnectionFactory; -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.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -56,7 +60,7 @@ public class MultiThreadConvertTest extends SmokeTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -71,7 +75,7 @@ public class MultiThreadConvertTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -92,17 +96,19 @@ public class MultiThreadConvertTest extends SmokeTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { super.tearDown(); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testSendLotsOfDurableMessagesOnTopicWithManySubscribersPersistent() throws Exception { doTestSendLotsOfDurableMessagesOnTopicWithManySubscribers(DeliveryMode.PERSISTENT); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testSendLotsOfDurableMessagesOnTopicWithManySubscribersNonPersistent() throws Exception { doTestSendLotsOfDurableMessagesOnTopicWithManySubscribers(DeliveryMode.NON_PERSISTENT); } @@ -159,7 +165,7 @@ public class MultiThreadConvertTest extends SmokeTestBase { }); } - assertTrue("Receivers didn't signal ready", subscribed.await(10, TimeUnit.SECONDS)); + assertTrue(subscribed.await(10, TimeUnit.SECONDS), "Receivers didn't signal ready"); // Send using AMQP and receive using Core JMS client. Session amqpSession = amqpConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -173,8 +179,8 @@ public class MultiThreadConvertTest extends SmokeTestBase { producer.send(message); } - assertTrue("did not read all messages, waiting on: " + done.getCount(), done.await(30, TimeUnit.SECONDS)); - assertFalse("should not be any errors on receive", error.get()); + assertTrue(done.await(30, TimeUnit.SECONDS), "did not read all messages, waiting on: " + done.getCount()); + assertFalse(error.get(), "should not be any errors on receive"); } finally { try { amqpConnection.close(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/custometc/CustomETCTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/custometc/CustomETCTest.java index 137a134aec..8be191406e 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/custometc/CustomETCTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/custometc/CustomETCTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.smoke.custometc; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -32,16 +36,15 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class CustomETCTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "customETC/server"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -57,7 +60,7 @@ public class CustomETCTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -77,12 +80,12 @@ public class CustomETCTest extends SmokeTestBase { connection.start(); producer.send(session.createTextMessage(text)); TextMessage txtMessage = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(txtMessage); - Assert.assertEquals(text, txtMessage.getText()); + assertNotNull(txtMessage); + assertEquals(text, txtMessage.getText()); } File logLocation = new File(getServerLocation(SERVER_NAME_0) + "/log/artemis.log"); - Assert.assertTrue(logLocation.exists()); + assertTrue(logLocation.exists()); AtomicBoolean started = new AtomicBoolean(false); Files.lines(logLocation.toPath()).forEach(line -> { @@ -91,7 +94,7 @@ public class CustomETCTest extends SmokeTestBase { } }); - Assert.assertTrue(started.get()); + assertTrue(started.get()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/expire/TestSimpleExpire.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/expire/TestSimpleExpire.java index 2da6154ffe..00dd00541b 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/expire/TestSimpleExpire.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/expire/TestSimpleExpire.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.smoke.expire; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; @@ -30,16 +34,15 @@ import java.io.File; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.qpid.jms.JmsConnectionFactory; -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; public class TestSimpleExpire extends SmokeTestBase { public static final String SERVER_NAME_0 = "expire"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -52,7 +55,7 @@ public class TestSimpleExpire extends SmokeTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -97,10 +100,10 @@ public class TestSimpleExpire extends SmokeTestBase { for (int i = 0; i < NUMBER_NON_EXPIRED; i++) { TextMessage txt = (TextMessage) consumer.receive(10000); - Assert.assertNotNull(txt); - Assert.assertEquals("ok", txt.getText()); + assertNotNull(txt); + assertEquals("ok", txt.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.commit(); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/infinite/InfiniteRedeliverySmokeTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/infinite/InfiniteRedeliverySmokeTest.java index 5a71bc1d73..8bb9d2aa6c 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/infinite/InfiniteRedeliverySmokeTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/infinite/InfiniteRedeliverySmokeTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.infinite; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; @@ -33,10 +36,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -47,7 +49,7 @@ public class InfiniteRedeliverySmokeTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "infinite-redelivery"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -62,7 +64,7 @@ public class InfiniteRedeliverySmokeTest extends SmokeTestBase { Process serverProcess; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 30000); @@ -95,14 +97,14 @@ public class InfiniteRedeliverySmokeTest extends SmokeTestBase { for (int i = 0; i < 500; i++) { if (i % 10 == 0) logger.debug("Redelivery {}", i); for (int j = 0; j < 5000; j++) { - Assert.assertNotNull(consumer.receive(5000)); + assertNotNull(consumer.receive(5000)); } session.rollback(); int numberOfFiles = fileFactory.listFiles("amq").size(); // it should be actually 10, However if a future rule changes it to allow removing files I'm ok with that - Assert.assertTrue("there are not enough files on journal", numberOfFiles >= 2); + assertTrue(numberOfFiles >= 2, "there are not enough files on journal"); // it should be max 10 actually, I'm just leaving some space for future changes, // as the real test I'm after here is the broker should clean itself up Wait.assertTrue("there are too many files created", () -> fileFactory.listFiles("amq").size() <= 20); @@ -147,17 +149,17 @@ public class InfiniteRedeliverySmokeTest extends SmokeTestBase { if (i % 100 == 0) { session.commit(); for (int c = 0; c < 5000; c++) { - Assert.assertNotNull(consumer.receive(5000)); + assertNotNull(consumer.receive(5000)); } session.commit(); - Assert.assertNotNull(consumer.receive(5000)); // there's one message behind + assertNotNull(consumer.receive(5000)); // there's one message behind session.rollback(); // we will keep the one message behind } else { session.rollback(); } int numberOfFiles = fileFactory.listFiles("amq").size(); // it should be actually 10, However if a future rule changes it to allow removing files I'm ok with that - Assert.assertTrue("there are not enough files on journal", numberOfFiles >= 2); + assertTrue(numberOfFiles >= 2, "there are not enough files on journal"); // it should be max 10 actually, I'm just leaving some space for future changes, // as the real test I'm after here is the broker should clean itself up Wait.assertTrue(() -> fileFactory.listFiles("amq").size() <= 20); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jdbccli/JDBCExportWrongUserTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jdbccli/JDBCExportWrongUserTest.java index 1bf8a0d184..1916b0c48a 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jdbccli/JDBCExportWrongUserTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jdbccli/JDBCExportWrongUserTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.jdbccli; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.apache.activemq.artemis.cli.commands.tools.DBOption; @@ -26,8 +29,7 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.FileUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JDBCExportWrongUserTest extends SmokeTestBase { @@ -50,7 +52,7 @@ public class JDBCExportWrongUserTest extends SmokeTestBase { String user = RandomUtil.randomString(); String password = RandomUtil.randomString(); - Assert.assertTrue(FileUtil.findReplace(new File(artemisInstance, "/etc/broker.xml"), "", " " + user + "\n" + " " + password + "\n" + " ")); + assertTrue(FileUtil.findReplace(new File(artemisInstance, "/etc/broker.xml"), "", " " + user + "\n" + " " + password + "\n" + " ")); { DBOption dbOption = new DBOption(); @@ -58,10 +60,10 @@ public class JDBCExportWrongUserTest extends SmokeTestBase { Configuration configuration = dbOption.getParameterConfiguration(); - Assert.assertEquals(user, ((DatabaseStorageConfiguration) configuration.getStoreConfiguration()).getJdbcUser()); - Assert.assertEquals(password, ((DatabaseStorageConfiguration) configuration.getStoreConfiguration()).getJdbcPassword()); - Assert.assertEquals(user, dbOption.getJdbcUser()); - Assert.assertEquals(password, dbOption.getJdbcPassword()); + assertEquals(user, ((DatabaseStorageConfiguration) configuration.getStoreConfiguration()).getJdbcUser()); + assertEquals(password, ((DatabaseStorageConfiguration) configuration.getStoreConfiguration()).getJdbcPassword()); + assertEquals(user, dbOption.getJdbcUser()); + assertEquals(password, dbOption.getJdbcPassword()); } { @@ -69,10 +71,10 @@ public class JDBCExportWrongUserTest extends SmokeTestBase { dbOption.setHomeValues(cliCreateServer.getArtemisHome(), artemisInstance, new File(artemisInstance, "/etc")); dbOption.setJdbcUser("myNewUser").setJdbcPassword("myNewPassword").setJdbcClassName("myClass").setJdbcURL("myURL"); Configuration config = dbOption.getParameterConfiguration(); - Assert.assertEquals("myNewUser", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcUser()); - Assert.assertEquals("myNewPassword", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcPassword()); - Assert.assertEquals("myURL", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcConnectionUrl()); - Assert.assertEquals("myClass", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcDriverClassName()); + assertEquals("myNewUser", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcUser()); + assertEquals("myNewPassword", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcPassword()); + assertEquals("myURL", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcConnectionUrl()); + assertEquals("myClass", ((DatabaseStorageConfiguration) config.getStoreConfiguration()).getJdbcDriverClassName()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jms/ManifestTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jms/ManifestTest.java index 79aabb6e79..9841c6ca07 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jms/ManifestTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jms/ManifestTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jms; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.ConnectionMetaData; import java.io.File; import java.util.ArrayList; @@ -31,8 +34,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.version.Version; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionMetaData; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ManifestTest extends SmokeTestBase { @@ -53,7 +55,7 @@ public class ManifestTest extends SmokeTestBase { for (String jarFile : jarFiles) { // The jar must be there File file = new File(distributionLibDir, jarFile + serverFullVersion + ".jar"); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); // Open the jar and load MANIFEST.MF JarFile jar = new JarFile(file); @@ -61,7 +63,7 @@ public class ManifestTest extends SmokeTestBase { // Compare the value from ConnectionMetaData and MANIFEST.MF Attributes attrs = manifest.getMainAttributes(); - Assert.assertEquals(meta.getProviderVersion(), attrs.getValue("Implementation-Version")); + assertEquals(meta.getProviderVersion(), attrs.getValue("Implementation-Version")); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx/JmxConnectionTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx/JmxConnectionTest.java index 1d8fbd5fca..1cbdea1404 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx/JmxConnectionTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx/JmxConnectionTest.java @@ -17,6 +17,12 @@ package org.apache.activemq.artemis.tests.smoke.jmx; +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 static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; @@ -32,11 +38,9 @@ import io.netty.util.internal.PlatformDependent; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.jctools.util.UnsafeAccess; -import org.junit.Assert; -import org.junit.Assume; -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; /** * This test checks JMX connection to Artemis with both necessary ports set up so that it's easier to tunnel through @@ -53,7 +57,7 @@ public class JmxConnectionTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "jmx"; private Class proxyRefClass; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -68,7 +72,7 @@ public class JmxConnectionTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -89,7 +93,7 @@ public class JmxConnectionTest extends SmokeTestBase { @Test public void testJmxConnection() throws Throwable { - Assert.assertNotNull(proxyRefClass); + assertNotNull(proxyRefClass); try { // Without this, the RMI server would bind to the default interface IP (the user's local IP mostly) @@ -107,7 +111,7 @@ public class JmxConnectionTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -116,7 +120,7 @@ public class JmxConnectionTest extends SmokeTestBase { * messy because I have to use reflection to reach the information. */ - Assert.assertTrue(jmxConnector instanceof RMIConnector); + assertTrue(jmxConnector instanceof RMIConnector); // 1. RMIConnector::connection is expected to be RMIConnectionImpl_Stub Field connectionField = RMIConnector.class.getDeclaredField("connection"); @@ -124,12 +128,12 @@ public class JmxConnectionTest extends SmokeTestBase { RMIConnection rmiConnection = (RMIConnection) connectionField.get(jmxConnector); // 2. RMIConnectionImpl_Stub extends RemoteStub which extends RemoteObject - Assert.assertTrue(rmiConnection instanceof RemoteObject); + assertTrue(rmiConnection instanceof RemoteObject); RemoteObject remoteObject = (RemoteObject) rmiConnection; // 3. RemoteObject::getRef is hereby expected to return ProxyRef RemoteRef remoteRef = remoteObject.getRef(); - Assert.assertTrue(proxyRefClass.isInstance(remoteRef)); + assertTrue(proxyRefClass.isInstance(remoteRef)); // 4. ProxyRef::ref is expected to contain UnicastRef (UnicastRef2 resp.) Field refField = proxyRefClass.getDeclaredField("ref"); RemoteRef remoteRefField; @@ -137,17 +141,17 @@ public class JmxConnectionTest extends SmokeTestBase { refField.setAccessible(true); remoteRefField = (RemoteRef) refField.get(remoteRef); } catch (Throwable error) { - Assume.assumeTrue("Unsafe must be available to continue the test", PlatformDependent.hasUnsafe()); + assumeTrue(PlatformDependent.hasUnsafe(), "Unsafe must be available to continue the test"); remoteRefField = (RemoteRef) UnsafeAccess.UNSAFE.getObject(remoteRef, UnsafeAccess.UNSAFE.objectFieldOffset(refField)); } - Assert.assertNotNull(remoteRefField); - Assert.assertEquals("sun.rmi.server.UnicastRef2", remoteRefField.getClass().getTypeName()); + assertNotNull(remoteRefField); + assertEquals("sun.rmi.server.UnicastRef2", remoteRefField.getClass().getTypeName()); // 5. UnicastRef::getLiveRef returns LiveRef Method getLiveRef = remoteRefField.getClass().getMethod("getLiveRef"); Object liveRef = getLiveRef.invoke(remoteRefField); - Assert.assertEquals(RMI_REGISTRY_PORT, liveRef.getClass().getMethod("getPort").invoke(liveRef)); + assertEquals(RMI_REGISTRY_PORT, liveRef.getClass().getMethod("getPort").invoke(liveRef)); } finally { jmxConnector.close(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx2/JmxServerControlTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx2/JmxServerControlTest.java index 9d21a124d2..58968f7c66 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx2/JmxServerControlTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmx2/JmxServerControlTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jmx2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.util.Map; @@ -40,10 +43,9 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class JmxServerControlTest extends SmokeTestBase { // This test will use a smoke created by the pom on this project (smoke-tsts) @@ -53,7 +55,7 @@ public class JmxServerControlTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "jmx2"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -70,7 +72,7 @@ public class JmxServerControlTest extends SmokeTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -94,7 +96,7 @@ public class JmxServerControlTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -118,10 +120,10 @@ public class JmxServerControlTest extends SmokeTestBase { JsonObject consumersAsJsonObject = JsonUtil.readJsonObject(consumersAsJsonString); JsonArray array = (JsonArray) consumersAsJsonObject.get("data"); - Assert.assertEquals("number of consumers returned from query", 1, array.size()); + assertEquals(1, array.size(), "number of consumers returned from query"); JsonObject jsonConsumer = array.getJsonObject(0); - Assert.assertEquals("queue name in consumer", queueName, jsonConsumer.getString("queue")); - Assert.assertEquals("address name in consumer", addressName, jsonConsumer.getString("address")); + assertEquals(queueName, jsonConsumer.getString("queue"), "queue name in consumer"); + assertEquals(addressName, jsonConsumer.getString("address"), "address name in consumer"); } finally { consumer.close(); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxfailback/JmxFailbackTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxfailback/JmxFailbackTest.java index 52140896cc..9f0ecdef91 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxfailback/JmxFailbackTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxfailback/JmxFailbackTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jmxfailback; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.management.MBeanServerInvocationHandler; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; @@ -28,10 +31,9 @@ import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class JmxFailbackTest extends SmokeTestBase { @@ -43,7 +45,7 @@ public class JmxFailbackTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "jmx-failback1"; public static final String SERVER_NAME_1 = "jmx-failback2"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -78,7 +80,7 @@ public class JmxFailbackTest extends SmokeTestBase { Process server1; Process server2; - @Before + @BeforeEach public void before() throws Exception { url1 = new JMXServiceURL(urlString_1); url2 = new JMXServiceURL(urlString_2); @@ -117,8 +119,8 @@ public class JmxFailbackTest extends SmokeTestBase { @Test public void testFailbackOnJMX() throws Exception { - Assert.assertFalse(isBackup(url1, objectNameBuilder1)); - Assert.assertTrue(isBackup(url2, objectNameBuilder2)); + assertFalse(isBackup(url1, objectNameBuilder1)); + assertTrue(isBackup(url2, objectNameBuilder2)); server1.destroyForcibly(); Wait.assertFalse(() -> isBackup(url2, objectNameBuilder2)); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxmultiplefailback/ReplicatedMultipleFailbackTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxmultiplefailback/ReplicatedMultipleFailbackTest.java index 2116fdc08b..259bb7ed8e 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxmultiplefailback/ReplicatedMultipleFailbackTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxmultiplefailback/ReplicatedMultipleFailbackTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jmxmultiplefailback; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.activemq.artemis.json.JsonArray; import org.apache.activemq.artemis.json.JsonObject; import javax.management.MBeanServerInvocationHandler; @@ -45,10 +48,9 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.JsonLoader; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -178,7 +180,7 @@ public class ReplicatedMultipleFailbackTest extends SmokeTestBase { private static final int BACKUP_1_PORT_ID = PRIMARY_3_PORT_ID + 100; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(PRIMARY_1_DATA_FOLDER); @@ -257,7 +259,7 @@ public class ReplicatedMultipleFailbackTest extends SmokeTestBase { } } - @Before + @BeforeEach public void before() { Stream.of(Broker.values()).forEach(Broker::cleanupData); disableCheckThread(); @@ -292,10 +294,10 @@ public class ReplicatedMultipleFailbackTest extends SmokeTestBase { } final String urlBackup1 = backupOf(nodeIDprimary1, decodeNetworkTopologyJson(Broker.backup1.listNetworkTopology().get())); - Assert.assertNotNull(urlBackup1); + assertNotNull(urlBackup1); final String urlPrimary1 = primaryOf(nodeIDprimary1, decodeNetworkTopologyJson(Broker.primary1.listNetworkTopology().get())); - Assert.assertNotNull(urlPrimary1); - Assert.assertNotEquals(urlPrimary1, urlBackup1); + assertNotNull(urlPrimary1); + assertNotEquals(urlPrimary1, urlBackup1); logger.info("Node ID primary 1 is {}", nodeIDprimary1); logger.info("Node ID primary 2 is {}", nodeIDprimary2); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACBrokerSecurityTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACBrokerSecurityTest.java index 0b9a0b54fb..024ce5c90e 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACBrokerSecurityTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACBrokerSecurityTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jmxrbac; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; @@ -35,10 +38,9 @@ import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; // clone of JmxRBACTest with jmx security settings in broker.xml and new guard that delegates to security settings // configured via -Djavax.management.builder.initial=org.apache.activemq.artemis.core.server.management.ArtemisRbacMBeanServerBuilder @@ -56,7 +58,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { public static final String ADDRESS_TEST = "TEST"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -71,7 +73,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -96,7 +98,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -116,9 +118,9 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { try { mBeanServerConnection.invoke(memoryObjectName, "gc", null, null); - Assert.fail(SERVER_ADMIN + " should not access to " + memoryObjectName); + fail(SERVER_ADMIN + " should not access to " + memoryObjectName); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); @@ -132,7 +134,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } @@ -146,9 +148,9 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { try { activeMQServerControl.getVersion(); - Assert.fail(SERVER_USER + " should not access to " + objectNameBuilder.getActiveMQServerObjectName()); + fail(SERVER_USER + " should not access to " + objectNameBuilder.getActiveMQServerObjectName()); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); @@ -172,7 +174,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -203,7 +205,7 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -213,9 +215,9 @@ public class JmxRBACBrokerSecurityTest extends SmokeTestBase { try { testAddressControl.sendMessage(null, Message.TEXT_TYPE, ADDRESS_TEST, true, null, null); - Assert.fail(SERVER_USER + " should not have permissions to send a message to the address " + ADDRESS_TEST); + fail(SERVER_USER + " should not have permissions to send a message to the address " + ADDRESS_TEST); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACTest.java index 94eca1018b..810f044e7c 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/jmxrbac/JmxRBACTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.jmxrbac; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; @@ -36,10 +39,9 @@ import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class JmxRBACTest extends SmokeTestBase { // This test will use a smoke created by the pom on this project (smoke-tsts) @@ -56,7 +58,7 @@ public class JmxRBACTest extends SmokeTestBase { public static final String ADDRESS_TEST = "TEST"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -71,7 +73,7 @@ public class JmxRBACTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -96,7 +98,7 @@ public class JmxRBACTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -116,9 +118,9 @@ public class JmxRBACTest extends SmokeTestBase { try { mBeanServerConnection.invoke(memoryObjectName, "gc", null, null); - Assert.fail(SERVER_ADMIN + " should not access to " + memoryObjectName); + fail(SERVER_ADMIN + " should not access to " + memoryObjectName); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); @@ -132,7 +134,7 @@ public class JmxRBACTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } @@ -146,9 +148,9 @@ public class JmxRBACTest extends SmokeTestBase { try { activeMQServerControl.getVersion(); - Assert.fail(SERVER_USER + " should not access to " + objectNameBuilder.getActiveMQServerObjectName()); + fail(SERVER_USER + " should not access to " + objectNameBuilder.getActiveMQServerObjectName()); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); @@ -172,7 +174,7 @@ public class JmxRBACTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -203,7 +205,7 @@ public class JmxRBACTest extends SmokeTestBase { } catch (Exception e) { jmxConnector = null; e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -213,9 +215,9 @@ public class JmxRBACTest extends SmokeTestBase { try { testAddressControl.sendMessage(null, Message.TEXT_TYPE, ADDRESS_TEST, true, null, null); - Assert.fail(SERVER_USER + " should not have permissions to send a message to the address " + ADDRESS_TEST); + fail(SERVER_USER + " should not have permissions to send a message to the address " + ADDRESS_TEST); } catch (Exception e) { - Assert.assertEquals(SecurityException.class, e.getClass()); + assertEquals(SecurityException.class, e.getClass()); } } finally { jmxConnector.close(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/LockManagerSinglePairTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/LockManagerSinglePairTest.java index 46183c3000..d95c3c50ed 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/LockManagerSinglePairTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/LockManagerSinglePairTest.java @@ -27,18 +27,19 @@ import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameter; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.Jmx; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -52,8 +53,12 @@ import static org.apache.activemq.artemis.tests.util.Jmx.withBackup; import static org.apache.activemq.artemis.tests.util.Jmx.withPrimary; import static org.apache.activemq.artemis.tests.util.Jmx.withMembers; import static org.apache.activemq.artemis.tests.util.Jmx.withNodes; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public abstract class LockManagerSinglePairTest extends SmokeTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -82,7 +87,7 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { } } - @BeforeClass + @BeforeAll public static void createServers() throws Exception { simpleCreate("zkReplicationPrimary"); simpleCreate("zkReplicationPrimaryPeerA"); @@ -144,10 +149,10 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { } } - @Parameterized.Parameter + @Parameter(index = 0) public boolean forceKill; - @Parameterized.Parameters(name = "forceKill={0}") + @Parameters(name = "forceKill={0}") public static Iterable getParams() { return Arrays.asList(new Object[][]{{false}, {true}}); } @@ -168,23 +173,23 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { protected abstract void restart(int[] nodes) throws Exception; - @Before + @BeforeEach public void setup() throws Exception { brokers.forEach(BrokerControl::cleanupData); } @Override - @After + @AfterEach public void after() throws Exception { super.after(); } - @Test + @TestTemplate public void testCanQueryEmptyBackup() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); logger.info("starting primary"); Process primary = this.primary.startServer(this, timeout); - Assert.assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); + assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); Wait.assertTrue(() -> !this.primary.isBackup().orElse(true), timeout); logger.info("killing primary"); ServerUtil.killServer(primary, forceKill); @@ -200,21 +205,21 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { Wait.assertTrue(() -> backup.isBackup().orElse(false), timeout); } - @Test + @TestTemplate public void testBackupFailoverAndPrimaryFailback() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); logger.info("starting primary"); Process primaryInstance = primary.startServer(this, timeout); - Assert.assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); + assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); // primary UN REPLICATED - Assert.assertEquals(1L, primary.getActivationSequence().get().longValue()); + assertEquals(1L, primary.getActivationSequence().get().longValue()); logger.info("started primary"); logger.info("starting backup"); Process backupInstance = backup.startServer(this, 0); Wait.assertTrue(() -> backup.isBackup().orElse(false), timeout); final String nodeID = primary.getNodeID().get(); - Assert.assertNotNull(nodeID); + assertNotNull(nodeID); logger.info("NodeID: {}", nodeID); for (BrokerControl broker : brokers) { Wait.assertTrue(() -> validateNetworkTopology(broker.listNetworkTopology().orElse(""), @@ -226,19 +231,19 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { } logger.info("primary topology is: {}", primary.listNetworkTopology().get()); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertTrue(backup.isReplicaSync().get()); + assertTrue(backup.isReplicaSync().get()); logger.info("backup is synchronized with live"); final String urlBackup = backupOf(nodeID, decodeNetworkTopologyJson(backup.listNetworkTopology().get())); - Assert.assertNotNull(urlBackup); + assertNotNull(urlBackup); logger.info("backup: {}", urlBackup); final String urlPrimary = primaryOf(nodeID, decodeNetworkTopologyJson(primary.listNetworkTopology().get())); - Assert.assertNotNull(urlPrimary); + assertNotNull(urlPrimary); logger.info("primary: {}", urlPrimary); - Assert.assertNotEquals(urlPrimary, urlBackup); + assertNotEquals(urlPrimary, urlBackup); // primary REPLICATED, backup matches (has replicated) activation sequence - Assert.assertEquals(1L, primary.getActivationSequence().get().longValue()); - Assert.assertEquals(1L, backup.getActivationSequence().get().longValue()); + assertEquals(1L, primary.getActivationSequence().get().longValue()); + assertEquals(1L, backup.getActivationSequence().get().longValue()); logger.info("killing primary"); ServerUtil.killServer(primaryInstance, forceKill); @@ -251,10 +256,10 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { .and(withMembers(1)) .and(withNodes(1))), timeout); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertEquals(nodeID, backup.getNodeID().get()); + assertEquals(nodeID, backup.getNodeID().get()); // backup UN REPLICATED (new version) - Assert.assertEquals(2L, backup.getActivationSequence().get().longValue()); + assertEquals(2L, backup.getActivationSequence().get().longValue()); // wait a bit before restarting primary logger.info("waiting before starting primary"); @@ -263,7 +268,7 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { primaryInstance = primary.startServer(this, 0); logger.info("started primary"); Wait.assertTrue(() -> backup.isBackup().orElse(false), timeout); - Assert.assertTrue(!primary.isBackup().get()); + assertTrue(!primary.isBackup().get()); for (BrokerControl broker : brokers) { Wait.assertTrue(() -> validateNetworkTopology(broker.listNetworkTopology().orElse(""), containsExactNodeIds(nodeID) @@ -274,24 +279,24 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { } logger.info("primary topology is: {}", primary.listNetworkTopology().get()); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertTrue(backup.isReplicaSync().get()); + assertTrue(backup.isReplicaSync().get()); logger.info("backup is synchronized with live"); - Assert.assertEquals(nodeID, primary.getNodeID().get()); + assertEquals(nodeID, primary.getNodeID().get()); // primary ran un replicated for a short while after failback, before backup was in sync - Assert.assertEquals(3L, primary.getActivationSequence().get().longValue()); - Assert.assertEquals(3L, backup.getActivationSequence().get().longValue()); + assertEquals(3L, primary.getActivationSequence().get().longValue()); + assertEquals(3L, backup.getActivationSequence().get().longValue()); logger.info("Done, killing both"); ServerUtil.killServer(primaryInstance); ServerUtil.killServer(backupInstance); } - @Test + @TestTemplate public void testActivePrimarySuicideOnLostQuorum() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); Process primaryInstance = primary.startServer(this, timeout); - Assert.assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); + assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); Wait.assertTrue(() -> !primary.isBackup().orElse(true), timeout); final String nodeID = primary.getNodeID().get(); Wait.assertTrue(() -> validateNetworkTopology(primary.listNetworkTopology().orElse(""), @@ -301,7 +306,7 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { .and(withMembers(1)) .and(withNodes(1))), timeout); final String urlPrimary = primaryOf(nodeID, decodeNetworkTopologyJson(primary.listNetworkTopology().get())); - Assert.assertTrue(validateNetworkTopology(primary.listNetworkTopology().orElse(""), + assertTrue(validateNetworkTopology(primary.listNetworkTopology().orElse(""), containsExactNodeIds(nodeID) .and(withPrimary(nodeID, urlPrimary::equals)) .and(withBackup(nodeID, Objects::isNull)) @@ -311,16 +316,16 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { Wait.waitFor(()-> !primaryInstance.isAlive(), timeout); } - @Test + @TestTemplate public void testActiveBackupSuicideOnLostQuorum() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); Process primaryInstance = primary.startServer(this, timeout); - Assert.assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); + assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); Wait.assertTrue(() -> !primary.isBackup().orElse(true), timeout); Process backupInstance = backup.startServer(this, 0); Wait.assertTrue(() -> backup.isBackup().orElse(false), timeout); final String nodeID = primary.getNodeID().get(); - Assert.assertNotNull(nodeID); + assertNotNull(nodeID); for (BrokerControl broker : brokers) { Wait.assertTrue(() -> validateNetworkTopology(broker.listNetworkTopology().orElse(""), containsExactNodeIds(nodeID) @@ -329,12 +334,12 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { .and(withMembers(1)) .and(withNodes(2))), timeout); } - Assert.assertTrue(backup.isReplicaSync().get()); + assertTrue(backup.isReplicaSync().get()); final String urlBackup = backupOf(nodeID, decodeNetworkTopologyJson(backup.listNetworkTopology().get())); - Assert.assertNotNull(urlBackup); + assertNotNull(urlBackup); final String urlPrimary = primaryOf(nodeID, decodeNetworkTopologyJson(primary.listNetworkTopology().get())); - Assert.assertNotNull(urlPrimary); - Assert.assertNotEquals(urlPrimary, urlBackup); + assertNotNull(urlPrimary); + assertNotEquals(urlPrimary, urlBackup); ServerUtil.killServer(primaryInstance, forceKill); Wait.assertTrue(() -> !backup.isBackup().orElse(true), timeout); Wait.assertTrue(() -> validateNetworkTopology(backup.listNetworkTopology().orElse(""), @@ -343,25 +348,25 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { .and(withBackup(nodeID, Objects::isNull)) .and(withMembers(1)) .and(withNodes(1))), timeout); - Assert.assertEquals(nodeID, backup.getNodeID().get()); + assertEquals(nodeID, backup.getNodeID().get()); stopMajority(); Wait.waitFor(()-> !backupInstance.isAlive(), timeout); } - @Test + @TestTemplate public void testOnlyLastUnreplicatedCanStart() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); logger.info("starting primary"); Process primaryInstance = primary.startServer(this, timeout); - Assert.assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); + assertTrue(awaitAsyncSetupCompleted(timeout, TimeUnit.MILLISECONDS)); Wait.assertTrue(() -> !primary.isBackup().orElse(true), timeout); logger.info("started primary"); logger.info("starting backup"); Process backupInstance = backup.startServer(this, 0); Wait.assertTrue(() -> backup.isBackup().orElse(false), timeout); final String nodeID = primary.getNodeID().get(); - Assert.assertNotNull(nodeID); + assertNotNull(nodeID); logger.info("NodeID: {}", nodeID); for (BrokerControl broker : brokers) { Wait.assertTrue(() -> validateNetworkTopology(broker.listNetworkTopology().orElse(""), @@ -373,20 +378,20 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { } logger.info("primary topology is: {}", primary.listNetworkTopology().get()); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertTrue(backup.isReplicaSync().get()); + assertTrue(backup.isReplicaSync().get()); logger.info("backup is synchronized with live"); final String urlBackup = backupOf(nodeID, decodeNetworkTopologyJson(backup.listNetworkTopology().get())); - Assert.assertNotNull(urlBackup); + assertNotNull(urlBackup); logger.info("backup: {}", urlBackup); final String urlPrimary = primaryOf(nodeID, decodeNetworkTopologyJson(primary.listNetworkTopology().get())); - Assert.assertNotNull(urlPrimary); + assertNotNull(urlPrimary); logger.info("primary: {}", urlPrimary); - Assert.assertNotEquals(urlPrimary, urlBackup); + assertNotEquals(urlPrimary, urlBackup); // verify sequence id's in sync - Assert.assertEquals(1L, primary.getActivationSequence().get().longValue()); - Assert.assertEquals(1L, backup.getActivationSequence().get().longValue()); + assertEquals(1L, primary.getActivationSequence().get().longValue()); + assertEquals(1L, backup.getActivationSequence().get().longValue()); logger.info("killing primary"); ServerUtil.killServer(primaryInstance, forceKill); @@ -399,11 +404,11 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { .and(withMembers(1)) .and(withNodes(1))), timeout); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertEquals(nodeID, backup.getNodeID().get()); + assertEquals(nodeID, backup.getNodeID().get()); // backup now UNREPLICATED, it is the only node that can continue - Assert.assertEquals(2L, backup.getActivationSequence().get().longValue()); + assertEquals(2L, backup.getActivationSequence().get().longValue()); logger.info("killing backup"); ServerUtil.killServer(backupInstance, forceKill); @@ -428,6 +433,6 @@ public abstract class LockManagerSinglePairTest extends SmokeTestBase { assertTrue(Wait.waitFor(() -> nodeID.equals(backup.getNodeID().orElse("not set yet")))); logger.info("restarted backup"); - Assert.assertEquals(3L, backup.getActivationSequence().get().longValue()); + assertEquals(3L, backup.getActivationSequence().get().longValue()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerPeerTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerPeerTest.java index eaec02a329..cd4292d9e4 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerPeerTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerPeerTest.java @@ -20,11 +20,12 @@ import java.util.Arrays; import java.util.Objects; import java.util.concurrent.TimeUnit; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -37,7 +38,12 @@ import static org.apache.activemq.artemis.tests.util.Jmx.withBackup; import static org.apache.activemq.artemis.tests.util.Jmx.withPrimary; import static org.apache.activemq.artemis.tests.util.Jmx.withMembers; import static org.apache.activemq.artemis.tests.util.Jmx.withNodes; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +//Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePairTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -51,14 +57,14 @@ public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePair brokers = Arrays.asList(primary, backup); } - @Ignore - @Test + @Disabled @Override + @TestTemplate public void testBackupFailoverAndPrimaryFailback() throws Exception { // peers don't request fail back by default } - @Test + @TestTemplate public void testBackupCannotForgetPeerIdOnLostQuorum() throws Exception { // see FileLockTest::testCorrelationId to get more info why this is not peer-journal-001 as in broker.xml final String coordinationId = "peer.journal.001"; @@ -67,10 +73,10 @@ public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePair final Process primary = this.primary.startServer(this, 0); logger.info("waiting peer a to increase coordinated activation sequence to 1"); Wait.assertEquals(1L, () -> this.primary.getActivationSequence().orElse(Long.MAX_VALUE).longValue(), timeout); - Assert.assertEquals(coordinationId, this.primary.getNodeID().get()); + assertEquals(coordinationId, this.primary.getNodeID().get()); Wait.waitFor(() -> this.primary.listNetworkTopology().isPresent(), timeout); final String urlPeerA = primaryOf(coordinationId, decodeNetworkTopologyJson(this.primary.listNetworkTopology().get())); - Assert.assertNotNull(urlPeerA); + assertNotNull(urlPeerA); logger.info("peer a acceptor: {}", urlPeerA); logger.info("killing peer a"); ServerUtil.killServer(primary, forceKill); @@ -88,15 +94,15 @@ public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePair final Process restartedPrimary = this.primary.startServer(this, 0); logger.info("waiting peer a to increase coordinated activation sequence to 2"); Wait.assertEquals(2L, () -> this.primary.getActivationSequence().orElse(Long.MAX_VALUE).longValue(), timeout); - Assert.assertEquals(coordinationId, this.primary.getNodeID().get()); + assertEquals(coordinationId, this.primary.getNodeID().get()); logger.info("waiting peer b to be a replica"); Wait.waitFor(() -> backup.isReplicaSync().orElse(false)); Wait.assertEquals(2L, () -> backup.getActivationSequence().get().longValue()); final String expectedUrlPeerA = primaryOf(coordinationId, decodeNetworkTopologyJson(this.primary.listNetworkTopology().get())); - Assert.assertEquals(urlPeerA, expectedUrlPeerA); + assertEquals(urlPeerA, expectedUrlPeerA); } - @Test + @TestTemplate public void testMultiPrimary_Peer() throws Exception { final int timeout = (int) TimeUnit.SECONDS.toMillis(30); @@ -108,7 +114,7 @@ public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePair assertTrue(Wait.waitFor(() -> 1L == backup.getActivationSequence().orElse(Long.MAX_VALUE).longValue())); final String nodeID = backup.getNodeID().get(); - Assert.assertNotNull(nodeID); + assertNotNull(nodeID); logger.info("NodeID: {}", nodeID); logger.info("starting peer a primary"); @@ -128,8 +134,8 @@ public class ZookeeperLockManagerPeerTest extends ZookeeperLockManagerSinglePair logger.info("primary topology is: {}", primary.listNetworkTopology().get()); logger.info("backup topology is: {}", backup.listNetworkTopology().get()); - Assert.assertTrue(backup.isReplicaSync().get()); - Assert.assertTrue(primary.isReplicaSync().get()); + assertTrue(backup.isReplicaSync().get()); + assertTrue(primary.isReplicaSync().get()); logger.info("killing peer-b"); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerSinglePairTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerSinglePairTest.java index ee389166db..634c6a80f0 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerSinglePairTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/lockmanager/ZookeeperLockManagerSinglePairTest.java @@ -17,20 +17,28 @@ package org.apache.activemq.artemis.tests.smoke.lockmanager; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.List; import java.util.concurrent.TimeUnit; -import org.apache.activemq.artemis.utils.ThreadLeakCheckRule; +import org.apache.activemq.artemis.tests.extensions.ThreadLeakCheckExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.TestingZooKeeperServer; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; import java.lang.invoke.MethodHandles; +//Parameters set in super class +@ExtendWith(ParameterizedTestExtension.class) public class ZookeeperLockManagerSinglePairTest extends LockManagerSinglePairTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -42,26 +50,26 @@ public class ZookeeperLockManagerSinglePairTest extends LockManagerSinglePairTes private InstanceSpec[] clusterSpecs; private int nodes; - @Before + @BeforeEach @Override public void setup() throws Exception { super.setup(); nodes = 3; clusterSpecs = new InstanceSpec[nodes]; for (int i = 0; i < nodes; i++) { - clusterSpecs[i] = new InstanceSpec(temporaryFolder.newFolder(), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); + clusterSpecs[i] = new InstanceSpec(newFolder(temporaryFolder, "node" + i), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1); } testingServer = new TestingCluster(clusterSpecs); testingServer.start(); - Assert.assertEquals("127.0.0.1:6666,127.0.0.1:6667,127.0.0.1:6668", testingServer.getConnectString()); + assertEquals("127.0.0.1:6666,127.0.0.1:6667,127.0.0.1:6668", testingServer.getConnectString()); logger.info("Cluster of {} nodes on: {}", 3, testingServer.getConnectString()); } @Override - @After + @AfterEach public void after() throws Exception { // zk bits that leak from servers - ThreadLeakCheckRule.addKownThread("ListenerHandler-"); + ThreadLeakCheckExtension.addKownThread("ListenerHandler-"); try { super.after(); } finally { @@ -97,4 +105,13 @@ public class ZookeeperLockManagerSinglePairTest extends LockManagerSinglePairTes servers.get(nodeIndex).restart(); } } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerAMQPMutualSSLTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerAMQPMutualSSLTest.java index 3882c47229..649b016088 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerAMQPMutualSSLTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerAMQPMutualSSLTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.smoke.logging; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -26,8 +29,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import org.apache.qpid.jms.JmsConnectionFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * See the tests/security-resources/build.sh script for details on the security resources used. @@ -74,11 +76,11 @@ public class AuditLoggerAMQPMutualSSLTest extends AuditLoggerTestBase { assertNotNull(m); } - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601715: User myUser(producers)@", "successfully authenticated")); - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601267: User myUser(producers)@", "is creating a core session")); - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601500: User myUser(producers)@", "sent a message AMQPStandardMessage")); - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601265: User myUser(producers)@", "is creating a core consumer")); - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601501: User myUser(producers)@", "is consuming a message from exampleQueue")); - Assert.assertTrue(findLogRecord(getAuditLog(), "AMQ601502: User myUser(producers)@", "acknowledged message from exampleQueue: AMQPStandardMessage")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601715: User myUser(producers)@", "successfully authenticated")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601267: User myUser(producers)@", "is creating a core session")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601500: User myUser(producers)@", "sent a message AMQPStandardMessage")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601265: User myUser(producers)@", "is creating a core consumer")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601501: User myUser(producers)@", "is consuming a message from exampleQueue")); + assertTrue(findLogRecord(getAuditLog(), "AMQ601502: User myUser(producers)@", "acknowledged message from exampleQueue: AMQPStandardMessage")); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerResourceTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerResourceTest.java index c1a6f877f1..d9ea266fb4 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerResourceTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerResourceTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.smoke.logging; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Session; @@ -42,8 +44,7 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AuditLoggerResourceTest extends AuditLoggerTestBase { @@ -63,27 +64,27 @@ public class AuditLoggerResourceTest extends AuditLoggerTestBase { ActiveMQServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getActiveMQServerObjectName(), ActiveMQServerControl.class, false); serverControl.createAddress("auditAddress", "ANYCAST,MULTICAST"); - Assert.assertTrue(findLogRecord(getAuditLog(), "successfully created address:")); + assertTrue(findLogRecord(getAuditLog(), "successfully created address:")); serverControl.updateAddress("auditAddress", "ANYCAST"); - Assert.assertTrue(findLogRecord(getAuditLog(),"successfully updated address:")); + assertTrue(findLogRecord(getAuditLog(),"successfully updated address:")); serverControl.deleteAddress("auditAddress"); - Assert.assertTrue(findLogRecord(getAuditLog(),"successfully deleted address:")); + assertTrue(findLogRecord(getAuditLog(),"successfully deleted address:")); serverControl.createQueue("auditAddress", "auditQueue", "ANYCAST"); - Assert.assertTrue(findLogRecord(getAuditLog(),"successfully created queue:")); + assertTrue(findLogRecord(getAuditLog(),"successfully created queue:")); serverControl.updateQueue("auditQueue", "ANYCAST", -1, false); final QueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getQueueObjectName(new SimpleString( "auditAddress"), new SimpleString("auditQueue"), RoutingType.ANYCAST), QueueControl.class, false); - Assert.assertTrue(findLogRecord(getAuditLog(),"successfully updated queue:")); + assertTrue(findLogRecord(getAuditLog(),"successfully updated queue:")); queueControl.removeAllMessages(); - Assert.assertTrue(findLogRecord(getAuditLog(),"has removed 0 messages")); + assertTrue(findLogRecord(getAuditLog(),"has removed 0 messages")); queueControl.sendMessage(new HashMap<>(), 0, "foo", true, "admin", "admin"); - Assert.assertTrue(findLogRecord(getAuditLog(),"sent message to")); + assertTrue(findLogRecord(getAuditLog(),"sent message to")); CompositeData[] browse = queueControl.browse(); - Assert.assertTrue(findLogRecord(getAuditLog(),"browsed " + browse.length + " messages")); + assertTrue(findLogRecord(getAuditLog(),"browsed " + browse.length + " messages")); serverControl.destroyQueue("auditQueue"); - Assert.assertTrue(findLogRecord(getAuditLog(),"successfully deleted queue:")); + assertTrue(findLogRecord(getAuditLog(),"successfully deleted queue:")); ServerLocator locator = createNettyNonHALocator(); ClientSessionFactory sessionFactory = locator.createSessionFactory(); @@ -121,10 +122,10 @@ public class AuditLoggerResourceTest extends AuditLoggerTestBase { ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, url); Connection connection = factory.createConnection(); Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601767: " + protocol + " connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601767: " + protocol + " connection")); s.close(); connection.close(); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601768: " + protocol + " connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601768: " + protocol + " connection")); } @Test @@ -139,8 +140,8 @@ public class AuditLoggerResourceTest extends AuditLoggerTestBase { final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.disconnect(); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601767: MQTT connection")); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601768: MQTT connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601767: MQTT connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601768: MQTT connection")); } @Test @@ -148,7 +149,7 @@ public class AuditLoggerResourceTest extends AuditLoggerTestBase { StompClientConnection connection = StompClientConnectionFactory.createClientConnection(new URI("tcp://localhost:61613")); connection.connect(); connection.disconnect(); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601767: STOMP connection")); - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601768: STOMP connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601767: STOMP connection")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601768: STOMP connection")); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTest.java index 8a5c10571a..8bc186e108 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.smoke.logging; +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -42,9 +48,8 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Base64; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class AuditLoggerTest extends AuditLoggerTestBase { @@ -52,7 +57,7 @@ public class AuditLoggerTest extends AuditLoggerTestBase { private ServerLocator locator; private ClientSessionFactory sf; - @Before + @BeforeEach @Override public void before() throws Exception { super.before(); @@ -80,16 +85,16 @@ public class AuditLoggerTest extends AuditLoggerTestBase { final AddressControl addressControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getAddressObjectName(address), AddressControl.class, false); - Assert.assertEquals(0, addressControl.getQueueNames().length); + assertEquals(0, addressControl.getQueueNames().length); session.createQueue(new QueueConfiguration(address).setRoutingType(RoutingType.ANYCAST)); - Assert.assertEquals(1, addressControl.getQueueNames().length); + assertEquals(1, addressControl.getQueueNames().length); String uniqueStr = Base64.encodeBytes(UUID.randomUUID().toString().getBytes()); addressControl.sendMessage(null, Message.BYTES_TYPE, uniqueStr, false, null, null); Wait.waitFor(() -> addressControl.getMessageCount() == 1); - Assert.assertEquals(1, addressControl.getMessageCount()); + assertEquals(1, addressControl.getMessageCount()); - Assert.assertTrue(findLogRecord(getAuditLog(),"sending a message", uniqueStr)); + assertTrue(findLogRecord(getAuditLog(),"sending a message", uniqueStr)); //failure log address = RandomUtil.randomSimpleString(); @@ -97,7 +102,7 @@ public class AuditLoggerTest extends AuditLoggerTestBase { final AddressControl addressControl2 = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getAddressObjectName(address), AddressControl.class, false); - Assert.assertEquals(1, addressControl.getQueueNames().length); + assertEquals(1, addressControl.getQueueNames().length); session.createQueue(new QueueConfiguration(address).setRoutingType(RoutingType.ANYCAST).setDurable(false)); Wait.waitFor(() -> addressControl2.getQueueNames().length == 1); @@ -107,14 +112,14 @@ public class AuditLoggerTest extends AuditLoggerTestBase { Wait.waitFor(() -> addressControl.getMessageCount() == 1); try { session.deleteQueue(address); - Assert.fail("Deleting queue should get exception"); + fail("Deleting queue should get exception"); } catch (Exception e) { //ignore } - Assert.assertTrue(findLogRecord(getAuditLog(),"AMQ601264: User guest", "gets security check failure, reason = AMQ229213: User: guest does not have permission='DELETE_NON_DURABLE_QUEUE'")); + assertTrue(findLogRecord(getAuditLog(),"AMQ601264: User guest", "gets security check failure, reason = AMQ229213: User: guest does not have permission='DELETE_NON_DURABLE_QUEUE'")); //hot patch not in log - Assert.assertTrue(findLogRecord(getAuditLog(),"is sending a message")); + assertTrue(findLogRecord(getAuditLog(),"is sending a message")); } @Test @@ -147,9 +152,9 @@ public class AuditLoggerTest extends AuditLoggerTestBase { final AddressControl addressControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getAddressObjectName(address), AddressControl.class, false); - Assert.assertEquals(0, addressControl.getQueueNames().length); + assertEquals(0, addressControl.getQueueNames().length); session.createQueue(new QueueConfiguration(address).setRoutingType(RoutingType.ANYCAST)); - Assert.assertEquals(1, addressControl.getQueueNames().length); + assertEquals(1, addressControl.getQueueNames().length); String uniqueStr = RandomUtil.randomString(); session.close(); @@ -175,19 +180,19 @@ public class AuditLoggerTest extends AuditLoggerTestBase { // addressControl.sendMessage(null, Message.BYTES_TYPE, uniqueStr, false, null, null); Wait.waitFor(() -> addressControl.getMessageCount() == 2); - Assert.assertEquals(2, addressControl.getMessageCount()); + assertEquals(2, addressControl.getMessageCount()); - Assert.assertFalse(findLogRecord(getAuditLog(), "messageID=0")); - Assert.assertTrue(findLogRecord(getAuditLog(), "sent a message")); - Assert.assertTrue(findLogRecord(getAuditLog(), uniqueStr)); - Assert.assertTrue(findLogRecord(getAuditLog(), "Hello2")); + assertFalse(findLogRecord(getAuditLog(), "messageID=0")); + assertTrue(findLogRecord(getAuditLog(), "sent a message")); + assertTrue(findLogRecord(getAuditLog(), uniqueStr)); + assertTrue(findLogRecord(getAuditLog(), "Hello2")); connection.start(); MessageConsumer consumer = session.createConsumer(session.createQueue(address.toString())); javax.jms.Message clientMessage = consumer.receive(5000); - Assert.assertNotNull(clientMessage); + assertNotNull(clientMessage); clientMessage = consumer.receive(5000); - Assert.assertNotNull(clientMessage); + assertNotNull(clientMessage); } finally { connection.close(); } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTestBase.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTestBase.java index fe009350cb..3a219fe6bc 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTestBase.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/logging/AuditLoggerTestBase.java @@ -22,13 +22,13 @@ import java.io.PrintWriter; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; public abstract class AuditLoggerTestBase extends SmokeTestBase { private File auditLog = null; - @Before + @BeforeEach public void before() throws Exception { File server0Location = getFileServerLocation(getServerName()); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/maxConsumers/MaxConsumersTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/maxConsumers/MaxConsumersTest.java index 25a460e733..7eeb44f9f4 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/maxConsumers/MaxConsumersTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/maxConsumers/MaxConsumersTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.smoke.maxConsumers; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; @@ -28,10 +30,9 @@ import java.io.File; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.qpid.jms.JmsConnectionFactory; -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; public class MaxConsumersTest extends SmokeTestBase { @@ -56,7 +57,7 @@ public class MaxConsumersTest extends SmokeTestBase { */ - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -71,7 +72,7 @@ public class MaxConsumersTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); @@ -90,7 +91,7 @@ public class MaxConsumersTest extends SmokeTestBase { MessageConsumer consumer = session.createConsumer(queue); try { MessageConsumer consumer2 = session.createConsumer(queue); - Assert.fail("Exception was expected here"); + fail("Exception was expected here"); } catch (JMSException expectedMax) { } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/mqtt/MQTTLeakTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/mqtt/MQTTLeakTest.java index 52a1065c22..cb65a2d0f3 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/mqtt/MQTTLeakTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/mqtt/MQTTLeakTest.java @@ -31,10 +31,10 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; -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; public class MQTTLeakTest extends SmokeTestBase { @@ -62,7 +62,7 @@ public class MQTTLeakTest extends SmokeTestBase { */ - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -77,13 +77,13 @@ public class MQTTLeakTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); } - @After + @AfterEach @Override public void after() throws Exception { super.after(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/nettynative/NettyNativeTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/nettynative/NettyNativeTest.java index 5c50fd61c8..da0e7086bd 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/nettynative/NettyNativeTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/nettynative/NettyNativeTest.java @@ -16,14 +16,18 @@ */ package org.apache.activemq.artemis.tests.smoke.nettynative; +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.assertTrue; + import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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 javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -41,7 +45,7 @@ public class NettyNativeTest extends SmokeTestBase { protected static final String SERVER_ADMIN_PASSWORD = "admin"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME); @@ -56,7 +60,7 @@ public class NettyNativeTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME); disableCheckThread(); @@ -80,16 +84,16 @@ public class NettyNativeTest extends SmokeTestBase { connection.start(); TextMessage txt = (TextMessage) consumer.receive(10000); - Assert.assertNotNull(txt); - Assert.assertEquals("TEST", txt.getText()); + assertNotNull(txt); + assertEquals("TEST", txt.getText()); session.commit(); } } File artemisLog = new File("target/" + SERVER_NAME + "/log/artemis.log"); - Assert.assertTrue(findLogRecord(artemisLog, "Acceptor using native")); - Assert.assertFalse(findLogRecord(artemisLog, "Acceptor using nio")); + assertTrue(findLogRecord(artemisLog, "Acceptor using native")); + assertFalse(findLogRecord(artemisLog, "Acceptor using nio")); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/FloodServerWithAsyncSendTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/FloodServerWithAsyncSendTest.java index a6655ba109..c5f6aa9f67 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/FloodServerWithAsyncSendTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/FloodServerWithAsyncSendTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.smoke.paging; +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 static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -34,10 +39,9 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -48,7 +52,7 @@ public class FloodServerWithAsyncSendTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "paging"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -67,7 +71,7 @@ public class FloodServerWithAsyncSendTest extends SmokeTestBase { AtomicInteger errors = new AtomicInteger(0); - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); startServer(SERVER_NAME_0, 0, 30000); @@ -84,7 +88,7 @@ public class FloodServerWithAsyncSendTest extends SmokeTestBase { if (protocol.equalsIgnoreCase("OPENWIRE")) { return CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616?jms.useAsyncSend=true"); } else { - Assert.fail("unsuported protocol"); + fail("unsuported protocol"); return null; } } @@ -103,10 +107,10 @@ public class FloodServerWithAsyncSendTest extends SmokeTestBase { running = false; executorService.shutdown(); - Assert.assertTrue(executorService.awaitTermination(1, TimeUnit.MINUTES)); + assertTrue(executorService.awaitTermination(1, TimeUnit.MINUTES)); for (int i = 0; i < 2; i++) { - Assert.assertEquals("should have received at least a few messages", 20, consume(protocol, "queue" + i, 20)); + assertEquals(20, consume(protocol, "queue" + i, 20), "should have received at least a few messages"); } ConnectionFactory factory = newCF("openwire"); @@ -122,11 +126,11 @@ public class FloodServerWithAsyncSendTest extends SmokeTestBase { producer.send(session.createTextMessage(random)); TextMessage message = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals(random, message.getText()); + assertNotNull(message); + assertEquals(random, message.getText()); connection.close(); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } finally { running = false; executorService.shutdownNow(); // just to avoid thread leakage in case anything failed on the test diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokeMaxMessagePagingTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokeMaxMessagePagingTest.java index c97099cda6..17f2785b2a 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokeMaxMessagePagingTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokeMaxMessagePagingTest.java @@ -17,16 +17,18 @@ package org.apache.activemq.artemis.tests.smoke.paging; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.apache.activemq.artemis.cli.commands.ActionContext; import org.apache.activemq.artemis.cli.commands.messages.Producer; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class SmokeMaxMessagePagingTest extends SmokeTestBase { @@ -34,7 +36,7 @@ public class SmokeMaxMessagePagingTest extends SmokeTestBase { public static final String SERVER_NAME_ADDRESS = "pagingAddressMaxMessages"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_GLOBAL); @@ -57,7 +59,7 @@ public class SmokeMaxMessagePagingTest extends SmokeTestBase { } } - @Before + @BeforeEach public void before() throws Exception { } @@ -75,7 +77,7 @@ public class SmokeMaxMessagePagingTest extends SmokeTestBase { cleanupData(serverName); startServer(serverName, 0, 30000); internalSend("core", 2000); - Assert.assertTrue("System did not page", isPaging(serverName)); + assertTrue(isPaging(serverName), "System did not page"); } boolean isPaging(String serverName) { @@ -101,13 +103,13 @@ public class SmokeMaxMessagePagingTest extends SmokeTestBase { Process process = startServer(serverName, 0, 30000); internalSend("core", 500); - Assert.assertFalse(isPaging(serverName)); + assertFalse(isPaging(serverName)); process.destroy(); process = startServer(serverName, 0, 30000); internalSend("core", 1500); - Assert.assertTrue(isPaging(serverName)); + assertTrue(isPaging(serverName)); } private void internalSend(String protocol, int numberOfMessages) throws Exception { diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokePagingTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokePagingTest.java index a1332e6e57..4a33ed4ed7 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokePagingTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/paging/SmokePagingTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.smoke.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import org.apache.activemq.artemis.cli.commands.ActionContext; @@ -24,16 +26,15 @@ import org.apache.activemq.artemis.cli.commands.messages.Consumer; import org.apache.activemq.artemis.cli.commands.messages.Producer; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class SmokePagingTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "paging"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -47,7 +48,7 @@ public class SmokePagingTest extends SmokeTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); startServer(SERVER_NAME_0, 0, 30000); @@ -88,7 +89,7 @@ public class SmokePagingTest extends SmokeTestBase { consumer.setBreakOnNull(true); long consumed = (long)consumer.execute(new ActionContext()); - Assert.assertEquals(NUMBER_OF_MESSAGES, consumed); + assertEquals(NUMBER_OF_MESSAGES, consumed); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/resourcetest/MaxQueueResourceTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/resourcetest/MaxQueueResourceTest.java index e18781daca..22ecf0b885 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/resourcetest/MaxQueueResourceTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/resourcetest/MaxQueueResourceTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.resourcetest; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSSecurityException; @@ -31,16 +34,15 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class MaxQueueResourceTest extends SmokeTestBase { public static final String SERVER_NAME_A = "MaxQueueResourceTest"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_A); @@ -54,7 +56,7 @@ public class MaxQueueResourceTest extends SmokeTestBase { } - @Before + @BeforeEach public void before() throws Exception { startServer(SERVER_NAME_A, 0, 0); ServerUtil.waitForServerToStart(0, "admin", "admin", 30000); @@ -92,8 +94,8 @@ public class MaxQueueResourceTest extends SmokeTestBase { } catch (JMSSecurityException e) { exception = e; } - Assert.assertNull(consumer4); - Assert.assertNotNull(exception); + assertNull(consumer4); + assertNotNull(exception); MessageProducer producerA = sessionA.createProducer(topic); for (int i = 0; i < 10; i++) { producerA.send(sessionA.createTextMessage("toB")); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/retention/ReplayTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/retention/ReplayTest.java index 154ba240ba..c6f651d7c8 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/retention/ReplayTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/retention/ReplayTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.retention; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -35,10 +39,9 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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; public class ReplayTest extends SmokeTestBase { private static final String JMX_SERVER_HOSTNAME = "localhost"; @@ -48,7 +51,7 @@ public class ReplayTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "replay/replay"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -63,7 +66,7 @@ public class ReplayTest extends SmokeTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); startServer(SERVER_NAME_0, 0, 30000); @@ -125,36 +128,36 @@ public class ReplayTest extends SmokeTestBase { MessageConsumer consumer = session.createConsumer(queue); for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(bufferStr, message.getText()); + assertNotNull(message); + assertEquals(bufferStr, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.commit(); serverControl.replay(queueName, queueName, null); for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(bufferStr, message.getText()); + assertNotNull(message); + assertEquals(bufferStr, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.commit(); serverControl.replay(queueName, queueName, "i=1"); for (int i = 0; i < 2; i++) { // replay of a replay will give you 2 messages TextMessage message = (TextMessage)consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(1, message.getIntProperty("i")); - Assert.assertEquals(bufferStr, message.getText()); + assertNotNull(message); + assertEquals(1, message.getIntProperty("i")); + assertEquals(bufferStr, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.commit(); serverControl.replay(queueName, queueName, "foo='foo'"); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/topologycheck/TopologyCheckTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/topologycheck/TopologyCheckTest.java index 7d7c393e4b..10a2c49f78 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/topologycheck/TopologyCheckTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/topologycheck/TopologyCheckTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.smoke.topologycheck; +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.File; import java.lang.invoke.MethodHandles; @@ -30,10 +34,9 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -127,7 +130,7 @@ public class TopologyCheckTest extends SmokeTestBase { */ - @BeforeClass + @BeforeAll public static void createServers() throws Exception { for (int i = 1; i <= 4; i++) { @@ -152,7 +155,7 @@ public class TopologyCheckTest extends SmokeTestBase { String[] URLS = new String[]{URI_1, URI_2, URI_3, URI_4}; String[] SERVER_NAMES = new String[]{SERVER_NAME_1, SERVER_NAME_2, SERVER_NAME_3, SERVER_NAME_4}; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_1); cleanupData(SERVER_NAME_2); @@ -224,18 +227,18 @@ public class TopologyCheckTest extends SmokeTestBase { Wait.assertEquals(validNodes.length, () -> simpleManagement.listNetworkTopology().size(), 500, 5000); JsonArray topologyArray = simpleManagement.listNetworkTopology(); - Assert.assertNotNull(topologyArray); + assertNotNull(topologyArray); for (int j : validNodes) { JsonObject itemTopology = findTopologyNode(nodeIDs[j], topologyArray); - Assert.assertNotNull(itemTopology); + assertNotNull(itemTopology); JsonString jsonString = (JsonString) itemTopology.get("live"); - Assert.assertEquals(uris[j], "tcp://" + jsonString.getString()); + assertEquals(uris[j], "tcp://" + jsonString.getString()); } } ClusterNodeVerifier clusterVerifier = new ClusterNodeVerifier(uris[validNodes[0]], "admin", "admin"); - Assert.assertTrue(clusterVerifier.verify(new ActionContext())); + assertTrue(clusterVerifier.verify(new ActionContext())); } JsonObject findTopologyNode(String nodeID, JsonArray topologyArray) { diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/transfer/TransferTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/transfer/TransferTest.java index f332bc82a6..074902522c 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/transfer/TransferTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/transfer/TransferTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.smoke.transfer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; @@ -29,18 +33,18 @@ import java.io.File; import java.util.ArrayList; import java.util.Collection; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class TransferTest extends SmokeTestBase { public static final String SERVER_NAME_0 = "transfer1"; @@ -88,7 +92,7 @@ public class TransferTest extends SmokeTestBase { */ - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -118,7 +122,7 @@ public class TransferTest extends SmokeTestBase { this.targetTransferProtocol = target; } - @Parameterized.Parameters(name = "sender={0}, consumer={1}, sourceOnTransfer={2}, targetOnTransfer={3}") + @Parameters(name = "sender={0}, consumer={1}, sourceOnTransfer={2}, targetOnTransfer={3}") public static Collection getParams() { String[] protocols = new String[]{"core", "amqp"}; @@ -146,7 +150,7 @@ public class TransferTest extends SmokeTestBase { return CFUtil.createConnectionFactory(senderProtocol, "tcp://localhost:61616"); } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -155,12 +159,12 @@ public class TransferTest extends SmokeTestBase { startServer(SERVER_NAME_1, 100, 30000); } - @Test + @TestTemplate public void testTransferSimpleQueueCopy() throws Exception { internalTransferSimpleQueue(false); } - @Test + @TestTemplate public void testTransferSimpleQueue() throws Exception { internalTransferSimpleQueue(true); } @@ -214,13 +218,13 @@ public class TransferTest extends SmokeTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage received = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(received); - Assert.assertEquals("hello " + i, received.getText()); + assertNotNull(received); + assertEquals("hello " + i, received.getText()); } sessionTarget.commit(); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); MessageConsumer consumerSource = session.createConsumer(queue); connection.start(); @@ -228,18 +232,18 @@ public class TransferTest extends SmokeTestBase { if (copy) { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage received = (TextMessage) consumerSource.receive(1000); - Assert.assertNotNull(received); - Assert.assertEquals("hello " + i, received.getText()); + assertNotNull(received); + assertEquals("hello " + i, received.getText()); } } - Assert.assertNull(consumerSource.receiveNoWait()); + assertNull(consumerSource.receiveNoWait()); connection.close(); connectionTarget.close(); } - @Test + @TestTemplate public void testDurableSharedSubscrition() throws Exception { ConnectionFactory factory = createSenderCF(); Connection connection = factory.createConnection(); @@ -270,18 +274,18 @@ public class TransferTest extends SmokeTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage received = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(received); + assertNotNull(received); } sessionTarget.commit(); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); connection.close(); connectionTarget.close(); } - @Test + @TestTemplate public void testSharedSubscrition() throws Exception { ConnectionFactory factory = createSenderCF(); Connection connection = factory.createConnection(); @@ -322,7 +326,7 @@ public class TransferTest extends SmokeTestBase { // I'm not going to bother about being too strict about the content, just that some messages arrived for (int i = 0; i < PARTIAL_MESSAGES; i++) { TextMessage received = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(received); + assertNotNull(received); } sessionTarget.commit(); @@ -331,7 +335,7 @@ public class TransferTest extends SmokeTestBase { connectionTarget.close(); } - @Test + @TestTemplate public void testDurableConsumer() throws Exception { ConnectionFactory factory = createSenderCF(); Connection connection = factory.createConnection(); @@ -366,7 +370,7 @@ public class TransferTest extends SmokeTestBase { // I'm not going to bother about being too strict about the content, just that some messages arrived for (int i = 0; i < PARTIAL_MESSAGES; i++) { TextMessage received = (TextMessage) consumer.receive(1000); - Assert.assertNotNull(received); + assertNotNull(received); } sessionTarget.commit(); diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/CompareUpgradeTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/CompareUpgradeTest.java index 0ee64bdddb..c325671db9 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/CompareUpgradeTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/CompareUpgradeTest.java @@ -17,9 +17,13 @@ package org.apache.activemq.artemis.tests.smoke.upgradeTest; -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.assertArrayEquals; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.FileInputStream; @@ -40,8 +44,7 @@ import org.apache.activemq.artemis.cli.commands.ActionContext; import org.apache.activemq.artemis.cli.commands.Create; import org.apache.activemq.artemis.cli.commands.Upgrade; import org.apache.activemq.artemis.utils.FileUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,31 +97,31 @@ public class CompareUpgradeTest { } private void verifyBackupFiles(String backupFolder, String referenceFolder, String... files) throws Exception { - assertTrue("Files to check must be specified", files.length > 0); + assertTrue(files.length > 0, "Files to check must be specified"); File bck = new File(backupFolder); if (!(bck.exists() && bck.isDirectory())) { - Assert.fail("Backup folder does not exist at: " + bck.getAbsolutePath()); + fail("Backup folder does not exist at: " + bck.getAbsolutePath()); } File[] backupFiles = bck.listFiles(); - assertNotNull("Some backup files must exist", backupFiles); + assertNotNull(backupFiles, "Some backup files must exist"); int backupFilesCount = backupFiles.length; - assertTrue("Some backup files must exist", backupFilesCount > 0); - assertEquals("Different number of backup files found than specified for inspection, update test if backup procedure changed", files.length, backupFilesCount); + assertTrue(backupFilesCount > 0, "Some backup files must exist"); + assertEquals(files.length, backupFilesCount, "Different number of backup files found than specified for inspection, update test if backup procedure changed"); for (String f : files) { File bf = new File(backupFolder, f); if (!bf.exists()) { - Assert.fail("Expected backup file does not exist at: " + bf.getAbsolutePath()); + fail("Expected backup file does not exist at: " + bf.getAbsolutePath()); } File reference = new File(referenceFolder, bf.getName()); if (!reference.exists()) { - Assert.fail("Reference file does not exist at: " + reference.getAbsolutePath()); + fail("Reference file does not exist at: " + reference.getAbsolutePath()); } - Assert.assertArrayEquals(bf.getName() + " backup contents do not match reference file", Files.readAllBytes(bf.toPath()), Files.readAllBytes(reference.toPath())); + assertArrayEquals(Files.readAllBytes(bf.toPath()), Files.readAllBytes(reference.toPath()), bf.getName() + " backup contents do not match reference file"); } } @@ -139,12 +142,12 @@ public class CompareUpgradeTest { for (File f : foundFiles) { File upgradeFile = new File(upgradeFolderFile, f.getName()); if (!upgradeFile.exists()) { - Assert.fail(upgradeFile.getAbsolutePath() + " not does exist"); + fail(upgradeFile.getAbsolutePath() + " not does exist"); } if (f.getName().endsWith(".exe")) { - Assert.assertArrayEquals(f.getName() + " is different after upgrade", Files.readAllBytes(f.toPath()), Files.readAllBytes(upgradeFile.toPath())); + assertArrayEquals(Files.readAllBytes(f.toPath()), Files.readAllBytes(upgradeFile.toPath()), f.getName() + " is different after upgrade"); } else { compareFiles(allowExpectedWord, f, upgradeFile); } @@ -162,7 +165,7 @@ public class CompareUpgradeTest { int line = 1; while (expectedIterator.hasNext()) { - Assert.assertTrue(upgradeIterator.hasNext()); + assertTrue(upgradeIterator.hasNext()); String expectedString = expectedIterator.next().trim(); String upgradeString = upgradeIterator.next().trim(); @@ -173,11 +176,11 @@ public class CompareUpgradeTest { expectedString = expectedString.replace("Expected", ""); } - Assert.assertEquals("error on line " + line + " at " + upgradeFile, expectedString, upgradeString); + assertEquals(expectedString, upgradeString, "error on line " + line + " at " + upgradeFile); line++; } - Assert.assertFalse(upgradeIterator.hasNext()); + assertFalse(upgradeIterator.hasNext()); } } @@ -197,8 +200,8 @@ public class CompareUpgradeTest { ); String home = result.get(""); @@ -219,8 +222,8 @@ public class CompareUpgradeTest { File oldLogging = new File(windowsETC + "/logging.properties"); File newLogging = new File(windowsETC + "/log4j2.properties"); - Assert.assertFalse("Old logging must be removed by upgrade", oldLogging.exists()); - Assert.assertTrue("New Logging must be installed by upgrade", newLogging.exists()); + assertFalse(oldLogging.exists(), "Old logging must be removed by upgrade"); + assertTrue(newLogging.exists(), "New Logging must be installed by upgrade"); } @@ -243,14 +246,14 @@ public class CompareUpgradeTest { "ARTEMIS_INSTANCE_ETC_URI=", "'file:" + etc + "/'"); String home = result.get("ARTEMIS_HOME="); - Assert.assertNotNull(home); - Assert.assertNotEquals("'must-change'", home); + assertNotNull(home); + assertNotEquals("'must-change'", home); File oldLogging = new File(etc + "/logging.properties"); File newLogging = new File(etc + "/log4j2.properties"); - Assert.assertFalse("Old logging must be removed by upgrade", oldLogging.exists()); - Assert.assertTrue("New Logging must be installed by upgrade", newLogging.exists()); + assertFalse(oldLogging.exists(), "Old logging must be removed by upgrade"); + assertTrue(newLogging.exists(), "New Logging must be installed by upgrade"); } @Test @@ -280,7 +283,7 @@ public class CompareUpgradeTest { // Calling upgrade on itself should not cause any changes to *any* file // output should be exactly the same - Assert.assertTrue(compareDirectories(false, originalConfig.toPath(), upgradeConfig.toPath())); + assertTrue(compareDirectories(false, originalConfig.toPath(), upgradeConfig.toPath())); } private void removeBackups(File upgradeConfig) { @@ -322,12 +325,12 @@ public class CompareUpgradeTest { } private Map checkExpectedValues(String fileName, String... expectedPairs) throws Exception { - Assert.assertTrue("You must pass a pair of expected values", expectedPairs.length > 0 && expectedPairs.length % 2 == 0); + assertTrue(expectedPairs.length > 0 && expectedPairs.length % 2 == 0, "You must pass a pair of expected values"); HashMap expectedValues = new HashMap<>(); HashMap matchingValues = new HashMap<>(); for (int i = 0; i < expectedPairs.length; i += 2) { - Assert.assertFalse("Value duplicated on pairs ::" + expectedPairs[i], expectedValues.containsKey(expectedPairs[i])); + assertFalse(expectedValues.containsKey(expectedPairs[i]), "Value duplicated on pairs ::" + expectedPairs[i]); expectedValues.put(expectedPairs[i], expectedPairs[i + 1]); } @@ -347,14 +350,14 @@ public class CompareUpgradeTest { if (logger.isDebugEnabled()) { logger.debug("prefix={}, expecting={}, actualValue={}", key, value, actualValue); } - Assert.assertEquals(key + " did not match", value, actualValue); + assertEquals(value, actualValue, key + " did not match"); } } }); }); } - Assert.assertEquals("Some elements were not found in the output of " + fileName, matchingValues.size(), expectedValues.size()); + assertEquals(matchingValues.size(), expectedValues.size(), "Some elements were not found in the output of " + fileName); return matchingValues; } diff --git a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/UpgradeTest.java b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/UpgradeTest.java index 4936d1c370..8620b80cd3 100644 --- a/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/UpgradeTest.java +++ b/tests/smoke-tests/src/test/java/org/apache/activemq/artemis/tests/smoke/upgradeTest/UpgradeTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.smoke.upgradeTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -29,9 +32,8 @@ import org.apache.activemq.artemis.tests.smoke.common.SmokeTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** This test is making sure the upgrade command would be able to upgrade a test I created with artemis 2.25.0 */ public class UpgradeTest extends SmokeTestBase { @@ -40,7 +42,7 @@ public class UpgradeTest extends SmokeTestBase { Process processServer; - @Before + @BeforeEach public void beforeTest() throws Exception { upgradedServer = new File(basedir + "/target/classes/servers/linuxUpgrade"); deleteDirectory(new File(upgradedServer, "data")); @@ -63,8 +65,8 @@ public class UpgradeTest extends SmokeTestBase { String randomString = "Hello " + RandomUtil.randomString(); producer.send(session.createTextMessage(randomString)); TextMessage message = (TextMessage)consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(randomString, message.getText()); + assertNotNull(message); + assertEquals(randomString, message.getText()); } } diff --git a/tests/soak-tests/pom.xml b/tests/soak-tests/pom.xml index fbfb837f02..5c05f5a4d0 100644 --- a/tests/soak-tests/pom.xml +++ b/tests/soak-tests/pom.xml @@ -128,8 +128,14 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test jakarta.transaction diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ClusteredMirrorSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ClusteredMirrorSoakTest.java index 95f54f5593..a346ff250b 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ClusteredMirrorSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ClusteredMirrorSoakTest.java @@ -17,6 +17,13 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -52,8 +59,7 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.FileUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -113,11 +119,11 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); File brokerXml = new File(serverLocation, "/etc/broker.xml"); - Assert.assertTrue(brokerXml.exists()); + assertTrue(brokerXml.exists()); // Adding redistribution delay to broker configuration - Assert.assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); + assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); if (paging) { - Assert.assertTrue(FileUtil.findReplace(brokerXml, "-1", "1")); + assertTrue(FileUtil.findReplace(brokerXml, "-1", "1")); } } @@ -174,18 +180,18 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { logger.info("DC2B={}", simpleManagementDC2B.getMessageAddedOnQueue(snfQueue)); // no load generated.. just initial queues should have been sent - Assert.assertTrue(simpleManagementDC1A.getMessageAddedOnQueue(snfQueue) < 20); - Assert.assertTrue(simpleManagementDC2A.getMessageAddedOnQueue(snfQueue) < 20); - Assert.assertTrue(simpleManagementDC1B.getMessageAddedOnQueue(snfQueue) < 20); - Assert.assertTrue(simpleManagementDC2B.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC1A.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC2A.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC1B.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC2B.getMessageAddedOnQueue(snfQueue) < 20); Thread.sleep(100); } - Assert.assertEquals(0, simpleManagementDC2A.getMessageCountOnQueue(queueName)); - Assert.assertEquals(0, simpleManagementDC1A.getMessageCountOnQueue(internalQueue)); + assertEquals(0, simpleManagementDC2A.getMessageCountOnQueue(queueName)); + assertEquals(0, simpleManagementDC1A.getMessageCountOnQueue(internalQueue)); try { simpleManagementDC2A.getMessageCountOnQueue(internalQueue); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (Exception expected) { } @@ -242,7 +248,7 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { for (MessageConsumer c : consumers) { for (int i = 0; i < numberOfMessages; i++) { - Assert.assertNotNull(c.receive(5000)); + assertNotNull(c.receive(5000)); if (i % 100 == 0) { session.commit(); } @@ -263,12 +269,12 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { for (int i = 0; i < 10; i++) { // DC1 should be quiet and nothing moving out of it - Assert.assertEquals(countDC1A, simpleManagementDC1A.getMessageAddedOnQueue(snfQueue)); - Assert.assertEquals(countDC1B, simpleManagementDC1B.getMessageAddedOnQueue(snfQueue)); + assertEquals(countDC1A, simpleManagementDC1A.getMessageAddedOnQueue(snfQueue)); + assertEquals(countDC1B, simpleManagementDC1B.getMessageAddedOnQueue(snfQueue)); // DC2 is totally passive, nothing should have been generated - Assert.assertTrue(simpleManagementDC2A.getMessageAddedOnQueue(snfQueue) < 20); - Assert.assertTrue(simpleManagementDC2B.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC2A.getMessageAddedOnQueue(snfQueue) < 20); + assertTrue(simpleManagementDC2B.getMessageAddedOnQueue(snfQueue) < 20); // we take intervals, allowing to make sure it doesn't grow Thread.sleep(100); logger.info("DC1A={}", simpleManagementDC1A.getMessageAddedOnQueue(snfQueue)); @@ -285,7 +291,7 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { final int numberOfMessages = 200; - Assert.assertTrue("numberOfMessages must be even", numberOfMessages % 2 == 0); + assertTrue(numberOfMessages % 2 == 0, "numberOfMessages must be even"); ConnectionFactory connectionFactoryDC1A = CFUtil.createConnectionFactory("amqp", DC1_NODEA_URI); ConnectionFactory connectionFactoryDC2A = CFUtil.createConnectionFactory("amqp", DC2_NODEA_URI); @@ -329,7 +335,7 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { for (int i = 0; i < numberOfMessages / 2; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); } session.commit(); @@ -349,7 +355,7 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { for (int i = 0; i < numberOfMessages / 2; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); } session.commit(); @@ -456,14 +462,14 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { SimpleManagement simpleManagementDC2A = new SimpleManagement(DC2_NODEA_URI, null, null); SimpleManagement simpleManagementDC2B = new SimpleManagement(DC2_NODEB_URI, null, null)) { - Assert.assertFalse(findQueue(simpleManagementDC1A, queueName)); - Assert.assertFalse(findQueue(simpleManagementDC1B, queueName)); - Assert.assertFalse(findQueue(simpleManagementDC2A, queueName)); - Assert.assertFalse(findQueue(simpleManagementDC2B, queueName)); + assertFalse(findQueue(simpleManagementDC1A, queueName)); + assertFalse(findQueue(simpleManagementDC1B, queueName)); + assertFalse(findQueue(simpleManagementDC2A, queueName)); + assertFalse(findQueue(simpleManagementDC2B, queueName)); // just to allow auto-creation to kick in.... - Assert.assertTrue(startConsumer(executorService, connectionFactoryDC2A, queueName, new AtomicBoolean(false), errors, receiverCount).await(1, TimeUnit.MINUTES)); - Assert.assertTrue(startConsumer(executorService, connectionFactoryDC2B, queueName, new AtomicBoolean(false), errors, receiverCount).await(1, TimeUnit.MINUTES)); + assertTrue(startConsumer(executorService, connectionFactoryDC2A, queueName, new AtomicBoolean(false), errors, receiverCount).await(1, TimeUnit.MINUTES)); + assertTrue(startConsumer(executorService, connectionFactoryDC2B, queueName, new AtomicBoolean(false), errors, receiverCount).await(1, TimeUnit.MINUTES)); Wait.assertTrue(() -> findQueue(simpleManagementDC1A, queueName)); Wait.assertTrue(() -> findQueue(simpleManagementDC1B, queueName)); @@ -496,8 +502,8 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { runningConsumers.set(false); - Assert.assertTrue(doneDC2B.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, errors.get()); + assertTrue(doneDC2B.await(5, TimeUnit.SECONDS)); + assertEquals(0, errors.get()); } } @@ -508,7 +514,7 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { final int numberOfMessages = 200; - Assert.assertTrue("numberOfMessages must be even", numberOfMessages % 2 == 0); + assertTrue(numberOfMessages % 2 == 0, "numberOfMessages must be even"); String clientIDA = "nodeA"; String clientIDB = "nodeB"; @@ -585,25 +591,25 @@ public class ClusteredMirrorSoakTest extends SoakTestBase { for (int i = start; i < start + numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(10_000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); if (message.getIntProperty("i") != i) { failed = true; logger.warn("Expected message {} but got {}", i, message.getIntProperty("i")); } if (message.getBooleanProperty("large")) { - Assert.assertEquals(largeBody, message.getText()); + assertEquals(largeBody, message.getText()); } else { - Assert.assertEquals(smallBody, message.getText()); + assertEquals(smallBody, message.getText()); } logger.debug("Consumed {}, large={}", i, message.getBooleanProperty("large")); } session.commit(); - Assert.assertFalse(failed); + assertFalse(failed); if (expectEmpty) { - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/IdempotentACKTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/IdempotentACKTest.java index f8b0c41313..46bd815c91 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/IdempotentACKTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/IdempotentACKTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; @@ -44,10 +47,9 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -103,7 +105,7 @@ public class IdempotentACKTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); } - @BeforeClass + @BeforeAll public static void createServers() throws Exception { createServer(DC1_NODE_A, "mirror", DC2_NODEA_URI, 0); createServer(DC2_NODE_A, "mirror", DC1_NODEA_URI, 2); @@ -117,7 +119,7 @@ public class IdempotentACKTest extends SoakTestBase { ServerUtil.waitForServerToStart(2, 10_000); } - @Before + @BeforeEach public void cleanupServers() { cleanupData(DC1_NODE_A); cleanupData(DC2_NODE_A); @@ -171,7 +173,7 @@ public class IdempotentACKTest extends SoakTestBase { final int messagesPerConsumer = 30; // Just a reminder: if you change number on this test, this needs to be true: - Assert.assertEquals("Invalid test config", 0, numberOfMessages % consumers); + assertEquals(0, numberOfMessages % consumers, "Invalid test config"); AtomicBoolean running = new AtomicBoolean(true); runAfter(() -> running.set(false)); @@ -217,11 +219,11 @@ public class IdempotentACKTest extends SoakTestBase { sendDone.countDown(); }); - Assert.assertTrue(killSend.await(50, TimeUnit.SECONDS)); + assertTrue(killSend.await(50, TimeUnit.SECONDS)); restartDC1_ServerA(); - Assert.assertTrue(sendDone.await(50, TimeUnit.SECONDS)); + assertTrue(sendDone.await(50, TimeUnit.SECONDS)); SimpleManagement simpleManagementDC1A = new SimpleManagement(DC1_NODEA_URI, null, null); SimpleManagement simpleManagementDC2A = new SimpleManagement(DC2_NODEA_URI, null, null); @@ -271,11 +273,11 @@ public class IdempotentACKTest extends SoakTestBase { executor.execute(runnableConsumer); } - Assert.assertTrue(latchKill.await(10, TimeUnit.SECONDS)); + assertTrue(latchKill.await(10, TimeUnit.SECONDS)); restartDC1_ServerA(); - Assert.assertTrue(latchDone.await(4, TimeUnit.MINUTES)); + assertTrue(latchDone.await(4, TimeUnit.MINUTES)); long flushedMessages = 0; @@ -302,7 +304,7 @@ public class IdempotentACKTest extends SoakTestBase { private void restartDC1_ServerA() throws Exception { processDC1_node_A.destroyForcibly(); - Assert.assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); + assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); processDC1_node_A = startServer(DC1_NODE_A, -1, -1, new File(getServerLocation(DC1_NODE_A), "broker.properties")); ServerUtil.waitForServerToStart(0, 10_000); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/InterruptedLargeMessageTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/InterruptedLargeMessageTest.java index 2173258372..33a2c92eac 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/InterruptedLargeMessageTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/InterruptedLargeMessageTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -44,10 +48,10 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.FileUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -124,27 +128,29 @@ public class InterruptedLargeMessageTest extends SoakTestBase { insert = insertWriter.toString(); } - Assert.assertTrue(FileUtil.findReplace(new File(getServerLocation(serverName), "./etc/broker.xml"), "", insert)); + assertTrue(FileUtil.findReplace(new File(getServerLocation(serverName), "./etc/broker.xml"), "", insert)); } - @BeforeClass + @BeforeAll public static void createServers() throws Exception { createServer(DC1_NODE_A, "mirror", DC2_NODEA_URI, 0); createServer(DC2_NODE_A, "mirror", DC1_NODEA_URI, 2); } - @Before + @BeforeEach public void cleanupServers() { cleanupData(DC1_NODE_A); cleanupData(DC2_NODE_A); } - @Test(timeout = 240_000L) + @Test + @Timeout(value = 240_000L, unit = TimeUnit.MILLISECONDS) public void testAMQP() throws Exception { testInterrupt("AMQP"); } - @Test(timeout = 240_000L) + @Test + @Timeout(value = 240_000L, unit = TimeUnit.MILLISECONDS) public void testCORE() throws Exception { testInterrupt("CORE"); } @@ -246,8 +252,8 @@ public class InterruptedLargeMessageTest extends SoakTestBase { MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); for (int i = 0; i < numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(i, message.getIntProperty("id")); + assertNotNull(message); + assertEquals(i, message.getIntProperty("id")); if (i % 10 == 0) { session.commit(); logger.debug("Received {} messages", i); @@ -267,7 +273,7 @@ public class InterruptedLargeMessageTest extends SoakTestBase { int getNumberOfLargeMessages(String serverName) throws Exception { File lmFolder = new File(getServerLocation(serverName) + "/data/large-messages"); - Assert.assertTrue(lmFolder.exists()); + assertTrue(lmFolder.exists()); return lmFolder.list().length; } @@ -278,12 +284,12 @@ public class InterruptedLargeMessageTest extends SoakTestBase { private void stopDC1() throws Exception { processDC1_node_A.destroyForcibly(); - Assert.assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); + assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); } private void stopDC2() throws Exception { processDC2_node_A.destroyForcibly(); - Assert.assertTrue(processDC2_node_A.waitFor(10, TimeUnit.SECONDS)); + assertTrue(processDC2_node_A.waitFor(10, TimeUnit.SECONDS)); } private void startDC2() throws Exception { diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/MultiMirrorSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/MultiMirrorSoakTest.java index 2ddf9713c3..7930ea8fd6 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/MultiMirrorSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/MultiMirrorSoakTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -24,6 +28,7 @@ import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; + import java.io.File; import java.io.StringWriter; import java.lang.invoke.MethodHandles; @@ -37,8 +42,7 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.FileUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -103,11 +107,11 @@ public class MultiMirrorSoakTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); File brokerXml = new File(serverLocation, "/etc/broker.xml"); - Assert.assertTrue(brokerXml.exists()); + assertTrue(brokerXml.exists()); // Adding redistribution delay to broker configuration - Assert.assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); + assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); if (paging) { - Assert.assertTrue(FileUtil.findReplace(brokerXml, "-1", "1")); + assertTrue(FileUtil.findReplace(brokerXml, "-1", "1")); } } @@ -141,7 +145,7 @@ public class MultiMirrorSoakTest extends SoakTestBase { public void internalMirror(String producerURI, String consumerURi) throws Exception { final int numberOfMessages = 200; - Assert.assertTrue("numberOfMessages must be even", numberOfMessages % 2 == 0); + assertTrue(numberOfMessages % 2 == 0, "numberOfMessages must be even"); ConnectionFactory producerCF = CFUtil.createConnectionFactory("amqp", producerURI); @@ -202,9 +206,9 @@ public class MultiMirrorSoakTest extends SoakTestBase { large = false; } message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(i, message.getIntProperty("i")); - Assert.assertEquals(large, message.getBooleanProperty("large")); + assertNotNull(message); + assertEquals(i, message.getIntProperty("i")); + assertEquals(large, message.getBooleanProperty("large")); if (i % 100 == 0) { logger.debug("commit {}", i); session.commit(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/PagedSNFSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/PagedSNFSoakTest.java index d42be07a99..54a39d28dc 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/PagedSNFSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/PagedSNFSoakTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; @@ -39,10 +43,10 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,24 +112,26 @@ public class PagedSNFSoakTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); } - @BeforeClass + @BeforeAll public static void createServers() throws Exception { createServer(DC1_NODE_A, "mirror", DC2_NODEA_URI, 0); createServer(DC2_NODE_A, "mirror", DC1_NODEA_URI, 2); } - @Before + @BeforeEach public void cleanupServers() { cleanupData(DC1_NODE_A); cleanupData(DC2_NODE_A); } - @Test(timeout = 240_000L) + @Test + @Timeout(value = 240_000L, unit = TimeUnit.MILLISECONDS) public void testAMQP() throws Exception { testAccumulateAndSend("AMQP"); } - @Test(timeout = 240_000L) + @Test + @Timeout(value = 240_000L, unit = TimeUnit.MILLISECONDS) public void testCORE() throws Exception { testAccumulateAndSend("CORE"); } @@ -235,7 +241,7 @@ public class PagedSNFSoakTest extends SoakTestBase { MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); for (int i = 0; i < numberOfMessages; i++) { Message message = consumer.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); if (i > 0 && i % batchSize == 0) { logger.debug("Commit consume {}", i); session.commit(); @@ -258,9 +264,9 @@ public class PagedSNFSoakTest extends SoakTestBase { try (MessageConsumer consumer = session.createConsumer(queue)) { for (int i = 0; i < numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(10_000); - Assert.assertNotNull(message); - Assert.assertEquals(body, message.getText()); - Assert.assertEquals(i, message.getIntProperty("id")); + assertNotNull(message); + assertEquals(body, message.getText()); + assertEquals(i, message.getIntProperty("id")); logger.debug("received {}", i); if ((i + 1) % 10 == 0) { session.commit(); @@ -301,7 +307,7 @@ public class PagedSNFSoakTest extends SoakTestBase { int getNumberOfLargeMessages(String serverName) throws Exception { File lmFolder = new File(getServerLocation(serverName) + "/data/large-messages"); - Assert.assertTrue(lmFolder.exists()); + assertTrue(lmFolder.exists()); return lmFolder.list().length; } @@ -312,12 +318,12 @@ public class PagedSNFSoakTest extends SoakTestBase { private void stopDC1() throws Exception { processDC1_node_A.destroyForcibly(); - Assert.assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); + assertTrue(processDC1_node_A.waitFor(10, TimeUnit.SECONDS)); } private void stopDC2() throws Exception { processDC2_node_A.destroyForcibly(); - Assert.assertTrue(processDC2_node_A.waitFor(10, TimeUnit.SECONDS)); + assertTrue(processDC2_node_A.waitFor(10, TimeUnit.SECONDS)); } private void startDC2() throws Exception { diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ReplicatedMirrorTargetTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ReplicatedMirrorTargetTest.java index 3a1cea632b..5a4952462d 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ReplicatedMirrorTargetTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/ReplicatedMirrorTargetTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -48,9 +53,8 @@ import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.actors.OrderedExecutor; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,7 +104,7 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { volatile Process processDC2; volatile Process processDC2_REPLICA; - @After + @AfterEach public void destroyServers() throws Exception { if (processDC1 != null) { processDC1.destroyForcibly(); @@ -171,9 +175,9 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); File brokerXml = new File(serverLocation, "/etc/broker.xml"); - Assert.assertTrue(brokerXml.exists()); + assertTrue(brokerXml.exists()); // Adding redistribution delay to broker configuration - Assert.assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); + assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); if (TRACE_LOGS) { replaceLogs(serverLocation); @@ -183,7 +187,7 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { private static void replaceLogs(File serverLocation) throws Exception { File log4j = new File(serverLocation, "/etc/log4j2.properties"); - Assert.assertTrue(FileUtil.findReplace(log4j, "logger.artemis_utils.level=INFO", "logger.artemis_utils.level=INFO\n" + + assertTrue(FileUtil.findReplace(log4j, "logger.artemis_utils.level=INFO", "logger.artemis_utils.level=INFO\n" + "\n" + "logger.endpoint.name=org.apache.activemq.artemis.core.replication.ReplicationEndpoint\n" + "logger.endpoint.level=DEBUG\n" + "appender.console.filter.threshold.type = ThresholdFilter\n" @@ -210,9 +214,9 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { cliCreateServer.createServer(); File brokerXml = new File(serverLocation, "/etc/broker.xml"); - Assert.assertTrue(brokerXml.exists()); + assertTrue(brokerXml.exists()); // Adding redistribution delay to broker configuration - Assert.assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); + assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); if (TRACE_LOGS) { replaceLogs(serverLocation); @@ -243,7 +247,7 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { startServers(); - Assert.assertTrue(KILL_INTERVAL > SEND_COMMIT || KILL_INTERVAL < 0); + assertTrue(KILL_INTERVAL > SEND_COMMIT || KILL_INTERVAL < 0); String clientIDA = "nodeA"; String clientIDB = "nodeB"; @@ -353,9 +357,9 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { server.getStorageManager().getMessageJournal().scheduleCompactAndBlock(10_000); HashMap records = countJournal(server.getConfiguration()); AtomicInteger duplicateRecordsCount = records.get((int) JournalRecordIds.DUPLICATE_ID); - Assert.assertNotNull(duplicateRecordsCount); + assertNotNull(duplicateRecordsCount); // 1000 credits by default - Assert.assertTrue(duplicateRecordsCount.get() <= 1000); + assertTrue(duplicateRecordsCount.get() <= 1000); } @@ -379,7 +383,7 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { for (int i = start; i < start + numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(10_000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); if (message.getIntProperty("i") != i) { failed = true; @@ -398,10 +402,10 @@ public class ReplicatedMirrorTargetTest extends SoakTestBase { } session.commit(); - Assert.assertFalse(failed); + assertFalse(failed); if (expectEmpty) { - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/SingleMirrorSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/SingleMirrorSoakTest.java index fd75f66c9f..36a38e7b25 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/SingleMirrorSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/mirror/SingleMirrorSoakTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.mirror; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -24,6 +29,7 @@ import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; + import java.io.File; import java.io.StringWriter; import java.lang.invoke.MethodHandles; @@ -48,9 +54,8 @@ import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.actors.OrderedExecutor; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,7 +103,7 @@ public class SingleMirrorSoakTest extends SoakTestBase { volatile Process processDC1; volatile Process processDC2; - @After + @AfterEach public void destroyServers() throws Exception { if (processDC1 != null) { processDC1.destroyForcibly(); @@ -157,13 +162,13 @@ public class SingleMirrorSoakTest extends SoakTestBase { saveProperties(brokerProperties, brokerPropertiesFile); File brokerXml = new File(serverLocation, "/etc/broker.xml"); - Assert.assertTrue(brokerXml.exists()); + assertTrue(brokerXml.exists()); // Adding redistribution delay to broker configuration - Assert.assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); + assertTrue(FileUtil.findReplace(brokerXml, "", "\n\n" + " 0 \n")); if (TRACE_LOGS) { File log4j = new File(serverLocation, "/etc/log4j2.properties"); - Assert.assertTrue(FileUtil.findReplace(log4j, "logger.artemis_utils.level=INFO", "logger.artemis_utils.level=INFO\n" + + assertTrue(FileUtil.findReplace(log4j, "logger.artemis_utils.level=INFO", "logger.artemis_utils.level=INFO\n" + "\n" + "logger.ack.name=org.apache.activemq.artemis.protocol.amqp.connect.mirror.AckManager\n" + "logger.ack.level=TRACE\n" + "logger.config.name=org.apache.activemq.artemis.core.config.impl.ConfigurationImpl\n" @@ -199,7 +204,7 @@ public class SingleMirrorSoakTest extends SoakTestBase { startServers(); - Assert.assertTrue(KILL_INTERVAL > SEND_COMMIT || KILL_INTERVAL < 0); + assertTrue(KILL_INTERVAL > SEND_COMMIT || KILL_INTERVAL < 0); String clientIDA = "nodeA"; String clientIDB = "nodeB"; @@ -303,9 +308,9 @@ public class SingleMirrorSoakTest extends SoakTestBase { server.getStorageManager().getMessageJournal().scheduleCompactAndBlock(10_000); HashMap records = countJournal(server.getConfiguration()); AtomicInteger duplicateRecordsCount = records.get((int) JournalRecordIds.DUPLICATE_ID); - Assert.assertNotNull(duplicateRecordsCount); + assertNotNull(duplicateRecordsCount); // 1000 credits by default - Assert.assertTrue(duplicateRecordsCount.get() <= 1000); + assertTrue(duplicateRecordsCount.get() <= 1000); } @@ -329,7 +334,7 @@ public class SingleMirrorSoakTest extends SoakTestBase { for (int i = start; i < start + numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(10_000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); if (message.getIntProperty("i") != i) { failed = true; @@ -348,10 +353,10 @@ public class SingleMirrorSoakTest extends SoakTestBase { } session.commit(); - Assert.assertFalse(failed); + assertFalse(failed); if (expectEmpty) { - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); } } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/sender/SenderSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/sender/SenderSoakTest.java index ae0a4364dc..aebbc38496 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/sender/SenderSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/brokerConnection/sender/SenderSoakTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.soak.brokerConnection.sender; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -33,8 +36,7 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -127,7 +129,7 @@ public class SenderSoakTest extends SoakTestBase { final int numberOfMessages = 1000; - Assert.assertTrue("numberOfMessages must be even", numberOfMessages % 2 == 0); + assertTrue(numberOfMessages % 2 == 0, "numberOfMessages must be even"); ConnectionFactory connectionFactoryDC1A = CFUtil.createConnectionFactory("amqp", "tcp://localhost:61616"); ConnectionFactory connectionFactoryDC2A = CFUtil.createConnectionFactory("amqp", "tcp://localhost:61618"); @@ -168,7 +170,7 @@ public class SenderSoakTest extends SoakTestBase { for (int i = 0; i < numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); + assertNotNull(message); logger.debug("Received message {}, large={}", message.getIntProperty("i"), message.getBooleanProperty("large")); } session.commit(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientCrashMassiveRollbackTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientCrashMassiveRollbackTest.java index 9d25268153..f501a13824 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientCrashMassiveRollbackTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientCrashMassiveRollbackTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.soak.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.Queue; @@ -36,9 +38,8 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.critical.CriticalAnalyzerPolicy; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ClientCrashMassiveRollbackTest extends ActiveMQTestBase { protected ActiveMQServer server; @@ -47,7 +48,7 @@ public class ClientCrashMassiveRollbackTest extends ActiveMQTestBase { protected ServerLocator locator; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); Configuration config = createDefaultNettyConfig(); @@ -111,8 +112,8 @@ public class ClientCrashMassiveRollbackTest extends ActiveMQTestBase { thread.interrupt(); - Assert.assertEquals(messageCount, queueControl.getMessageCount()); - Assert.assertEquals(ActiveMQServer.SERVER_STATE.STARTED, server.getState()); + assertEquals(messageCount, queueControl.getMessageCount()); + assertEquals(ActiveMQServer.SERVER_STATE.STARTED, server.getState()); server.stop(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java index 331897f234..88af8fd566 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientNonDivertedSoakTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.soak.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -30,8 +32,8 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -55,7 +57,7 @@ public class ClientNonDivertedSoakTest extends ActiveMQTestBase { private ActiveMQServer server; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java index 28c5ab611f..11e9ff4710 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/ClientSoakTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.soak.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -32,8 +34,8 @@ import org.apache.activemq.artemis.core.config.DivertConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -61,7 +63,7 @@ public class ClientSoakTest extends ActiveMQTestBase { private ActiveMQServer server; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); clearDataRecreateServerDirs(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/LargeMessageSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/LargeMessageSoakTest.java index 7e625c1fa6..5fd794e745 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/LargeMessageSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/LargeMessageSoakTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.client; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -33,8 +37,8 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,6 +48,7 @@ public class LargeMessageSoakTest extends ActiveMQTestBase { ActiveMQServer server; + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -117,12 +122,12 @@ public class LargeMessageSoakTest extends ActiveMQTestBase { while (textMessage == null); - Assert.assertNotNull(textMessage); + assertNotNull(textMessage); if (logger.isDebugEnabled()) { logger.debug("Consumer Thread {} received {} messages, protocol={}", localT, i, protocol); } // Since all messages come from the same queue on all consumers, this is the only assertion possible for the message - Assert.assertEquals(largetext, textMessage.getText()); + assertEquals(largetext, textMessage.getText()); } } } catch (Throwable e) { @@ -157,8 +162,8 @@ public class LargeMessageSoakTest extends ActiveMQTestBase { }); } - Assert.assertTrue(done.await(5, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(done.await(5, TimeUnit.MINUTES)); + assertEquals(0, errors.get()); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java index 55b402b683..ba74771ffe 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/client/SimpleSendReceiveSoakTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.soak.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.util.HashMap; import org.apache.activemq.artemis.api.core.QueueConfiguration; @@ -30,8 +33,8 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SimpleSendReceiveSoakTest extends ActiveMQTestBase { @@ -51,7 +54,7 @@ public class SimpleSendReceiveSoakTest extends ActiveMQTestBase { private ActiveMQServer server; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clientFailure/ClientFailureSoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clientFailure/ClientFailureSoakTest.java index ef16da818e..3884608e90 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clientFailure/ClientFailureSoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clientFailure/ClientFailureSoakTest.java @@ -17,6 +17,14 @@ package org.apache.activemq.artemis.tests.soak.clientFailure; +import static org.apache.activemq.artemis.utils.TestParameters.testProperty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -40,24 +48,21 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; import org.apache.activemq.artemis.api.core.management.SimpleManagement; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.activemq.artemis.utils.TestParameters.testProperty; - -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class ClientFailureSoakTest extends SoakTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @@ -68,7 +73,7 @@ public class ClientFailureSoakTest extends SoakTestBase { private static File brokerPropertiesFile; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File serverLocation = getFileServerLocation(SERVER_NAME_0); deleteDirectory(serverLocation); @@ -103,7 +108,7 @@ public class ClientFailureSoakTest extends SoakTestBase { private final int NUMBER_OF_MESSAGES; private final String MEMORY_CLIENT; - @Parameterized.Parameters(name = "protocol={0}") + @Parameters(name = "protocol={0}") public static Collection parameters() { String[] protocols = PROTOCOL_LIST.split(","); @@ -116,9 +121,9 @@ public class ClientFailureSoakTest extends SoakTestBase { return parameters; } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 30_000, brokerPropertiesFile); @@ -137,7 +142,7 @@ public class ClientFailureSoakTest extends SoakTestBase { MEMORY_CLIENT = testProperty(TEST_NAME, protocol + "_MEMORY_CLIENT", "-Xmx128m"); } - @Test + @TestTemplate public void testSoakClientFailures() throws Exception { SimpleManagement simpleManagement = new SimpleManagement("tcp://localhost:61616", null, null); @@ -197,8 +202,8 @@ public class ClientFailureSoakTest extends SoakTestBase { logger.info("\n*******************************************************************************************************************************" + "\nThread {} iteration {}" + "\n*******************************************************************************************************************************", threadID, it); Process process = SpawnedVMSupport.spawnVM(null, null, ClientFailureSoakTestClient.class.getName(), "-Xms128m", MEMORY_CLIENT, new String[]{}, true, true, protocol, String.valueOf(THREADS_PER_VM), String.valueOf(CLIENT_CONSUMERS_PER_THREAD), QUEUE_NAME); logger.info("Started process"); - Assert.assertTrue(process.waitFor(10, TimeUnit.HOURS)); - Assert.assertEquals(ClientFailureSoakTestClient.RETURN_OK, process.exitValue()); + assertTrue(process.waitFor(10, TimeUnit.HOURS)); + assertEquals(ClientFailureSoakTestClient.RETURN_OK, process.exitValue()); } } catch (Throwable throwable) { logger.warn(throwable.getMessage(), throwable); @@ -209,7 +214,7 @@ public class ClientFailureSoakTest extends SoakTestBase { }); } - Assert.assertTrue(done.await(10, TimeUnit.HOURS)); + assertTrue(done.await(10, TimeUnit.HOURS)); if (errors.get() != 0) { logger.warn("There were errors in previous executions:: {}. We will look into the receiving part now, but beware of previous errors", errors.get()); @@ -240,15 +245,15 @@ public class ClientFailureSoakTest extends SoakTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { Message message = consumer.receive(60_000); - Assert.assertNotNull(message); + assertNotNull(message); if (!receivedIDs.add(message.getIntProperty("i"))) { logger.warn("Message {} received in duplicate", message.getIntProperty("i")); - Assert.fail("Message " + message.getIntProperty("i") + " received in duplicate"); + fail("Message " + message.getIntProperty("i") + " received in duplicate"); } if (i != message.getIntProperty("i")) { - Assert.fail("Message " + message.getIntProperty("i") + " received out of order, when it was supposed to be " + i + " with body size = " + ((TextMessage) message).getText().length()); + fail("Message " + message.getIntProperty("i") + " received out of order, when it was supposed to be " + i + " with body size = " + ((TextMessage) message).getText().length()); logger.info("message {} received out of order. Expected {}", message.getIntProperty("i"), i); outOfOrder++; } @@ -258,15 +263,15 @@ public class ClientFailureSoakTest extends SoakTestBase { } } logger.info("Received {} messages outOfOrder", outOfOrder); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.rollback(); - Assert.assertEquals(0, outOfOrder); + assertEquals(0, outOfOrder); } Wait.assertEquals(0, () -> simpleManagement.getDeliveringCountOnQueue(QUEUE_NAME), 10_000, 100); Wait.assertEquals(0, () -> simpleManagement.getNumberOfConsumersOnQueue(QUEUE_NAME), 10_000, 100); Wait.assertEquals((long) NUMBER_OF_MESSAGES, () -> simpleManagement.getMessageCountOnQueue(QUEUE_NAME), 10_000, 500); - Assert.assertEquals("There were errors in the consumers", 0, errors.get()); + assertEquals(0, errors.get(), "There were errors in the consumers"); } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clusterNotificationsContinuity/ClusterNotificationsContinuityTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clusterNotificationsContinuity/ClusterNotificationsContinuityTest.java index 181303adf6..9f183dbecb 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clusterNotificationsContinuity/ClusterNotificationsContinuityTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/clusterNotificationsContinuity/ClusterNotificationsContinuityTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.clusterNotificationsContinuity; +import static org.apache.activemq.artemis.utils.TestParameters.testProperty; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.MessageListener; import javax.jms.Queue; @@ -39,19 +43,15 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jms.connection.CachingConnectionFactory; import org.springframework.jms.listener.DefaultMessageListenerContainer; -import static org.apache.activemq.artemis.utils.TestParameters.testProperty; - /** * Refer to ./scripts/parameters.sh for suggested parameters * @@ -77,7 +77,7 @@ public class ClusterNotificationsContinuityTest extends SoakTestBase { private final Process[] serverProcesses = new Process[NUMBER_OF_SERVERS]; private Process dmlcProcess; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { for (int s = 0; s < NUMBER_OF_SERVERS; s++) { String serverName = SERVER_NAME_BASE + s; @@ -128,9 +128,9 @@ public class ClusterNotificationsContinuityTest extends SoakTestBase { } } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); for (int i = 0; i < NUMBER_OF_SERVERS; i++) { String serverName = SERVER_NAME_BASE + i; @@ -187,12 +187,12 @@ public class ClusterNotificationsContinuityTest extends SoakTestBase { String serverName = SERVER_NAME_BASE + i; File artemisLog = new File("target/" + serverName + "/log/artemis.log"); - Assert.assertFalse(findLogRecord(artemisLog, "AMQ224037")); + assertFalse(findLogRecord(artemisLog, "AMQ224037")); } } - @After + @AfterEach public void cleanup() { SpawnedVMSupport.forceKill(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interrupt/JournalFlushInterruptTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interrupt/JournalFlushInterruptTest.java index e0cb69ab49..beb07ff5ca 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interrupt/JournalFlushInterruptTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interrupt/JournalFlushInterruptTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.soak.interrupt; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; @@ -33,17 +35,16 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; public class JournalFlushInterruptTest extends SoakTestBase { public static final String SERVER_NAME_0 = "interruptjf"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { File server0Location = getFileServerLocation(SERVER_NAME_0); @@ -65,7 +66,7 @@ public class JournalFlushInterruptTest extends SoakTestBase { static ObjectNameBuilder nameBuilder = ObjectNameBuilder.create(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), "jfinterrupt", true); Process serverProcess; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 30000); @@ -96,7 +97,7 @@ public class JournalFlushInterruptTest extends SoakTestBase { Thread.sleep(100); killProcess(serverProcess); - Assert.assertTrue(serverProcess.waitFor(1, TimeUnit.MINUTES)); + assertTrue(serverProcess.waitFor(1, TimeUnit.MINUTES)); serverProcess = startServer(SERVER_NAME_0, 0, 0); waitForServerToStart("tcp://localhost:61616", "artemis", "artemis", 5000); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/ClusteredLargeMessageInterruptTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/ClusteredLargeMessageInterruptTest.java index a938ee821e..f6ff2a70d1 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/ClusteredLargeMessageInterruptTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/ClusteredLargeMessageInterruptTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.soak.interruptlm; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -41,10 +44,9 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,7 +56,7 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { public static final String SERVER_NAME_0 = "lmbroker1"; public static final String SERVER_NAME_1 = "lmbroker2"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -124,7 +126,7 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -295,9 +297,9 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { killProcess(serverProcess, useKill); runningSend = false; runningConsumer = false; - Assert.assertTrue(serverProcess.waitFor(10, TimeUnit.SECONDS)); - Assert.assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(sendDone.await(10, TimeUnit.SECONDS)); + assertTrue(serverProcess.waitFor(10, TimeUnit.SECONDS)); + assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); + assertTrue(sendDone.await(10, TimeUnit.SECONDS)); logger.info("All receivers and senders are done!!!"); @@ -309,11 +311,11 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { receiverDone = startConsumingThreads(executorService, protocol, 1, CONSUMING_THREADS, tx, queueName); killProcess(serverProcess2, useKill); - Assert.assertTrue(serverProcess2.waitFor(10, TimeUnit.SECONDS)); + assertTrue(serverProcess2.waitFor(10, TimeUnit.SECONDS)); runningSend = false; runningConsumer = false; - Assert.assertTrue(sendDone.await(1, TimeUnit.MINUTES)); - Assert.assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); + assertTrue(sendDone.await(1, TimeUnit.MINUTES)); + assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); serverProcess2 = startServer1(); @@ -322,7 +324,7 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { Thread.sleep(2000); runningSend = false; - Assert.assertTrue(sendDone.await(10, TimeUnit.SECONDS)); + assertTrue(sendDone.await(10, TimeUnit.SECONDS)); QueueControl queueControl1 = getQueueControl(server1URI, builderServer1, queueName, queueName, RoutingType.ANYCAST, 5000); QueueControl queueControl2 = getQueueControl(server2URI, builderServer2, queueName, queueName, RoutingType.ANYCAST, 5000); @@ -333,12 +335,12 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { Wait.waitFor(() -> queueControl1.getMessageCount() == 0 && queueControl2.getMessageCount() == 0 && lmFolder.listFiles().length == 0 && lmFolder2.listFiles().length == 0); runningConsumer = false; - Assert.assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); + assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); // no need to use wait here, the previous check should have checked that already - Assert.assertEquals(0, lmFolder.listFiles().length); - Assert.assertEquals(0, lmFolder2.listFiles().length); - Assert.assertEquals(0, errors.get()); + assertEquals(0, lmFolder.listFiles().length); + assertEquals(0, lmFolder2.listFiles().length); + assertEquals(0, errors.get()); } @Test @@ -381,18 +383,18 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { runningSend = runningConsumer = false; killProcess(serverProcess, false); - Assert.assertTrue(serverProcess.waitFor(10, TimeUnit.MINUTES)); - Assert.assertTrue(sendDone.await(10, TimeUnit.SECONDS)); + assertTrue(serverProcess.waitFor(10, TimeUnit.MINUTES)); + assertTrue(sendDone.await(10, TimeUnit.SECONDS)); sendDone = startSendingThreads(executorService, protocol, 1, SENDING_THREADS, tx, queueName); CountDownLatch receiverDone = startConsumingThreads(executorService, protocol, 1, CONSUMING_THREADS, tx, queueName); killProcess(serverProcess, false); - Assert.assertTrue(serverProcess.waitFor(10, TimeUnit.SECONDS)); + assertTrue(serverProcess.waitFor(10, TimeUnit.SECONDS)); serverProcess = startServer0(); Thread.sleep(5000); runningSend = false; - Assert.assertTrue(sendDone.await(10, TimeUnit.SECONDS)); + assertTrue(sendDone.await(10, TimeUnit.SECONDS)); QueueControl queueControl1 = getQueueControl(server1URI, builderServer1, queueName, queueName, RoutingType.ANYCAST, 5000); QueueControl queueControl2 = getQueueControl(server2URI, builderServer2, queueName, queueName, RoutingType.ANYCAST, 5000); @@ -403,7 +405,7 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { Wait.assertTrue(() -> queueControl1.getMessageCount() == 0 && queueControl2.getMessageCount() == 0); runningConsumer = false; - Assert.assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); + assertTrue(receiverDone.await(10, TimeUnit.SECONDS)); Wait.assertEquals(0, () -> lmFolder.listFiles().length); @@ -411,7 +413,7 @@ public class ClusteredLargeMessageInterruptTest extends SoakTestBase { logger.info("queueControl2.count={}", queueControl2.getMessageCount()); return lmFolder2.listFiles().length; }); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageFrozenTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageFrozenTest.java index b4e100687a..a885377ada 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageFrozenTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageFrozenTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.interruptlm; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -40,9 +45,8 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.tests.util.TcpProxy; import org.apache.activemq.artemis.utils.Wait; import org.apache.qpid.jms.JmsConnectionFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +59,7 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { ActiveMQServer server; - @Before + @BeforeEach public void startServer() throws Exception { server = createServer(true, true); server.getConfiguration().addAcceptorConfiguration("alternate", "tcp://localhost:44444?amqpIdleTimeout=100"); @@ -87,9 +91,9 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { switch (protocol.toUpperCase(Locale.ROOT)) { case "CORE": ActiveMQConnectionFactory artemisfactory = new ActiveMQConnectionFactory("tcp://localhost:33333?connectionTTL=1000&clientFailureCheckPeriod=100&consumerWindowSize=1000"); - Assert.assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); + assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); + assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); + assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); factory = artemisfactory; break; case "AMQP": @@ -107,8 +111,8 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Queue queue = session.createQueue(getName()); - Assert.assertEquals(1, proxy.getInboundHandlers().size()); - Assert.assertEquals(1, proxy.getOutbounddHandlers().size()); + assertEquals(1, proxy.getInboundHandlers().size()); + assertEquals(1, proxy.getOutbounddHandlers().size()); String body; { @@ -135,7 +139,7 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { for (int repeat = 0; repeat < 5; repeat++) { try { for (int i = 0; i < 1; i++) { - Assert.assertNotNull(consumer.receive(1000)); + assertNotNull(consumer.receive(1000)); } proxy.stopAllHandlers(); consumer.receive(100); @@ -145,7 +149,7 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { failed = true; } - Assert.assertTrue(failed); + assertTrue(failed); server.getRemotingService().getConnections().forEach(r -> r.fail(new ActiveMQException("forced failure"))); connection = factory.createConnection(); @@ -157,8 +161,8 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(body, message.getText()); + assertNotNull(message); + assertEquals(body, message.getText()); session.commit(); } @@ -189,9 +193,9 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { switch (protocol.toUpperCase(Locale.ROOT)) { case "CORE": ActiveMQConnectionFactory artemisfactory = new ActiveMQConnectionFactory("tcp://localhost:44444?connectionTTL=1000&clientFailureCheckPeriod=100&consumerWindowSize=1000"); - Assert.assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); + assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); + assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); + assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); factory = artemisfactory; break; case "AMQP": @@ -235,13 +239,13 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { MessageConsumer consumer = session.createConsumer(queue); connection.start(); - Assert.assertEquals(1, serverQueue.getConsumers().size()); + assertEquals(1, serverQueue.getConsumers().size()); ServerConsumerImpl serverConsumer = (ServerConsumerImpl) serverQueue.getConsumers().iterator().next(); TextMessage message = (TextMessage) consumer.receive(100); - Assert.assertNotNull(message); - Assert.assertEquals(body, message.getText()); + assertNotNull(message); + assertEquals(body, message.getText()); serverConsumer.errorProcessing(new Exception("Dumb error"), queueMessages.get(0)); @@ -263,16 +267,16 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { for (int i = 0; i < recCount; i++) { TextMessage recMessage = (TextMessage)consumer.receive(5000); - Assert.assertNotNull(recMessage); - Assert.assertEquals(body, recMessage.getText()); + assertNotNull(recMessage); + assertEquals(body, recMessage.getText()); session.commit(); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); // I could have done this assert before the loop // but I also wanted to see a condition where messages get damaged - Assert.assertEquals(NUMBER_OF_MESSAGES, recCount); + assertEquals(NUMBER_OF_MESSAGES, recCount); Wait.assertEquals(0, serverQueue::getMessageCount); @@ -294,9 +298,9 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { switch (protocol.toUpperCase(Locale.ROOT)) { case "CORE": ActiveMQConnectionFactory artemisfactory = new ActiveMQConnectionFactory("tcp://localhost:33333?connectionTTL=1000&clientFailureCheckPeriod=100&consumerWindowSize=1000"); - Assert.assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); - Assert.assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); + assertEquals(100, artemisfactory.getServerLocator().getClientFailureCheckPeriod()); + assertEquals(1000, artemisfactory.getServerLocator().getConnectionTTL()); + assertEquals(1000, artemisfactory.getServerLocator().getConsumerWindowSize()); factory = artemisfactory; break; case "AMQP": @@ -314,8 +318,8 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = sessionConsumer.createQueue(getName()); - Assert.assertEquals(1, proxy.getInboundHandlers().size()); - Assert.assertEquals(1, proxy.getOutbounddHandlers().size()); + assertEquals(1, proxy.getInboundHandlers().size()); + assertEquals(1, proxy.getOutbounddHandlers().size()); String body; { @@ -357,7 +361,7 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { long numberOfMessages = serverQueue.getMessageCount(); - Assert.assertTrue(failed); + assertTrue(failed); connection = factory.createConnection(); connection.start(); @@ -368,13 +372,13 @@ public class LargeMessageFrozenTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(body, message.getText()); + assertNotNull(message); + assertEquals(body, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); - Assert.assertEquals(0L, serverQueue.getMessageCount()); + assertEquals(0L, serverQueue.getMessageCount()); Wait.assertEquals(0, () -> { System.gc(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageInterruptTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageInterruptTest.java index d7bc41604f..208696068e 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageInterruptTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/interruptlm/LargeMessageInterruptTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.interruptlm; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -40,10 +44,9 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +56,7 @@ public class LargeMessageInterruptTest extends SoakTestBase { public static final String SERVER_NAME_0 = "interruptlm"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -79,7 +82,7 @@ public class LargeMessageInterruptTest extends SoakTestBase { return CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616"); } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 30000); @@ -236,13 +239,13 @@ public class LargeMessageInterruptTest extends SoakTestBase { }); } - Assert.assertTrue(killAt.await(60, TimeUnit.SECONDS)); + assertTrue(killAt.await(60, TimeUnit.SECONDS)); killProcess(serverProcess); - Assert.assertTrue(serverProcess.waitFor(1, TimeUnit.MINUTES)); + assertTrue(serverProcess.waitFor(1, TimeUnit.MINUTES)); serverProcess = startServer(SERVER_NAME_0, 0, 0); - Assert.assertTrue(done.await(60, TimeUnit.SECONDS)); - Assert.assertEquals(0, errors.get()); + assertTrue(done.await(60, TimeUnit.SECONDS)); + assertEquals(0, errors.get()); QueueControl queueControl = getQueueControl(liveURI, nameBuilder, queueName, queueName, RoutingType.ANYCAST, 5000); @@ -255,13 +258,13 @@ public class LargeMessageInterruptTest extends SoakTestBase { connection.start(); for (int i = 0; i < numberOfMessages; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertTrue(message.getText().equals("forcePage") || message.getText().equals(largebody)); + assertNotNull(message); + assertTrue(message.getText().equals("forcePage") || message.getText().equals(largebody)); } } File lmFolder = new File(getServerLocation(SERVER_NAME_0) + "/data/large-messages"); - Assert.assertTrue(lmFolder.exists()); + assertTrue(lmFolder.exists()); Wait.assertEquals(0, () -> lmFolder.listFiles().length); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/mqtt/MQTT5SoakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/mqtt/MQTT5SoakTest.java index fa524f32f4..bd498d8e26 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/mqtt/MQTT5SoakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/mqtt/MQTT5SoakTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.soak.mqtt; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.lang.invoke.MethodHandles; import java.util.Arrays; @@ -37,10 +40,9 @@ import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence; import org.eclipse.paho.mqttv5.common.MqttException; import org.eclipse.paho.mqttv5.common.MqttMessage; import org.eclipse.paho.mqttv5.common.packet.MqttProperties; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,7 +54,7 @@ public class MQTT5SoakTest extends SoakTestBase { - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -72,7 +74,7 @@ public class MQTT5SoakTest extends SoakTestBase { return new MqttClient("tcp://localhost:1883", clientId, new MemoryPersistence()); } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); @@ -141,7 +143,7 @@ public class MQTT5SoakTest extends SoakTestBase { consumer.close(); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } protected interface DefaultMqttCallback extends MqttCallback { diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/owleak/OWLeakTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/owleak/OWLeakTest.java index 4a599a241b..c632d30149 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/owleak/OWLeakTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/owleak/OWLeakTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.owleak; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -36,18 +41,17 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,14 +63,14 @@ import static org.apache.activemq.artemis.utils.TestParameters.testProperty; * Even though this test is not testing Paging, it will use Page just to generate enough load to the server to compete for resources in Native Buffers. * */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class OWLeakTest extends SoakTestBase { private static final int OK = 33; // arbitrary code. if the spawn returns this the test went fine public static final String SERVER_NAME_0 = "openwire-leaktest"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -96,7 +100,7 @@ public class OWLeakTest extends SoakTestBase { MESSAGE_SIZE = TestParameters.testProperty(TEST_NAME, protocol + "_MESSAGE_SIZE", 10_000); } - @Parameterized.Parameters(name = "protocol={0}") + @Parameters(name = "protocol={0}") public static Collection parameters() { String[] protocols = PROTOCOL_LIST.split(","); @@ -109,9 +113,9 @@ public class OWLeakTest extends SoakTestBase { return parameters; } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 10_000); @@ -191,13 +195,13 @@ public class OWLeakTest extends SoakTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES * PRODUCERS; i++) { TextMessage message = (TextMessage) consumer.receive(60_000); - Assert.assertNotNull(message); + assertNotNull(message); int producerID = message.getIntProperty("producerID"); int sequence = message.getIntProperty("sequence"); logger.debug("Received message {} from producer {}", sequence, producerID); - Assert.assertEquals(producerSequence[producerID], sequence); + assertEquals(producerSequence[producerID], sequence); producerSequence[producerID]++; - Assert.assertEquals(createLMBody(MESSAGE_SIZE, producerID, sequence), message.getText()); + assertEquals(createLMBody(MESSAGE_SIZE, producerID, sequence), message.getText()); semaphore.release(); } @@ -232,7 +236,7 @@ public class OWLeakTest extends SoakTestBase { if (msg > 5000L) { message = (TextMessage) consumer.receive(10000); - Assert.assertNotNull(message); + assertNotNull(message); } if (msg % 100L == 0L) { @@ -255,9 +259,9 @@ public class OWLeakTest extends SoakTestBase { }); - Assert.assertTrue(latch.await(TEST_TIMEOUT_MINUTES, TimeUnit.MINUTES)); + assertTrue(latch.await(TEST_TIMEOUT_MINUTES, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); System.exit(OK); } catch (Throwable e) { @@ -266,14 +270,14 @@ public class OWLeakTest extends SoakTestBase { } } - @Test + @TestTemplate public void testValidateLeaks() throws Exception { // I am using a spawn for the test client, as this test will need a big VM for the client. // so I need control over the memory size for the VM. Process process = SpawnedVMSupport.spawnVM(OWLeakTest.class.getName(), new String[]{"-Xmx3G"}, "" + PRODUCERS, "" + NUMBER_OF_MESSAGES, "" + MESSAGE_SIZE, protocol); logger.debug("Process PID::{}", process.pid()); - Assert.assertTrue(process.waitFor(TEST_TIMEOUT_MINUTES, TimeUnit.MINUTES)); - Assert.assertEquals(OK, process.exitValue()); + assertTrue(process.waitFor(TEST_TIMEOUT_MINUTES, TimeUnit.MINUTES)); + assertEquals(OK, process.exitValue()); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/FlowControlPagingTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/FlowControlPagingTest.java index 8469a5be58..3ecc1cd07f 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/FlowControlPagingTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/FlowControlPagingTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -32,17 +36,16 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -53,7 +56,7 @@ import static org.apache.activemq.artemis.utils.TestParameters.testProperty; * Refer to ./scripts/parameters.sh for suggested parameters * #You may choose to use zip files to save some time on producing if you want to run this test over and over when debugging * export TEST_FLOW_ZIP_LOCATION=a folder */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class FlowControlPagingTest extends SoakTestBase { private static final String TEST_NAME = "FLOW"; @@ -78,7 +81,7 @@ public class FlowControlPagingTest extends SoakTestBase { public static final String SERVER_NAME_0 = "flowControlPaging"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -94,7 +97,7 @@ public class FlowControlPagingTest extends SoakTestBase { } - @Parameterized.Parameters(name = "protocol={0}") + @Parameters(name = "protocol={0}") public static Collection parameters() { String[] protocols = PROTOCOL_LIST.split(","); @@ -124,9 +127,9 @@ public class FlowControlPagingTest extends SoakTestBase { return "flow-data-" + protocol + "-" + MESSAGES + "-" + MESSAGE_SIZE + ".zip"; } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); cleanupData(SERVER_NAME_0); boolean useZip = ZIP_LOCATION != null; @@ -141,7 +144,7 @@ public class FlowControlPagingTest extends SoakTestBase { serverProcess = startServer(SERVER_NAME_0, 0, SERVER_START_TIMEOUT); } - @Test + @TestTemplate public void testFlow() throws Exception { String QUEUE_NAME = "QUEUE_FLOW"; ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616"); @@ -231,7 +234,7 @@ public class FlowControlPagingTest extends SoakTestBase { continue; } - Assert.assertEquals(m, message.getIntProperty("m")); + assertEquals(m, message.getIntProperty("m")); // The sending commit interval here will be used for printing if (PRINT_INTERVAL > 0 && m % PRINT_INTERVAL == 0) { @@ -258,8 +261,8 @@ public class FlowControlPagingTest extends SoakTestBase { connectionConsumer.start(); service.shutdown(); - Assert.assertTrue("Test Timed Out", service.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(service.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES), "Test Timed Out"); + assertEquals(0, errors.get()); connectionConsumer.close(); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/HorizontalPagingTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/HorizontalPagingTest.java index 4434d27bf2..08f20812cf 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/HorizontalPagingTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/HorizontalPagingTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.paging; +import static org.apache.activemq.artemis.utils.TestParameters.testProperty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -32,30 +37,27 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -import static org.apache.activemq.artemis.utils.TestParameters.testProperty; - /** * Refer to ./scripts/parameters.sh for suggested parameters * #You may choose to use zip files to save some time on producing if you want to run this test over and over when debugging * export TEST_HORIZONTAL_ZIP_LOCATION=a folder * */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class HorizontalPagingTest extends SoakTestBase { private static final String TEST_NAME = "HORIZONTAL"; @@ -81,7 +83,7 @@ public class HorizontalPagingTest extends SoakTestBase { public static final String SERVER_NAME_0 = "horizontalPaging"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -96,7 +98,7 @@ public class HorizontalPagingTest extends SoakTestBase { } } - @Parameterized.Parameters(name = "protocol={0}") + @Parameters(name = "protocol={0}") public static Collection parameters() { String[] protocols = PROTOCOL_LIST.split(","); @@ -128,9 +130,9 @@ public class HorizontalPagingTest extends SoakTestBase { return "horizontal-" + protocol + "-" + DESTINATIONS + "-" + MESSAGES + "-" + MESSAGE_SIZE + ".zip"; } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); cleanupData(SERVER_NAME_0); boolean useZip = ZIP_LOCATION != null; @@ -146,7 +148,7 @@ public class HorizontalPagingTest extends SoakTestBase { } - @Test + @TestTemplate public void testHorizontal() throws Exception { ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616"); AtomicInteger errors = new AtomicInteger(0); @@ -251,7 +253,7 @@ public class HorizontalPagingTest extends SoakTestBase { logger.info("Destination {} received {} {} messages", destination, m, protocol); } - Assert.assertEquals(m, message.getIntProperty("m")); + assertEquals(m, message.getIntProperty("m")); if (RECEIVE_COMMIT_INTERVAL > 0 && (m + 1) % RECEIVE_COMMIT_INTERVAL == 0) { sessionConsumer.commit(); @@ -274,9 +276,9 @@ public class HorizontalPagingTest extends SoakTestBase { connectionConsumer.start(); service.shutdown(); - Assert.assertTrue("Test Timed Out", service.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); - Assert.assertEquals(DESTINATIONS, completedFine.get()); + assertTrue(service.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES), "Test Timed Out"); + assertEquals(0, errors.get()); + assertEquals(DESTINATIONS, completedFine.get()); connectionConsumer.close(); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/M_and_M_FactoryTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/M_and_M_FactoryTest.java index 66bf606077..e37c283e34 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/M_and_M_FactoryTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/M_and_M_FactoryTest.java @@ -47,9 +47,9 @@ import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -62,7 +62,7 @@ public class M_and_M_FactoryTest extends SoakTestBase { private static final String JMX_SERVER_HOSTNAME = "localhost"; private static final int JMX_SERVER_PORT = 11099; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -115,7 +115,7 @@ public class M_and_M_FactoryTest extends SoakTestBase { Process serverProcess; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); disableCheckThread(); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/MegaCleanerPagingTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/MegaCleanerPagingTest.java index 3c7cdb9e96..8f8fa79f66 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/MegaCleanerPagingTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/MegaCleanerPagingTest.java @@ -17,6 +17,12 @@ package org.apache.activemq.artemis.tests.soak.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -42,8 +48,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -93,8 +98,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { // Using a spawn to limit memory consumption to the test Process process = SpawnedVMSupport.spawnVM(MegaCleanerPagingTest.class.getName(), new String[]{"-Xmx512M"}, getTestDir(), methodName); logger.debug("process PID {}", process.pid()); - Assert.assertTrue(process.waitFor(10, TimeUnit.MINUTES)); - Assert.assertEquals(OK, process.exitValue()); + assertTrue(process.waitFor(10, TimeUnit.MINUTES)); + assertEquals(OK, process.exitValue()); } // I am using a separate VM to limit memory.. @@ -148,11 +153,11 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(queueName); - Assert.assertNotNull(serverQueue); + assertNotNull(serverQueue); serverQueue.getPagingStore().startPaging(); ConnectionFactory cf = CFUtil.createConnectionFactory("core", "tcp://localhost:61616?consumerWindowSize=0"); - Assert.assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); + assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); final int SIZE = 10 * 1024; for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { @@ -173,8 +178,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES / 2; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(createBuffer(i, SIZE), message.getText()); + assertNotNull(message); + assertEquals(createBuffer(i, SIZE), message.getText()); if (i % 1000 == 0) { logger.debug("received {} messages", i); @@ -186,8 +191,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { server.stop(); - Assert.assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME - Assert.assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error + assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME + assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error } } @@ -212,11 +217,11 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(queueName); - Assert.assertNotNull(serverQueue); + assertNotNull(serverQueue); serverQueue.getPagingStore().startPaging(); ConnectionFactory cf = CFUtil.createConnectionFactory("core", "tcp://localhost:61616?consumerWindowSize=0"); - Assert.assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); + assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); final int SIZE = 10 * 1024; session.commit(); @@ -230,8 +235,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { for (int i = NUMBER_OF_MESSAGES / 2; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(createBuffer(i, SIZE), message.getText()); + assertNotNull(message); + assertEquals(createBuffer(i, SIZE), message.getText()); if (i % 1000 == 0) { logger.debug("received {} messages", i); @@ -239,15 +244,15 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { } } session.commit(); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); connection.close(); try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { store.getCursorProvider().resumeCleanup(); server.stop(); - Assert.assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME - Assert.assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error + assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME + assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error } } @@ -275,11 +280,11 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(queueName); - Assert.assertNotNull(serverQueue); + assertNotNull(serverQueue); serverQueue.getPagingStore().startPaging(); ConnectionFactory cf = CFUtil.createConnectionFactory("core", "tcp://localhost:61616?consumerWindowSize=0"); - Assert.assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); + assertEquals(0, ((ActiveMQConnectionFactory)cf).getServerLocator().getConsumerWindowSize()); Connection slowConnection = cf.createConnection(); Session slowSession = slowConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue slowQueue = slowSession.createQueue(queueName); @@ -293,11 +298,11 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { if (midstream) { slowMessage = (TextMessage) slowConsumer.receive(5000); - Assert.assertNotNull(slowMessage); - Assert.assertEquals("slow", slowMessage.getText()); + assertNotNull(slowMessage); + assertEquals("slow", slowMessage.getText()); } else { slowMessage = (TextMessage) slowConsumer.receiveNoWait(); - Assert.assertNull(slowMessage); + assertNull(slowMessage); } @@ -320,8 +325,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { TextMessage message = (TextMessage) consumer.receive(5000); - Assert.assertNotNull(message); - Assert.assertEquals(createBuffer(i, SIZE), message.getText()); + assertNotNull(message); + assertEquals(createBuffer(i, SIZE), message.getText()); if (i % 1000 == 0) { logger.debug("received {} messages", i); @@ -329,7 +334,7 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { } } session.commit(); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); connection.close(); slowConnection.close(); @@ -340,8 +345,8 @@ public class MegaCleanerPagingTest extends ActiveMQTestBase { Wait.assertFalse(store::isPaging); } server.stop(); - Assert.assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME - Assert.assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error + assertFalse(loggerHandler.findText("AMQ222023")); // error associated with OME + assertFalse(loggerHandler.findText("AMQ222010")); // critical IO Error } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/SubscriptionPagingTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/SubscriptionPagingTest.java index 2be5327c3c..1247ffcc40 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/SubscriptionPagingTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/SubscriptionPagingTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.paging; +import static org.apache.activemq.artemis.utils.TestParameters.testProperty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -35,28 +40,25 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.TestParameters; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -import static org.apache.activemq.artemis.utils.TestParameters.testProperty; - /** * Refer to ./scripts/parameters.sh for suggested parameters * #You may choose to use zip files to save some time on producing if you want to run this test over and over when debugging * export TEST_FLOW_ZIP_LOCATION=a folder */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SubscriptionPagingTest extends SoakTestBase { private static final String TEST_NAME = "SUBSCRIPTION"; @@ -83,7 +85,7 @@ public class SubscriptionPagingTest extends SoakTestBase { public static final String SERVER_NAME_0 = "subscriptionPaging"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -99,7 +101,7 @@ public class SubscriptionPagingTest extends SoakTestBase { } - @Parameterized.Parameters(name = "protocol={0}") + @Parameters(name = "protocol={0}") public static Collection parameters() { String[] protocols = PROTOCOL_LIST.split(","); @@ -131,9 +133,9 @@ public class SubscriptionPagingTest extends SoakTestBase { return "subscription-" + protocol + "-" + MESSAGES + "-" + MESSAGE_SIZE + "-" + SLOW_SUBSCRIPTIONS + ".zip"; } - @Before + @BeforeEach public void before() throws Exception { - Assume.assumeTrue(TEST_ENABLED); + assumeTrue(TEST_ENABLED); cleanupData(SERVER_NAME_0); boolean useZip = ZIP_LOCATION != null; @@ -181,7 +183,7 @@ public class SubscriptionPagingTest extends SoakTestBase { logger.info("Received {} on {}_{}", i, clientID, name); } - Assert.assertEquals(i, message.getIntProperty("m")); + assertEquals(i, message.getIntProperty("m")); if (txInterval > 0) { commitPending++; @@ -217,7 +219,7 @@ public class SubscriptionPagingTest extends SoakTestBase { } - @Test + @TestTemplate public void testSubscription() throws Exception { ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616"); AtomicInteger errors = new AtomicInteger(0); @@ -247,8 +249,8 @@ public class SubscriptionPagingTest extends SoakTestBase { service.execute(() -> receive(factoryClient, "slow_" + finalI, "slow_" + finalI, 0, errors, new AtomicInteger(0), 0, countDownLatch::countDown)); } - Assert.assertTrue(countDownLatch.await(1, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(countDownLatch.await(1, TimeUnit.MINUTES)); + assertEquals(0, errors.get()); } if (!unzipped) { @@ -304,12 +306,12 @@ public class SubscriptionPagingTest extends SoakTestBase { service.execute(() -> receive(factoryClient, "slow_" + finalI, "slow_" + finalI, RECEIVE_COMMIT_INTERVAL, errors, sleepInterval, MESSAGES, countDownLatch::countDown)); } - Assert.assertTrue(countDownLatch.await(TIMEOUT_MINUTES, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(countDownLatch.await(TIMEOUT_MINUTES, TimeUnit.MINUTES)); + assertEquals(0, errors.get()); service.shutdown(); - Assert.assertTrue("Test Timed Out", service.awaitTermination(1, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(service.awaitTermination(1, TimeUnit.MINUTES), "Test Timed Out"); + assertEquals(0, errors.get()); } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/ValidateExportSpeedTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/ValidateExportSpeedTest.java index 27a8501d53..3144267363 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/ValidateExportSpeedTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/paging/ValidateExportSpeedTest.java @@ -17,6 +17,10 @@ package org.apache.activemq.artemis.tests.soak.paging; +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 javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -31,6 +35,7 @@ import javax.jms.TextMessage; import java.io.File; import java.lang.invoke.MethodHandles; import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.cli.commands.ActionContext; import org.apache.activemq.artemis.cli.commands.tools.xml.XmlDataExporter; @@ -39,11 +44,11 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,7 +56,7 @@ public class ValidateExportSpeedTest extends SoakTestBase { public static final String SERVER_NAME_0 = "paging-export"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -68,14 +73,14 @@ public class ValidateExportSpeedTest extends SoakTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); Process serverProcess; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); serverProcess = startServer(SERVER_NAME_0, 0, 10_000); } - @After + @AfterEach public void cleanup() throws Exception { File dmp = new File(TARGET_EXPORTER_DMP); if (dmp.exists()) { @@ -127,49 +132,49 @@ public class ValidateExportSpeedTest extends SoakTestBase { private void receive(MessageConsumer consumer, int i) throws Exception { Message message = consumer.receive(10_000); - Assert.assertNotNull(message); + assertNotNull(message); switch (i % 5) { case 0: { - Assert.assertTrue(message instanceof TextMessage); + assertTrue(message instanceof TextMessage); TextMessage textMessage = (TextMessage) message; - Assert.assertEquals("hello" + i, textMessage.getText()); + assertEquals("hello" + i, textMessage.getText()); break; } case 1: { - Assert.assertTrue(message instanceof MapMessage); + assertTrue(message instanceof MapMessage); MapMessage mapMessage = (MapMessage) message; - Assert.assertEquals("hello" + i, mapMessage.getString("hello")); + assertEquals("hello" + i, mapMessage.getString("hello")); break; } case 2: { - Assert.assertTrue(message instanceof StreamMessage); + assertTrue(message instanceof StreamMessage); StreamMessage streamMessage = (StreamMessage) message; - Assert.assertEquals("string" + i, streamMessage.readString()); - Assert.assertEquals((long) i, streamMessage.readLong()); - Assert.assertEquals(i, streamMessage.readInt()); + assertEquals("string" + i, streamMessage.readString()); + assertEquals((long) i, streamMessage.readLong()); + assertEquals(i, streamMessage.readInt()); break; } case 3: { - Assert.assertTrue(message instanceof BytesMessage); + assertTrue(message instanceof BytesMessage); BytesMessage bytesMessage = (BytesMessage) message; int length = (int) bytesMessage.getBodyLength(); byte[] bytes = new byte[length]; bytesMessage.readBytes(bytes); String str = new String(bytes, StandardCharsets.UTF_8); - Assert.assertEquals("hello " + i, str); + assertEquals("hello " + i, str); break; } case 4: { - Assert.assertTrue(message instanceof ObjectMessage); + assertTrue(message instanceof ObjectMessage); ObjectMessage objectMessage = (ObjectMessage) message; String result = (String)objectMessage.getObject(); - Assert.assertEquals("hello " + i, result); + assertEquals("hello " + i, result); break; } } - Assert.assertEquals(i, message.getIntProperty("i")); - Assert.assertEquals("string" + i, message.getStringProperty("stri")); + assertEquals(i, message.getIntProperty("i")); + assertEquals("string" + i, message.getStringProperty("stri")); } String largeString; @@ -197,22 +202,24 @@ public class ValidateExportSpeedTest extends SoakTestBase { for (int i = 0; i < numberOfMessages; i++) { logger.info("Receiving {} large message", i); Message message = consumer.receive(5000); - Assert.assertTrue(message instanceof TextMessage); + assertTrue(message instanceof TextMessage); TextMessage textMessage = (TextMessage) message; - Assert.assertEquals(largeString + " Hello " + i, textMessage.getText()); + assertEquals(largeString + " Hello " + i, textMessage.getText()); } session.commit(); } - @Test(timeout = 120_000) + @Test + @Timeout(value = 120_000, unit = TimeUnit.MILLISECONDS) public void testExportAMQP() throws Exception { testExport("AMQP", false, 100, 1); // small sample of data to validate the test itself testExport("AMQP", true, 50_000, 100); } - @Test(timeout = 120_000) + @Test + @Timeout(value = 120_000, unit = TimeUnit.MILLISECONDS) public void testExportCORE() throws Exception { testExport("CORE", false, 100, 1); // small sample of data to validate the test itself testExport("CORE", true, 50_000, 100); diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicaTxCheck/ReplicaTXCheckTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicaTxCheck/ReplicaTXCheckTest.java index 0675330c88..1739342478 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicaTxCheck/ReplicaTXCheckTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicaTxCheck/ReplicaTXCheckTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.soak.replicaTxCheck; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; @@ -34,11 +36,10 @@ import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.qpid.jms.JmsConnectionFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,7 +64,7 @@ public class ReplicaTXCheckTest extends SoakTestBase { cliCreateServer.createServer(); } - @BeforeClass + @BeforeAll public static void createServers() throws Exception { createServer(SERVER_NAME_0); createServer(SERVER_NAME_1); @@ -83,7 +84,7 @@ public class ReplicaTXCheckTest extends SoakTestBase { int NUMBER_OF_MESSAGES = 1000; int KILL_AT = 100; - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -95,18 +96,18 @@ public class ReplicaTXCheckTest extends SoakTestBase { server0 = startServer(SERVER_NAME_0, 0, 0); server1 = startServer(SERVER_NAME_1, 0, 0); - Assert.assertTrue(ServerUtil.waitForServerToStartOnPort(61000, null, null, 15000)); + assertTrue(ServerUtil.waitForServerToStartOnPort(61000, null, null, 15000)); server2 = startServer(SERVER_NAME_2, 0, 0); server3 = startServer(SERVER_NAME_3, 0, 0); - Assert.assertTrue(ServerUtil.waitForServerToStartOnPort(61001, null, null, 15000)); + assertTrue(ServerUtil.waitForServerToStartOnPort(61001, null, null, 15000)); server4 = startServer(SERVER_NAME_4, 0, 0); server4 = startServer(SERVER_NAME_5, 0, 0); - Assert.assertTrue(ServerUtil.waitForServerToStartOnPort(61002, null, null, 15000)); + assertTrue(ServerUtil.waitForServerToStartOnPort(61002, null, null, 15000)); } - @After + @AfterEach @Override public void after() throws Exception { super.after(); @@ -241,10 +242,10 @@ public class ReplicaTXCheckTest extends SoakTestBase { targetSession.commit(); for (i = 0; i < NUMBER_OF_MESSAGES; i++) { - Assert.assertTrue(received.contains(i)); + assertTrue(received.contains(i)); } // we could receive duplicates, but not lose messages - Assert.assertTrue(rec >= NUMBER_OF_MESSAGES); + assertTrue(rec >= NUMBER_OF_MESSAGES); } } } \ No newline at end of file diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/ReplicationFlowControlTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/ReplicationFlowControlTest.java index 3cf0f74704..a810be3a77 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/ReplicationFlowControlTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/ReplicationFlowControlTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.soak.replicationflow; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -35,11 +38,10 @@ import org.apache.activemq.artemis.util.ServerUtil; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; import org.apache.qpid.jms.JmsConnectionFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ReplicationFlowControlTest extends SoakTestBase { @@ -47,7 +49,7 @@ public class ReplicationFlowControlTest extends SoakTestBase { public static final String SERVER_NAME_0 = "replicated-static0"; public static final String SERVER_NAME_1 = "replicated-static1"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -83,14 +85,14 @@ public class ReplicationFlowControlTest extends SoakTestBase { static AtomicInteger totalConsumed = new AtomicInteger(0); - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); disableCheckThread(); } - @After + @AfterEach @Override public void after() throws Exception { super.after(); @@ -205,7 +207,7 @@ public class ReplicationFlowControlTest extends SoakTestBase { System.out.println("retention folder = " + retentionFolder.getAbsolutePath()); File[] files = retentionFolder.listFiles(); // it should be max = 2, however I'm giving some extra due to async factors.. - Assert.assertTrue(retentionFolder.getAbsolutePath() + " has " + (files == null ? "no files" : files.length + " elements"), files != null && files.length <= 10); + assertTrue(files != null && files.length <= 10, retentionFolder.getAbsolutePath() + " has " + (files == null ? "no files" : files.length + " elements")); } void startConsumers(boolean useAMQP) { diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/SoakReplicatedPagingTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/SoakReplicatedPagingTest.java index 0d107dad3c..0a61858cc9 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/SoakReplicatedPagingTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/replicationflow/SoakReplicatedPagingTest.java @@ -17,6 +17,8 @@ package org.apache.activemq.artemis.tests.soak.replicationflow; +import static org.junit.jupiter.api.Assertions.assertEquals; + import javax.jms.BytesMessage; import javax.jms.CompletionListener; import javax.jms.Connection; @@ -53,6 +55,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.soak.SoakTestBase; import org.apache.activemq.artemis.utils.ExecuteUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; @@ -62,16 +66,14 @@ import org.apache.qpid.jms.JmsConnectionFactory; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.QoS; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SoakReplicatedPagingTest extends SoakTestBase { public static int OK = 1; @@ -99,7 +101,7 @@ public class SoakReplicatedPagingTest extends SoakTestBase { } } - @Parameterized.Parameters(name = "protocol={0}, type={1}, tx={2}") + @Parameters(name = "protocol={0}, type={1}, tx={2}") public static Collection getParams() { return Arrays.asList(new Object[][]{{"MQTT", "topic", false}, {"AMQP", "shared", false}, {"AMQP", "queue", false}, {"OPENWIRE", "topic", false}, {"OPENWIRE", "queue", false}, {"CORE", "shared", false}, {"CORE", "queue", false}, {"AMQP", "shared", true}, {"AMQP", "queue", true}, {"OPENWIRE", "topic", true}, {"OPENWIRE", "queue", true}, {"CORE", "shared", true}, {"CORE", "queue", true}}); @@ -114,7 +116,7 @@ public class SoakReplicatedPagingTest extends SoakTestBase { private static Process server1; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -137,7 +139,7 @@ public class SoakReplicatedPagingTest extends SoakTestBase { } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); cleanupData(SERVER_NAME_1); @@ -248,9 +250,8 @@ public class SoakReplicatedPagingTest extends SoakTestBase { System.exit(code); } - @Test + @TestTemplate public void testPagingReplication() throws Throwable { - server1 = startServer(SERVER_NAME_1, 0, 30000); for (int i = 0; i < CLIENT_KILLS; i++) { @@ -267,7 +268,7 @@ public class SoakReplicatedPagingTest extends SoakTestBase { if (result <= 0) { jstack(); } - Assert.assertEquals(OK, result); + assertEquals(OK, result); } } diff --git a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/retention/LargeMessageRetentionTest.java b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/retention/LargeMessageRetentionTest.java index d1e73118e6..1fbcbe71e2 100644 --- a/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/retention/LargeMessageRetentionTest.java +++ b/tests/soak-tests/src/test/java/org/apache/activemq/artemis/tests/soak/retention/LargeMessageRetentionTest.java @@ -17,6 +17,11 @@ package org.apache.activemq.artemis.tests.soak.retention; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; @@ -45,10 +50,9 @@ import org.apache.activemq.artemis.tests.util.CFUtil; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.cli.helper.HelperCreate; -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.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,7 +70,7 @@ public class LargeMessageRetentionTest extends SoakTestBase { public static final String SERVER_NAME_0 = "replay/large-message"; - @BeforeClass + @BeforeAll public static void createServers() throws Exception { { File serverLocation = getFileServerLocation(SERVER_NAME_0); @@ -81,7 +85,7 @@ public class LargeMessageRetentionTest extends SoakTestBase { } } - @Before + @BeforeEach public void before() throws Exception { cleanupData(SERVER_NAME_0); startServer(SERVER_NAME_0, 0, 30000); @@ -116,7 +120,7 @@ public class LargeMessageRetentionTest extends SoakTestBase { } private void testRetention(String protocol, int NUMBER_OF_MESSAGES, int backlog, int bodySize, int producers) throws Throwable { - Assert.assertTrue(NUMBER_OF_MESSAGES % producers == 0); // checking that it is a multiple + assertTrue(NUMBER_OF_MESSAGES % producers == 0); // checking that it is a multiple ActiveMQServerControl serverControl = getServerControl(liveURI, nameBuilder, 5000); @@ -149,18 +153,18 @@ public class LargeMessageRetentionTest extends SoakTestBase { MessageConsumer consumer = consumerSession.createConsumer(queue); for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { logger.debug("Acquiring semop at {}", i); - Assert.assertTrue(consumerCredits.tryAcquire(1, TimeUnit.MINUTES)); + assertTrue(consumerCredits.tryAcquire(1, TimeUnit.MINUTES)); TextMessage message = (TextMessage) consumer.receive(60_000); - Assert.assertNotNull(message); + assertNotNull(message); int producerI = message.getIntProperty("producerI"); AtomicInteger messageSequence = messageSequences.get(producerI); if (messageSequence == null) { messageSequence = new AtomicInteger(0); messageSequences.put(producerI, messageSequence); } - Assert.assertEquals(messageSequence.getAndIncrement(), message.getIntProperty("messageI")); + assertEquals(messageSequence.getAndIncrement(), message.getIntProperty("messageI")); logger.info("Received message {}", i); - Assert.assertEquals(bufferStr, message.getText()); + assertEquals(bufferStr, message.getText()); } } catch (Throwable e) { logger.warn(e.getMessage(), e); @@ -196,10 +200,10 @@ public class LargeMessageRetentionTest extends SoakTestBase { } - Assert.assertTrue(latchSender.await(10, TimeUnit.MINUTES)); + assertTrue(latchSender.await(10, TimeUnit.MINUTES)); consumerCredits.release(backlog); - Assert.assertTrue(latchReceiver.await(10, TimeUnit.MINUTES)); - Assert.assertEquals(0, errors.get()); + assertTrue(latchReceiver.await(10, TimeUnit.MINUTES)); + assertEquals(0, errors.get()); try (Connection consumerConnection = factory.createConnection()) { HashMap messageSequences = new HashMap<>(); @@ -207,7 +211,7 @@ public class LargeMessageRetentionTest extends SoakTestBase { Queue queue = consumerSession.createQueue(queueName); consumerConnection.start(); MessageConsumer consumer = consumerSession.createConsumer(queue); - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); serverControl.replay(queueName, queueName, "producerI=0 AND messageI>=0 AND messageI<10"); SimpleManagement simpleManagement = new SimpleManagement("tcp://localhost:61616", null, null); @@ -217,17 +221,17 @@ public class LargeMessageRetentionTest extends SoakTestBase { for (int i = 0; i < 10; i++) { TextMessage message = (TextMessage) consumer.receive(300_000); - Assert.assertNotNull(message); + assertNotNull(message); logger.info("Received replay message {}", i); - Assert.assertEquals(0, message.getIntProperty("producerI")); + assertEquals(0, message.getIntProperty("producerI")); receivedMessages.add(message.getIntProperty("messageI")); - Assert.assertEquals(bufferStr, message.getText()); + assertEquals(bufferStr, message.getText()); } - Assert.assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); - Assert.assertEquals(10, receivedMessages.size()); + assertEquals(10, receivedMessages.size()); for (int i = 0; i < 10; i++) { - Assert.assertTrue(receivedMessages.contains(i)); + assertTrue(receivedMessages.contains(i)); } } diff --git a/tests/stress-tests/pom.xml b/tests/stress-tests/pom.xml index b7d45b1dd8..650f1a2c9d 100644 --- a/tests/stress-tests/pom.xml +++ b/tests/stress-tests/pom.xml @@ -91,8 +91,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java index 2ded6fce21..81fc7dfdc4 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/chunk/LargeMessageStressTest.java @@ -17,9 +17,13 @@ package org.apache.activemq.artemis.tests.stress.chunk; import org.apache.activemq.artemis.core.config.StoreConfiguration; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; import org.apache.activemq.artemis.tests.integration.largemessage.LargeMessageTestBase; -import org.junit.Test; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; +//Parameters set in superclass +@ExtendWith(ParameterizedTestExtension.class) public class LargeMessageStressTest extends LargeMessageTestBase { public LargeMessageStressTest(StoreConfiguration.StoreType storeType) { @@ -28,7 +32,7 @@ public class LargeMessageStressTest extends LargeMessageTestBase { - @Test + @TestTemplate public void testMessageChunkFilePersistenceOneHugeMessage() throws Exception { testChunks(false, false, false, true, true, false, false, false, true, 1, 200 * 1024L * 1024L + 1024L, 120000, 0, 10 * 1024 * 1024, 1024 * 1024); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java index c3539a386d..5cf693c24e 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/client/SendStressTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.client; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; @@ -25,8 +27,7 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SendStressTest extends ActiveMQTestBase { @@ -88,7 +89,7 @@ public class SendStressTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessages; i++) { ClientMessage msg = consumer.receive(5000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); if (i % batchSize == 0) { diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java index 3b6fb7287a..48aea46868 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AIOMultiThreadCompactorStressTest.java @@ -18,13 +18,13 @@ package org.apache.activemq.artemis.tests.stress.journal; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.core.server.JournalType; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class AIOMultiThreadCompactorStressTest extends NIOMultiThreadCompactorStressTest { - @BeforeClass + @BeforeAll public static void hasAIO() { - org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); + org.junit.jupiter.api.Assumptions.assumeTrue(AIOSequentialFileFactory.isSupported(), "Test case needs AIO to run"); } /** diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java index 531e021695..0170defb28 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/AddAndRemoveStressTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.List; @@ -27,8 +29,7 @@ import org.apache.activemq.artemis.core.journal.RecordInfo; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AddAndRemoveStressTest extends ActiveMQTestBase { @@ -120,10 +121,10 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase { impl.stop(); - Assert.assertEquals(0, info.size()); - Assert.assertEquals(0, trans.size()); + assertEquals(0, info.size()); + assertEquals(0, trans.size()); - Assert.assertEquals(0, impl.getDataFilesCount()); + assertEquals(0, impl.getDataFilesCount()); } @@ -183,9 +184,9 @@ public class AddAndRemoveStressTest extends ActiveMQTestBase { impl.stop(); - Assert.assertEquals(0, info.size()); - Assert.assertEquals(0, trans.size()); - Assert.assertEquals(0, impl.getDataFilesCount()); + assertEquals(0, info.size()); + assertEquals(0, trans.size()); + assertEquals(0, impl.getDataFilesCount()); System.out.println("Size = " + impl.getDataFilesCount()); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java index 664a51c173..04940d7f93 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/CompactingStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; @@ -33,8 +36,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CompactingStressTest extends ActiveMQTestBase { @@ -110,7 +112,7 @@ public class CompactingStressTest extends ActiveMQTestBase { for (int j = 0; j < 1000; j++) { ClientMessage msg = cons.receive(2000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); } @@ -119,7 +121,7 @@ public class CompactingStressTest extends ActiveMQTestBase { } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); session.close(); @@ -135,11 +137,11 @@ public class CompactingStressTest extends ActiveMQTestBase { for (int i = 0; i < 500; i++) { ClientMessage msg = cons.receive(1000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); prod = session.createProducer(CompactingStressTest.AD2); @@ -263,7 +265,7 @@ public class CompactingStressTest extends ActiveMQTestBase { msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); } catch (Throwable e) { this.e = e; } finally { @@ -315,17 +317,17 @@ public class CompactingStressTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessages.intValue(); i++) { ClientMessage msg = cons.receive(60000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); cons.close(); cons = sess.createConsumer(CompactingStressTest.Q2); - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); cons.close(); @@ -333,11 +335,11 @@ public class CompactingStressTest extends ActiveMQTestBase { for (int i = 0; i < CompactingStressTest.TOT_AD3; i++) { ClientMessage msg = cons.receive(60000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); } finally { try { diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java index 2cd54cfafd..640cb972be 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalCleanupCompactStressTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -47,9 +49,9 @@ import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.SimpleIDGenerator; -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; public class JournalCleanupCompactStressTest extends ActiveMQTestBase { @@ -87,7 +89,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -149,7 +151,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { try { if (journal.isStarted()) { @@ -243,7 +245,7 @@ public class JournalCleanupCompactStressTest extends ActiveMQTestBase { try { journal.appendDeleteRecord(id, false); } catch (Exception e) { - new RuntimeException(e); + throw new RuntimeException(e); } }); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java index b7c3eefde2..5ca1e8aed2 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/JournalRestartStressTest.java @@ -29,7 +29,7 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Simulates the journal being updated, compacted cleared up, diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java index edfb18e2d4..1357db3768 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/LargeJournalStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; @@ -31,10 +34,9 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.After; -import org.junit.Assert; -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; public class LargeJournalStressTest extends ActiveMQTestBase { @@ -150,7 +152,7 @@ public class LargeJournalStressTest extends ActiveMQTestBase { msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); } catch (Throwable e) { this.e = e; } finally { @@ -198,24 +200,24 @@ public class LargeJournalStressTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessages.intValue(); i++) { ClientMessage msg = cons.receive(10000); - Assert.assertNotNull(msg); + assertNotNull(msg); msg.acknowledge(); } - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); cons.close(); cons = sess.createConsumer(LargeJournalStressTest.Q2); - Assert.assertNull(cons.receiveImmediate()); + assertNull(cons.receiveImmediate()); sess.close(); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -254,7 +256,7 @@ public class LargeJournalStressTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { locator.close(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java index 23750956a3..6ed84e0c1a 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MixupCompactorTestBase.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import java.io.FilenameFilter; @@ -25,10 +27,9 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.JournalImplTestBase; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.SimpleIDGenerator; -import org.junit.After; -import org.junit.Assert; -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; /** * This class will control mix up compactor between each operation of a test @@ -54,7 +55,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -69,7 +70,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { File testDir = new File(getTestDir()); @@ -83,7 +84,7 @@ public abstract class MixupCompactorTestBase extends JournalImplTestBase { }); for (File file : files) { - Assert.assertEquals("File " + file + " doesn't have the expected number of bytes", fileSize, file.length()); + assertEquals(fileSize, file.length(), "File " + file + " doesn't have the expected number of bytes"); } super.tearDown(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java index fe12ca31a6..a073604d21 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/MultiThreadConsumerStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.ArrayList; import java.util.concurrent.CountDownLatch; @@ -32,9 +35,8 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * A MultiThreadConsumerStressTest @@ -53,7 +55,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase { private ClientSessionFactory sf; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); setupServer(JournalType.NIO); @@ -126,7 +128,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessagesExpected; i++) { ClientMessage msg = consumer.receive(5000); - Assert.assertNotNull(msg); + assertNotNull(msg); if (i % 1000 == 0) { System.out.println("Received #" + i + " on thread before end"); @@ -134,7 +136,7 @@ public class MultiThreadConsumerStressTest extends ActiveMQTestBase { msg.acknowledge(); } - Assert.assertNull(consumer.receiveImmediate()); + assertNull(consumer.receiveImmediate()); sess.close(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java index 796cd15b4a..c93ad0d0f6 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/NIOMultiThreadCompactorStressTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import java.io.File; @@ -42,9 +46,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { @@ -64,7 +67,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -90,8 +93,8 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { journal.start(); journal.load(committedRecords, preparedTransactions, null); - Assert.assertEquals(0, committedRecords.size()); - Assert.assertEquals(0, preparedTransactions.size()); + assertEquals(0, committedRecords.size()); + assertEquals(0, preparedTransactions.size()); System.out.println("DataFiles = " + journal.getDataFilesCount()); @@ -105,7 +108,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { if (journal.getDataFilesCount() != 0) { System.out.println("DebugJournal:" + journal.debug()); } - Assert.assertEquals(0, journal.getDataFilesCount()); + assertEquals(0, journal.getDataFilesCount()); } journal.stop(); @@ -142,8 +145,8 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { ClientSession session = sf.createSession(true, false, false); Xid[] xids = session.recover(XAResource.TMSTARTRSCAN); - Assert.assertEquals(1, xids.length); - Assert.assertEquals(xid, xids[0]); + assertEquals(1, xids.length); + assertEquals(xid, xids[0]); session.rollback(xid); @@ -237,7 +240,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { for (int i = 0; i < numberOfMessagesExpected; i++) { ClientMessage msg = consumer.receive(5000); - Assert.assertNotNull(msg); + assertNotNull(msg); if (i % 100 == 0) { // System.out.println("Received #" + i + " on thread after start"); @@ -245,7 +248,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { msg.acknowledge(); } - Assert.assertNull(consumer.receiveImmediate()); + assertNull(consumer.receiveImmediate()); sess.close(); } @@ -271,7 +274,7 @@ public class NIOMultiThreadCompactorStressTest extends ActiveMQTestBase { session.start(); ClientConsumer cons = session.createConsumer(queue); - Assert.assertNotNull(cons.receive(1000)); + assertNotNull(cons.receive(1000)); session.rollback(); session.close(); } diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java index 605bd592d2..4084bd3909 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/journal/XmlImportExportStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.journal; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; @@ -32,7 +35,7 @@ import org.apache.activemq.artemis.cli.commands.tools.xml.XmlDataExporter; import org.apache.activemq.artemis.cli.commands.tools.xml.XmlDataImporter; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XmlImportExportStressTest extends ActiveMQTestBase { diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java index 5eb2c0b2b0..c8ffa70913 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/MultipleConsumersPageStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.util.ArrayList; import java.util.HashMap; import java.util.Random; @@ -34,9 +37,8 @@ import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.core.server.impl.QueueImpl; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -93,7 +95,7 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -319,14 +321,14 @@ public class MultipleConsumersPageStressTest extends ActiveMQTestBase { if (msg == null) { logger.warn("msg {} was null, currentBatchSize={}, current msg being read={}", count, numberOfMessages, i); } - Assert.assertNotNull("msg " + count + + assertNotNull(msg, "msg " + count + " was null, currentBatchSize=" + numberOfMessages + ", current msg being read=" + - i, msg); + i); if (numberOfConsumers == 1 && numberOfProducers == 1) { - Assert.assertEquals(count, msg.getIntProperty("count").intValue()); + assertEquals(count, msg.getIntProperty("count").intValue()); } count++; diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java index e01cc5d1c8..305acfadc7 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageCursorStressTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.stress.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -51,9 +57,8 @@ import org.apache.activemq.artemis.tests.unit.core.postoffice.impl.fakes.FakeQue import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class PageCursorStressTest extends ActiveMQTestBase { @@ -366,7 +371,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); - Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); + assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); PagedReference readMessage = iterator.next(); @@ -399,7 +404,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); - Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); + assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); } PagedReference readMessage = iterator.next(); @@ -429,7 +434,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); - Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); + assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); } PagedReference readMessage = iterator.next(); @@ -514,7 +519,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); - Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); + assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); } if (tx != null) { @@ -582,7 +587,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { Thread.sleep(100); } - assertTrue("expected " + lookupPageStore(ADDRESS).getNumberOfPages(), lookupPageStore(ADDRESS).getNumberOfPages() <= 2); + assertTrue(lookupPageStore(ADDRESS).getNumberOfPages() <= 2, "expected " + lookupPageStore(ADDRESS).getNumberOfPages()); } @Test @@ -616,7 +621,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { // First consume what's already there without any tx as nothing was committed for (int i = 100; i < 200; i++) { PagedReference pos = iterator.next(); - assertNotNull("Null at position " + i, pos); + assertNotNull(pos, "Null at position " + i); assertEquals(i, pos.getMessage().getIntProperty("key").intValue()); cursor.ack(pos); } @@ -629,7 +634,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { for (int i = 0; i < 100; i++) { PagedReference pos = iterator.next(); - assertNotNull("Null at position " + i, pos); + assertNotNull(pos, "Null at position " + i); assertEquals(i, pos.getMessage().getIntProperty("key").intValue()); cursor.ack(pos); } @@ -733,7 +738,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { msg.getBodyBuffer().writeBytes(buffer, 0, buffer.writerIndex()); - Assert.assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); + assertTrue(pageStore.page(msg, ctx.getTransaction(), ctx.getContextListing(ADDRESS))); } return pageStore.getNumberOfPages(); @@ -750,7 +755,7 @@ public class PageCursorStressTest extends ActiveMQTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); OperationContextImpl.clearContext(); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java index 28f481abd9..76f5f75436 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/paging/PageStressTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.paging; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.HashMap; import org.apache.activemq.artemis.api.core.ActiveMQException; @@ -32,9 +34,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.jms.client.ActiveMQBytesMessage; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * This is an integration-tests that will take some time to run. @@ -129,7 +130,7 @@ public class PageStressTest extends ActiveMQTestBase { System.out.println("msgs second time: " + msgs); - Assert.assertEquals(NUMBER_OF_MESSAGES, msgs); + assertEquals(NUMBER_OF_MESSAGES, msgs); } @Test @@ -190,8 +191,8 @@ public class PageStressTest extends ActiveMQTestBase { consumers[0].close(); consumers[1].close(); - Assert.assertEquals(NUMBER_OF_MESSAGES, counters[0]); - Assert.assertEquals(NUMBER_OF_MESSAGES, counters[1]); + assertEquals(NUMBER_OF_MESSAGES, counters[0]); + assertEquals(NUMBER_OF_MESSAGES, counters[1]); } private int readMessages(final ClientSession session, @@ -228,7 +229,7 @@ public class PageStressTest extends ActiveMQTestBase { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setBlockOnDurableSend(false).setBlockOnNonDurableSend(false); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java index 2672e76614..da1521e839 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/remote/PingStressTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.stress.remote; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -30,8 +32,8 @@ import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -45,7 +47,7 @@ public class PingStressTest extends ActiveMQTestBase { private ActiveMQServer server; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); server = createServer(false, createDefaultNettyConfig()); diff --git a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java index 24b76a3a3b..0f64e3c3fd 100644 --- a/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java +++ b/tests/stress-tests/src/test/java/org/apache/activemq/artemis/tests/stress/stomp/StompStressTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.stress.stomp; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -36,10 +39,9 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.After; -import org.junit.Assert; -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; public class StompStressTest extends ActiveMQTestBase { @@ -61,7 +63,7 @@ public class StompStressTest extends ActiveMQTestBase { sendFrame(frame); frame = receiveFrame(10000); - Assert.assertTrue(frame.startsWith("CONNECTED")); + assertTrue(frame.startsWith("CONNECTED")); frame = "SUBSCRIBE\n" + "destination:" + destination + "\n" + "ack:auto\n\n" + Stomp.NULL; sendFrame(frame); @@ -76,9 +78,9 @@ public class StompStressTest extends ActiveMQTestBase { for (int i = 0; i < COUNT; i++) { System.out.println("<<< " + i); frame = receiveFrame(10000); - Assert.assertTrue(frame.startsWith("MESSAGE")); - Assert.assertTrue(frame.indexOf("destination:") > 0); - Assert.assertTrue(frame.indexOf("count:" + i) > 0); + assertTrue(frame.startsWith("MESSAGE")); + assertTrue(frame.indexOf("destination:") > 0); + assertTrue(frame.indexOf("count:" + i) > 0); } frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; @@ -88,7 +90,7 @@ public class StompStressTest extends ActiveMQTestBase { // Implementation methods // ------------------------------------------------------------------------- @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -111,7 +113,7 @@ public class StompStressTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { if (stompSocket != null) { stompSocket.close(); @@ -154,7 +156,7 @@ public class StompStressTest extends ActiveMQTestBase { byte[] ba = inputBuffer.toByteArray(); System.out.println(new String(ba, StandardCharsets.UTF_8)); } - Assert.assertEquals("Expecting stomp frame to terminate with \0\n", c, '\n'); + assertEquals(c, '\n', "Expecting stomp frame to terminate with \0\n"); byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, StandardCharsets.UTF_8); diff --git a/tests/timing-tests/pom.xml b/tests/timing-tests/pom.xml index 3ddff09b8f..c2954eb99f 100644 --- a/tests/timing-tests/pom.xml +++ b/tests/timing-tests/pom.xml @@ -70,8 +70,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java index 4e8e9623db..ff24c94223 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/AIOJournalImplTest.java @@ -21,13 +21,13 @@ import java.io.File; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class AIOJournalImplTest extends JournalImplTestUnit { - @BeforeClass + @BeforeAll public static void hasAIO() { - org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); + org.junit.jupiter.api.Assumptions.assumeTrue(AIOSequentialFileFactory.isSupported(), "Test case needs AIO to run"); } @Override diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java index 436a28e406..55e190df8d 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/journal/impl/JournalImplTestUnit.java @@ -16,15 +16,16 @@ */ package org.apache.activemq.artemis.tests.timing.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo; import org.apache.activemq.artemis.core.journal.RecordInfo; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.unit.core.journal.impl.JournalImplTestBase; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -34,11 +35,11 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override - @After + @AfterEach public void tearDown() throws Exception { super.tearDown(); - Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); + assertEquals(0, LibaioContext.getTotalMaxIO()); } @Test @@ -160,7 +161,7 @@ public abstract class JournalImplTestUnit extends JournalImplTestBase { startJournal(); journal.load(new ArrayList(), new ArrayList(), null); - Assert.assertEquals(NUMBER_OF_RECORDS / 2, journal.getIDMapSize()); + assertEquals(NUMBER_OF_RECORDS / 2, journal.getIDMapSize()); stopJournal(); } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java index dc8bc90ef4..d7e940a876 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueConcurrentTest.java @@ -29,9 +29,9 @@ import org.apache.activemq.artemis.core.server.impl.QueueImpl; import org.apache.activemq.artemis.tests.unit.core.server.impl.fakes.FakeConsumer; import org.apache.activemq.artemis.tests.unit.core.server.impl.fakes.FakeQueueFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -48,14 +48,14 @@ public class QueueConcurrentTest extends ActiveMQTestBase { private FakeQueueFactory queueFactory = new FakeQueueFactory(); @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); queueFactory = new FakeQueueFactory(); } @Override - @After + @AfterEach public void tearDown() throws Exception { queueFactory.stop(); super.tearDown(); diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java index 7744616c6a..e139c3468b 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/core/server/impl/QueueImplTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.timing.core.server.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -34,10 +37,9 @@ import org.apache.activemq.artemis.tests.unit.core.server.impl.fakes.FakeConsume import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; -import org.junit.After; -import org.junit.Assert; -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; public class QueueImplTest extends ActiveMQTestBase { @@ -50,7 +52,7 @@ public class QueueImplTest extends ActiveMQTestBase { private ExecutorService executor; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -59,7 +61,7 @@ public class QueueImplTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { scheduledExecutor.shutdownNow(); executor.shutdown(); @@ -193,31 +195,31 @@ public class QueueImplTest extends ActiveMQTestBase { consumer.getReferences().clear(); MessageReference ref = consumer.waitForNextReference(QueueImplTest.TIMEOUT); - Assert.assertEquals(ref7, ref); + assertEquals(ref7, ref); long now2 = System.currentTimeMillis(); - Assert.assertTrue(now2 - now >= 300); + assertTrue(now2 - now >= 300); ref = consumer.waitForNextReference(QueueImplTest.TIMEOUT); - Assert.assertEquals(ref6, ref); + assertEquals(ref6, ref); now2 = System.currentTimeMillis(); - Assert.assertTrue(now2 - now >= 400); + assertTrue(now2 - now >= 400); ref = consumer.waitForNextReference(QueueImplTest.TIMEOUT); - Assert.assertEquals(ref5, ref); + assertEquals(ref5, ref); now2 = System.currentTimeMillis(); - Assert.assertTrue(now2 - now >= 500); + assertTrue(now2 - now >= 500); ref = consumer.waitForNextReference(QueueImplTest.TIMEOUT); - Assert.assertEquals(ref8, ref); + assertEquals(ref8, ref); now2 = System.currentTimeMillis(); - Assert.assertTrue(now2 - now >= 600); + assertTrue(now2 - now >= 600); ref = consumer.waitForNextReference(QueueImplTest.TIMEOUT); - Assert.assertEquals(ref1, ref); + assertEquals(ref1, ref); now2 = System.currentTimeMillis(); - Assert.assertTrue(now2 - now >= 700); + assertTrue(now2 - now >= 700); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertTrue(consumer.getReferences().isEmpty()); } @Test @@ -242,7 +244,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addHead(messageReference, false); boolean gotLatch = countDownLatch.await(3000, TimeUnit.MILLISECONDS); - Assert.assertTrue(gotLatch); + assertTrue(gotLatch); } } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java index 020a390a74..09756fb4f9 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/jms/bridge/impl/JMSBridgeImplTest.java @@ -16,6 +16,14 @@ */ package org.apache.activemq.artemis.tests.timing.jms.bridge.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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 javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -64,11 +72,8 @@ import org.apache.activemq.artemis.jms.bridge.impl.JMSBridgeImpl; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -86,9 +91,6 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { private static final AtomicBoolean tcclClassFound = new AtomicBoolean(false); - @Rule - public ExpectedException thrown = ExpectedException.none(); - protected static TransactionManager newTransactionManager() { return new TransactionManager() { @@ -215,12 +217,12 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); Thread.sleep(50); - Assert.assertFalse(bridge.isStarted()); - Assert.assertTrue(bridge.isFailed()); + assertFalse(bridge.isStarted()); + assertTrue(bridge.isFailed()); bridge.stop(); @@ -268,12 +270,12 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); Thread.sleep(500); - Assert.assertTrue(bridge.isStarted()); - Assert.assertFalse(bridge.isFailed()); + assertTrue(bridge.isStarted()); + assertFalse(bridge.isFailed()); bridge.stop(); } @@ -292,7 +294,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -310,15 +312,15 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTargetUsername("targetuser"); bridge.setTargetPassword("ENC(56a0db3b71043054269d11823973462f)"); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); assertEquals("sourcepassword", bridge.getSourcePassword()); assertEquals("targetpassword", bridge.getTargetPassword()); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); } @Test @@ -333,7 +335,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -346,9 +348,9 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); Connection targetConn = JMSBridgeImplTest.createConnectionFactory().createConnection(); Session targetSess = targetConn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -370,13 +372,13 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { producer.send(sourceSess.createTextMessage()); sourceConn.close(); - Assert.assertEquals(0, messages.size()); + assertEquals(0, messages.size()); Thread.sleep(3 * maxBatchTime); - Assert.assertEquals(1, messages.size()); + assertEquals(1, messages.size()); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); targetConn.close(); } @@ -392,7 +394,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -405,9 +407,9 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); Connection targetConn = JMSBridgeImplTest.createConnectionFactory().createConnection(); Session targetSess = targetConn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -437,20 +439,20 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { Thread.sleep(1000); - Assert.assertEquals(0, messages.size()); + assertEquals(0, messages.size()); TextMessage msg = sourceSess.createTextMessage(); producer.send(msg); - Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); sourceConn.close(); - Assert.assertEquals(numMessages, messages.size()); + assertEquals(numMessages, messages.size()); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); targetConn.close(); } @@ -475,7 +477,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -488,9 +490,9 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); Connection sourceConn = JMSBridgeImplTest.createConnectionFactory().createConnection(); Session sourceSess = sourceConn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -509,7 +511,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { assertNotEquals(jmsQueueControl.getDeliveringCount(), numMessages); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); } @Test @@ -536,7 +538,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -549,17 +551,17 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); sourceConn.get().getExceptionListener().onException(new JMSException("exception on the source")); Thread.sleep(4 * bridge.getFailureRetryInterval()); // reconnection must have succeeded - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); } @Test @@ -592,7 +594,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -605,14 +607,14 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); sourceConn.get().getExceptionListener().onException(new JMSException("exception on the source")); Thread.sleep(4 * bridge.getFailureRetryInterval()); // reconnection must have failed - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); } @@ -642,7 +644,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { TransactionManager tm = JMSBridgeImplTest.newTransactionManager(); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -655,9 +657,9 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setTransactionManager(tm); bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); unsetMockTCCL(mockTccl); tcclClassFound.set(false); @@ -665,10 +667,10 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { sourceConn.get().getExceptionListener().onException(new JMSException("exception on the source")); Thread.sleep(4 * bridge.getFailureRetryInterval()); // reconnection must have succeeded - Assert.assertTrue(bridge.isStarted()); + assertTrue(bridge.isStarted()); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); assertTrue(tcclClassFound.get()); } finally { if (mockTccl != null) @@ -689,7 +691,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -710,7 +712,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { DestinationFactory targetDF = JMSBridgeImplTest.newDestinationFactory(ActiveMQJMSClient.createQueue(JMSBridgeImplTest.TARGET)); JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + assertNotNull(bridge); bridge.setSourceConnectionFactoryFactory(sourceCFF); bridge.setSourceDestinationFactory(sourceDF); @@ -722,7 +724,7 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { bridge.setMaxBatchSize(10); bridge.setQualityOfServiceMode(QualityOfServiceMode.DUPLICATES_OK); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); bridge.start(); Field field = JMSBridgeImpl.class.getDeclaredField("tm"); @@ -730,40 +732,41 @@ public class JMSBridgeImplTest extends ActiveMQTestBase { assertNull(field.get(bridge)); bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + assertFalse(bridge.isStarted()); } @Test public void testThrowErrorWhenTMNotSetForOnceOnly() throws Exception { - thrown.expect(RuntimeException.class); + assertThrows(RuntimeException.class, () -> { - ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); - ConnectionFactoryFactory targetCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); - DestinationFactory sourceDF = JMSBridgeImplTest.newDestinationFactory(ActiveMQJMSClient.createQueue(JMSBridgeImplTest.SOURCE)); - DestinationFactory targetDF = JMSBridgeImplTest.newDestinationFactory(ActiveMQJMSClient.createQueue(JMSBridgeImplTest.TARGET)); + ConnectionFactoryFactory sourceCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); + ConnectionFactoryFactory targetCFF = JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory()); + DestinationFactory sourceDF = JMSBridgeImplTest.newDestinationFactory(ActiveMQJMSClient.createQueue(JMSBridgeImplTest.SOURCE)); + DestinationFactory targetDF = JMSBridgeImplTest.newDestinationFactory(ActiveMQJMSClient.createQueue(JMSBridgeImplTest.TARGET)); - JMSBridgeImpl bridge = new JMSBridgeImpl(); - Assert.assertNotNull(bridge); + JMSBridgeImpl bridge = new JMSBridgeImpl(); + assertNotNull(bridge); - bridge.setSourceConnectionFactoryFactory(sourceCFF); - bridge.setSourceDestinationFactory(sourceDF); - bridge.setTargetConnectionFactoryFactory(targetCFF); - bridge.setTargetDestinationFactory(targetDF); - bridge.setFailureRetryInterval(10); - bridge.setMaxRetries(1); - bridge.setMaxBatchTime(-1); - bridge.setMaxBatchSize(10); - bridge.setQualityOfServiceMode(QualityOfServiceMode.ONCE_AND_ONLY_ONCE); + bridge.setSourceConnectionFactoryFactory(sourceCFF); + bridge.setSourceDestinationFactory(sourceDF); + bridge.setTargetConnectionFactoryFactory(targetCFF); + bridge.setTargetDestinationFactory(targetDF); + bridge.setFailureRetryInterval(10); + bridge.setMaxRetries(1); + bridge.setMaxBatchTime(-1); + bridge.setMaxBatchSize(10); + bridge.setQualityOfServiceMode(QualityOfServiceMode.ONCE_AND_ONLY_ONCE); - Assert.assertFalse(bridge.isStarted()); - bridge.start(); + assertFalse(bridge.isStarted()); + bridge.start(); - Field field = JMSBridgeImpl.class.getDeclaredField("tm"); - field.setAccessible(true); - assertNotNull(field.get(bridge)); + Field field = JMSBridgeImpl.class.getDeclaredField("tm"); + field.setAccessible(true); + assertNotNull(field.get(bridge)); - bridge.stop(); - Assert.assertFalse(bridge.isStarted()); + bridge.stop(); + assertFalse(bridge.isStarted()); + }); } private static class MockContextClassLoader extends ClassLoader { diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java index 288ec119c5..fe0ba0a102 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/ReusableLatchTest.java @@ -16,10 +16,12 @@ */ package org.apache.activemq.artemis.tests.timing.util; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ReusableLatch; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ReusableLatchTest extends ActiveMQTestBase { @@ -30,9 +32,9 @@ public class ReusableLatchTest extends ActiveMQTestBase { latch.countUp(); long start = System.currentTimeMillis(); - Assert.assertFalse(latch.await(1000)); + assertFalse(latch.await(1000)); long end = System.currentTimeMillis(); - Assert.assertTrue("Timeout didn't work correctly", end - start >= 1000 && end - start < 2000); + assertTrue(end - start >= 1000 && end - start < 2000, "Timeout didn't work correctly"); } } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java index 60525462a8..f62427ddd2 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/TokenBucketLimiterImplTest.java @@ -16,14 +16,15 @@ */ package org.apache.activemq.artemis.tests.timing.util; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.TokenBucketLimiterImpl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TokenBucketLimiterImplTest extends ActiveMQTestBase { @@ -126,13 +127,13 @@ public class TokenBucketLimiterImplTest extends ActiveMQTestBase { // any variation on 1 could make the test to fail, for that reason we make it this way - Assert.assertTrue(count == 5 || count == 6); + assertTrue(count == 5 || count == 6); } else { double actualRate = (double) (1000 * count) / measureTime; - Assert.assertTrue("actual rate = " + actualRate + " expected=" + rate, actualRate > rate * (1 - error)); + assertTrue(actualRate > rate * (1 - error), "actual rate = " + actualRate + " expected=" + rate); - Assert.assertTrue("actual rate = " + actualRate + " expected=" + rate, actualRate < rate * (1 + error)); + assertTrue(actualRate < rate * (1 + error), "actual rate = " + actualRate + " expected=" + rate); } } diff --git a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java index efa06d9b17..6480ca5ae9 100644 --- a/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java +++ b/tests/timing-tests/src/test/java/org/apache/activemq/artemis/tests/timing/util/UTF8Test.java @@ -16,14 +16,14 @@ */ package org.apache.activemq.artemis.tests.timing.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.apache.activemq.artemis.utils.ThreadLeakCheckRule; import org.apache.activemq.artemis.utils.UTF8Util; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class UTF8Test extends ActiveMQTestBase { @@ -62,12 +62,12 @@ public class UTF8Test extends ActiveMQTestBase { buffer.writeUTF(str); for (int c = 0; c < TIMES; c++) { - ThreadLeakCheckRule.forceGC(); + forceGC(); final long start = System.currentTimeMillis(); for (long i = 0; i < numberOfIteractions; i++) { buffer.resetReaderIndex(); String newstr = buffer.readUTF(); - Assert.assertEquals(str, newstr); + assertEquals(str, newstr); blackHole = newstr; } final long spentTime = System.currentTimeMillis() - start; @@ -79,7 +79,7 @@ public class UTF8Test extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { UTF8Util.clearBuffer(); super.tearDown(); diff --git a/tests/unit-tests/pom.xml b/tests/unit-tests/pom.xml index a7e5239c8f..ae1be59fee 100644 --- a/tests/unit-tests/pom.xml +++ b/tests/unit-tests/pom.xml @@ -98,8 +98,13 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/AllClassesTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/AllClassesTest.java index 74e6547c3a..fb27976818 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/AllClassesTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/AllClassesTest.java @@ -16,17 +16,21 @@ */ package org.apache.activemq.artemis.tests.unit; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import com.google.common.collect.ImmutableSet; import com.google.common.reflect.ClassPath; + +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assume; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; @@ -35,12 +39,13 @@ import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; +import java.util.concurrent.TimeUnit; -@RunWith(value = Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class AllClassesTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @Parameterized.Parameters(name = "classInfo={0}") + @Parameters(name = "classInfo={0}") public static Collection getParameters() { List parameters = new ArrayList<>(); ClassLoader classLoader = AllClassesTest.class.getClassLoader(); @@ -79,7 +84,8 @@ public class AllClassesTest { } - @Test(timeout = 3000) + @TestTemplate + @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS) public void testToString() { Object targetInstance = null; @@ -89,7 +95,7 @@ public class AllClassesTest { logger.debug("Error creating a new instance of {}: {}", targetClass.getName(), t); } - Assume.assumeTrue("Cannot create " + targetClass.getName(), targetInstance != null); + assumeTrue(targetInstance != null, "Cannot create " + targetClass.getName()); try { String targetOutput = targetInstance.toString(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java index a9eed3565f..65ab81d726 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/AIOTestBase.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.asyncio; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -27,9 +30,8 @@ import org.apache.activemq.artemis.core.io.IOCallback; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.nativo.jlibaio.LibaioFile; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; /** * The base class for AIO Tests @@ -41,17 +43,17 @@ public abstract class AIOTestBase extends ActiveMQTestBase { protected String fileName = "fileUsedOnNativeTests.log"; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); - Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")), LibaioContext.isLoaded()); + assertTrue(LibaioContext.isLoaded(), String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"))); } @Override - @After + @AfterEach public void tearDown() throws Exception { - Assert.assertEquals(0, LibaioContext.getTotalMaxIO()); + assertEquals(0, LibaioContext.getTotalMaxIO()); super.tearDown(); } @@ -130,10 +132,10 @@ public abstract class AIOTestBase extends ActiveMQTestBase { } public static void checkResults(final int numberOfElements, final ArrayList result) { - Assert.assertEquals(numberOfElements, result.size()); + assertEquals(numberOfElements, result.size()); int i = 0; for (Integer resultI : result) { - Assert.assertEquals(i++, resultI.intValue()); + assertEquals(i++, resultI.intValue()); } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java index 114414bc9c..50bfb93e77 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/asyncio/MultiThreadAsynchronousFileTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.asyncio; +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.nio.ByteBuffer; import java.util.ArrayList; import java.util.LinkedList; @@ -30,10 +34,10 @@ import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -49,9 +53,9 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @BeforeClass + @BeforeAll public static void hasAIO() { - org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); + org.junit.jupiter.api.Assumptions.assumeTrue(AIOSequentialFileFactory.isSupported(), "Test case needs AIO to run"); } AtomicInteger position = new AtomicInteger(0); @@ -67,7 +71,7 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase { ExecutorService pollerExecutor; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), false, this.getClass().getClassLoader())); @@ -75,7 +79,7 @@ public class MultiThreadAsynchronousFileTest extends AIOTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { executor.shutdown(); pollerExecutor.shutdown(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java index 79666306d5..a629db92a4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/client/impl/LargeMessageBufferTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.client.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -48,9 +52,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQBufferInputStream; import org.apache.activemq.artemis.utils.FutureLatch; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class LargeMessageBufferTest extends ActiveMQTestBase { @@ -59,7 +62,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -76,7 +79,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { for (int i = 1; i <= 15; i++) { try { - Assert.assertEquals(i, buffer.readByte()); + assertEquals(i, buffer.readByte()); } catch (Exception e) { throw new Exception("Exception at position " + i, e); } @@ -84,7 +87,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { try { buffer.readByte(); - Assert.fail("supposed to throw an exception"); + fail("supposed to throw an exception"); } catch (IndexOutOfBoundsException e) { } } @@ -104,7 +107,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { bytes = new byte[16]; buffer.getBytes(0, bytes); - Assert.fail("supposed to throw an exception"); + fail("supposed to throw an exception"); } catch (java.lang.IndexOutOfBoundsException e) { } } @@ -132,12 +135,12 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { LargeMessageControllerImpl buffer = createBufferWithIntegers(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); for (int i = 1; i <= 15; i++) { - Assert.assertEquals(i, buffer.readInt()); + assertEquals(i, buffer.readInt()); } try { buffer.readByte(); - Assert.fail("supposed to throw an exception"); + fail("supposed to throw an exception"); } catch (IndexOutOfBoundsException e) { } } @@ -149,7 +152,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { DataInputStream dataInput = new DataInputStream(is); for (int i = 1; i <= 15; i++) { - Assert.assertEquals(i, dataInput.readInt()); + assertEquals(i, dataInput.readInt()); } assertEquals(-1, dataInput.read()); @@ -162,12 +165,12 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { LargeMessageControllerImpl buffer = createBufferWithLongs(3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); for (int i = 1; i <= 15; i++) { - Assert.assertEquals(i, buffer.readLong()); + assertEquals(i, buffer.readLong()); } try { buffer.readByte(); - Assert.fail("supposed to throw an exception"); + fail("supposed to throw an exception"); } catch (IndexOutOfBoundsException e) { } } @@ -179,7 +182,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { DataInputStream dataInput = new DataInputStream(is); for (int i = 1; i <= 15; i++) { - Assert.assertEquals(i, dataInput.readLong()); + assertEquals(i, dataInput.readLong()); } assertEquals(-1, dataInput.read()); @@ -202,10 +205,10 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { LargeMessageControllerImpl readBuffer = splitBuffer(3, dynamic.toByteBuffer().array()); - Assert.assertEquals(str1, readBuffer.readUTF()); - Assert.assertEquals(str2, readBuffer.readString()); - Assert.assertEquals(d1, readBuffer.readDouble(), 0.000001); - Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001); + assertEquals(str1, readBuffer.readUTF()); + assertEquals(str2, readBuffer.readString()); + assertEquals(d1, readBuffer.readDouble(), 0.000001); + assertEquals(f1, readBuffer.readFloat(), 0.000001); } private File getTestFile() { @@ -230,17 +233,17 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { LargeMessageControllerImpl readBuffer = splitBuffer(3, dynamic.toByteBuffer().array(), getTestFile()); - Assert.assertEquals(str1, readBuffer.readUTF()); - Assert.assertEquals(str2, readBuffer.readString()); - Assert.assertEquals(d1, readBuffer.readDouble(), 0.00000001); - Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001); + assertEquals(str1, readBuffer.readUTF()); + assertEquals(str2, readBuffer.readString()); + assertEquals(d1, readBuffer.readDouble(), 0.00000001); + assertEquals(f1, readBuffer.readFloat(), 0.000001); readBuffer.readerIndex(0); - Assert.assertEquals(str1, readBuffer.readUTF()); - Assert.assertEquals(str2, readBuffer.readString()); - Assert.assertEquals(d1, readBuffer.readDouble(), 0.00000001); - Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001); + assertEquals(str1, readBuffer.readUTF()); + assertEquals(str2, readBuffer.readString()); + assertEquals(d1, readBuffer.readDouble(), 0.00000001); + assertEquals(f1, readBuffer.readFloat(), 0.000001); readBuffer.close(); } @@ -256,7 +259,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { buffer.readBytes(bytes, 0, 5); for (byte i = 0; i < 5; i++) { - Assert.assertEquals(i, bytes[i]); + assertEquals(i, bytes[i]); } final CountDownLatch latchGo = new CountDownLatch(1); @@ -288,7 +291,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { t.join(); - Assert.assertEquals(0, errorCount.get()); + assertEquals(0, errorCount.get()); } @@ -300,7 +303,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { readBuffer.readBytes(bytes, 0, 5); for (byte i = 0; i < 5; i++) { - Assert.assertEquals(i, bytes[i]); + assertEquals(i, bytes[i]); } } @@ -321,13 +324,13 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { outBuffer.readerIndex(0); for (int i = 0; i < 10240 * 10; i++) { - assertEquals("position " + i, getSamplebyte(i), outBuffer.readByte()); + assertEquals(getSamplebyte(i), outBuffer.readByte(), "position " + i); } outBuffer.readerIndex(0); for (int i = 0; i < 10240 * 10; i++) { - assertEquals("position " + i, getSamplebyte(i), outBuffer.readByte()); + assertEquals(getSamplebyte(i), outBuffer.readByte(), "position " + i); } } finally { outBuffer.close(); @@ -405,31 +408,31 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { twaiter.setDaemon(true); twaiter.start(); - Assert.assertTrue(done1.await(10, TimeUnit.SECONDS)); + assertTrue(done1.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(3, count.get()); - Assert.assertEquals(1024 * 3, totalBytes.get()); + assertEquals(3, count.get()); + assertEquals(1024 * 3, totalBytes.get()); for (int i = 0; i < 8; i++) { outBuffer.addPacket(new byte[1024], 1, true); } - Assert.assertEquals(1, waiting.getCount()); + assertEquals(1, waiting.getCount()); outBuffer.addPacket(new byte[123], 1, false); - Assert.assertTrue(done2.await(10, TimeUnit.SECONDS)); + assertTrue(done2.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(waiting.await(10, TimeUnit.SECONDS)); + assertTrue(waiting.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(12, count.get()); - Assert.assertEquals(1024 * 11 + 123, totalBytes.get()); + assertEquals(12, count.get()); + assertEquals(1024 * 11 + 123, totalBytes.get()); treader.join(); twaiter.join(); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); input.close(); } @@ -465,7 +468,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { } catch (ActiveMQException e) { } - assertTrue("It was supposed to wait at least 1 second", System.currentTimeMillis() - time > 1000); + assertTrue(System.currentTimeMillis() - time > 1000, "It was supposed to wait at least 1 second"); } @Test @@ -492,7 +495,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { } }).start(); outBuffer.addPacket(RandomUtil.randomBytes(), 1, true); - assertTrue("The IOException should trigger an immediate failure", latch.await(3, TimeUnit.SECONDS)); + assertTrue(latch.await(3, TimeUnit.SECONDS), "The IOException should trigger an immediate failure"); } @Test @@ -550,11 +553,11 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { try { outBuffer.readByte(); - Assert.fail("supposed to throw an exception"); + fail("supposed to throw an exception"); } catch (IllegalAccessError ignored) { } - Assert.assertTrue("It waited too much", System.currentTimeMillis() - start < 30000); + assertTrue(System.currentTimeMillis() - start < 30000, "It waited too much"); } @@ -652,7 +655,7 @@ public class LargeMessageBufferTest extends ActiveMQTestBase { */ private void validateAgainstSample(final byte[] bytes) { for (int i = 1; i <= 15; i++) { - Assert.assertEquals(i, bytes[i - 1]); + assertEquals(i, bytes[i - 1]); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java index 00f0663895..ed93a9db43 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/ConnectorsServiceTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.config.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -31,8 +34,8 @@ import org.apache.activemq.artemis.core.server.impl.ServiceRegistryImpl; import org.apache.activemq.artemis.tests.unit.core.config.impl.fakes.FakeConnectorService; import org.apache.activemq.artemis.tests.unit.core.config.impl.fakes.FakeConnectorServiceFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ConnectorsServiceTest extends ActiveMQTestBase { @@ -41,7 +44,7 @@ public class ConnectorsServiceTest extends ActiveMQTestBase { private ServiceRegistry serviceRegistry; @Override - @Before + @BeforeEach public void setUp() throws Exception { // Setup Configuration configuration = new ConfigurationImpl(); @@ -108,7 +111,7 @@ public class ConnectorsServiceTest extends ActiveMQTestBase { FakeConnectorServiceFactory connectorServiceFactory = new FakeConnectorServiceFactory(); try { connectorsService.createService(connectorServiceConfiguration, connectorServiceFactory); - assertTrue("Expected exception when creating service with same name", false); + assertTrue(false, "Expected exception when creating service with same name"); } catch (Exception e) { } @@ -128,7 +131,7 @@ public class ConnectorsServiceTest extends ActiveMQTestBase { // Destroy non-existing connector service try { connectorsService.destroyService("myfact"); - assertTrue("Expected exception when destroying non-existing service", false); + assertTrue(false, "Expected exception when destroying non-existing service"); } catch (Exception e) { } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java index 558210a473..baf223b8b5 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/config/impl/TransportConfigurationTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.config.impl; +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.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -24,8 +29,7 @@ import org.apache.activemq.artemis.core.remoting.impl.TransportConfigurationUtil import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TransportConfigurationTest extends ActiveMQTestBase { @@ -35,28 +39,28 @@ public class TransportConfigurationTest extends ActiveMQTestBase { public void testSplitNullAddress() throws Exception { String[] addresses = TransportConfiguration.splitHosts(null); - Assert.assertNotNull(addresses); - Assert.assertEquals(0, addresses.length); + assertNotNull(addresses); + assertEquals(0, addresses.length); } @Test public void testSplitSingleAddress() throws Exception { String[] addresses = TransportConfiguration.splitHosts("localhost"); - Assert.assertNotNull(addresses); - Assert.assertEquals(1, addresses.length); - Assert.assertEquals("localhost", addresses[0]); + assertNotNull(addresses); + assertEquals(1, addresses.length); + assertEquals("localhost", addresses[0]); } @Test public void testSplitManyAddresses() throws Exception { String[] addresses = TransportConfiguration.splitHosts("localhost, 127.0.0.1, 192.168.0.10"); - Assert.assertNotNull(addresses); - Assert.assertEquals(3, addresses.length); - Assert.assertEquals("localhost", addresses[0]); - Assert.assertEquals("127.0.0.1", addresses[1]); - Assert.assertEquals("192.168.0.10", addresses[2]); + assertNotNull(addresses); + assertEquals(3, addresses.length); + assertEquals("localhost", addresses[0]); + assertEquals("127.0.0.1", addresses[1]); + assertEquals("192.168.0.10", addresses[2]); } @Test @@ -69,7 +73,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase { params2.put("host", "blah"); params2.put("port", "5467"); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); } @Test @@ -82,7 +86,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase { params2.put("host", "blah2"); params2.put("port", "5467"); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertFalse(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertFalse(TransportConfigurationUtil.isSameHost(tc1, tc2)); } @Test @@ -93,7 +97,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase { TransportConfiguration tc1 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params1); Map params2 = new HashMap<>(); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); } @Test @@ -104,7 +108,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase { Map params2 = new HashMap<>(); params2.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "blah"); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); } @Test @@ -115,7 +119,7 @@ public class TransportConfigurationTest extends ActiveMQTestBase { Map params2 = new HashMap<>(); params2.put(org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "blah3"); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertFalse(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertFalse(TransportConfigurationUtil.isSameHost(tc1, tc2)); } @Test @@ -125,6 +129,6 @@ public class TransportConfigurationTest extends ActiveMQTestBase { TransportConfiguration tc1 = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params1); Map params2 = new HashMap<>(); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); - Assert.assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); + assertTrue(TransportConfigurationUtil.isSameHost(tc1, tc2)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java index 92237bb895..c94efe5f1e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/AlignedJournalImplTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -37,10 +41,9 @@ import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequen import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Assert; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -120,11 +123,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { file.read(buffer); for (int i = 0; i < 200; i++) { - Assert.assertEquals((byte) 1, buffer.get(i)); + assertEquals((byte) 1, buffer.get(i)); } for (int i = 201; i < 600; i++) { - Assert.assertEquals("Position " + i, (byte) 2, buffer.get(i)); + assertEquals((byte) 2, buffer.get(i), "Position " + i); } } catch (Exception ignored) { @@ -137,7 +140,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { try { journalImpl = new JournalImpl(2000, 2, 2, 0, 0, factory, "tt", "tt", 1000); - Assert.fail("Expected IllegalArgumentException"); + fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ignored) { // expected } @@ -158,15 +161,15 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 10); - Assert.assertEquals(1, records.size()); + assertEquals(1, records.size()); - Assert.assertEquals(13, records.get(0).id); + assertEquals(13, records.get(0).id); - Assert.assertEquals(14, records.get(0).userRecordType); + assertEquals(14, records.get(0).userRecordType); - Assert.assertEquals(1, records.get(0).data.length); + assertEquals(1, records.get(0).data.length); - Assert.assertEquals(15, records.get(0).data[0]); + assertEquals(15, records.get(0).data[0]); } @@ -177,8 +180,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 10); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 25; i++) { byte[] bytes = new byte[5]; @@ -195,15 +198,15 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1024); - Assert.assertEquals(50, records.size()); + assertEquals(50, records.size()); int i = 0; for (RecordInfo recordItem : records) { - Assert.assertEquals(i * 100L, recordItem.id); - Assert.assertEquals(i, recordItem.getUserRecordType()); - Assert.assertEquals(5, recordItem.data.length); + assertEquals(i * 100L, recordItem.id); + assertEquals(i, recordItem.getUserRecordType()); + assertEquals(5, recordItem.data.length); for (int j = 0; j < 5; j++) { - Assert.assertEquals((byte) i, recordItem.data[j]); + assertEquals((byte) i, recordItem.data[j]); } i++; @@ -224,19 +227,19 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { for (RecordInfo recordItem : records) { if (i < 50) { - Assert.assertEquals(i * 100L, recordItem.id); - Assert.assertEquals(i, recordItem.getUserRecordType()); - Assert.assertEquals(5, recordItem.data.length); + assertEquals(i * 100L, recordItem.id); + assertEquals(i, recordItem.getUserRecordType()); + assertEquals(5, recordItem.data.length); for (int j = 0; j < 5; j++) { - Assert.assertEquals((byte) i, recordItem.data[j]); + assertEquals((byte) i, recordItem.data[j]); } } else { - Assert.assertEquals((i - 10) * 100L, recordItem.id); - Assert.assertEquals(i - 10, recordItem.getUserRecordType()); - Assert.assertTrue(recordItem.isUpdate); - Assert.assertEquals(10, recordItem.data.length); + assertEquals((i - 10) * 100L, recordItem.id); + assertEquals(i - 10, recordItem.getUserRecordType()); + assertTrue(recordItem.isUpdate); + assertEquals(10, recordItem.data.length); for (int j = 0; j < 10; j++) { - Assert.assertEquals((byte) 'x', recordItem.data[j]); + assertEquals((byte) 'x', recordItem.data[j]); } } @@ -259,7 +262,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); logger.debug("Initial:--> {}", journalImpl.debug()); @@ -275,7 +278,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { // async requests are done journalImpl.debugWait(); - Assert.assertEquals(3, factory.listFiles("tt").size()); + assertEquals(3, factory.listFiles("tt").size()); for (int i = 10; i < 50; i++) { journalImpl.appendDeleteRecord(i, false); @@ -285,9 +288,9 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); - Assert.assertEquals(3, factory.listFiles("tt").size()); + assertEquals(3, factory.listFiles("tt").size()); } @@ -303,7 +306,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); logger.debug("Initial:--> {}", journalImpl.debug()); @@ -317,7 +320,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { // async requests are done journalImpl.debugWait(); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); for (int i = 0; i < 50; i++) { journalImpl.appendDeleteRecord(i, false); @@ -329,13 +332,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); - Assert.assertEquals(3, factory.listFiles("tt").size()); + assertEquals(3, factory.listFiles("tt").size()); setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(1, records.size()); + assertEquals(1, records.size()); - Assert.assertEquals(1000, records.get(0).id); + assertEquals(1000, records.get(0).id); journalImpl.checkReclaimStatus(); @@ -349,7 +352,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { logger.debug("Files bufferSize: {}", factory.listFiles("tt").size()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @@ -359,29 +362,29 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); journalImpl.appendAddRecordTransactional(1, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); try { journalImpl.appendCommitRecord(1L, true); // This was supposed to throw an exception, as the transaction was // forgotten (interrupted by a reload). - Assert.fail("Supposed to throw exception"); + fail("Supposed to throw exception"); } catch (Exception e) { logger.warn(e.getMessage(), e); } setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); } @@ -393,8 +396,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.setAutoReclaim(false); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(77L, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); @@ -403,25 +406,25 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); journalImpl.appendAddRecordTransactional(78L, 1, (byte) 1, new SimpleEncoding(1, (byte) 1)); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); - Assert.assertEquals(2, incompleteTransactions.size()); - Assert.assertEquals((Long) 77L, incompleteTransactions.get(0)); - Assert.assertEquals((Long) 78L, incompleteTransactions.get(1)); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); + assertEquals(2, incompleteTransactions.size()); + assertEquals((Long) 77L, incompleteTransactions.get(0)); + assertEquals((Long) 78L, incompleteTransactions.get(1)); try { journalImpl.appendCommitRecord(77L, true); // This was supposed to throw an exception, as the transaction was // forgotten (interrupted by a reload). - Assert.fail("Supposed to throw exception"); + fail("Supposed to throw exception"); } catch (Exception e) { logger.debug("Got an expected exception:", e); } @@ -431,8 +434,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.forceMoveNextFile(); journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); } @Test @@ -441,8 +444,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(1, (byte) 1)); @@ -453,18 +456,18 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(10, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(10, records.size()); + assertEquals(0, transactions.size()); journalImpl.checkReclaimStatus(); - Assert.assertEquals(10, journalImpl.getDataFilesCount()); + assertEquals(10, journalImpl.getDataFilesCount()); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecordTransactional(2L, i); @@ -481,13 +484,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.checkReclaimStatus(); - Assert.assertEquals(1, journalImpl.getDataFilesCount()); + assertEquals(1, journalImpl.getDataFilesCount()); setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(1, journalImpl.getDataFilesCount()); + assertEquals(1, journalImpl.getDataFilesCount()); - Assert.assertEquals(3, factory.listFiles("tt").size()); + assertEquals(3, factory.listFiles("tt").size()); } @Test @@ -496,8 +499,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); journalImpl.appendAddRecordTransactional(1L, 2L, (byte) 3, new SimpleEncoding(1900 - JournalImpl.SIZE_ADD_RECORD_TX - 1, (byte) 4)); @@ -507,7 +510,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(1, records.size()); + assertEquals(1, records.size()); } @@ -517,10 +520,10 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 2; i++) { journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); @@ -549,7 +552,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { int posCheckSize = buffer.position(); - Assert.assertEquals(JournalImpl.SIZE_ADD_RECORD_TX + 2, buffer.getInt()); + assertEquals(JournalImpl.SIZE_ADD_RECORD_TX + 2, buffer.getInt()); buffer.position(posCheckSize); @@ -566,13 +569,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); + assertEquals(0, records.size()); journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, journalImpl.getDataFilesCount()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @@ -582,10 +585,10 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 20; i++) { journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); @@ -615,7 +618,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { int posCheckSize = buffer.position(); - Assert.assertEquals(JournalImpl.SIZE_ADD_RECORD_TX + 2, buffer.getInt()); + assertEquals(JournalImpl.SIZE_ADD_RECORD_TX + 2, buffer.getInt()); buffer.position(posCheckSize); @@ -632,7 +635,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(20, records.size()); + assertEquals(20, records.size()); journalImpl.checkReclaimStatus(); @@ -644,11 +647,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100, 10); - Assert.assertEquals(10, factory.listFiles("tt").size()); + assertEquals(10, factory.listFiles("tt").size()); setupAndLoadJournal(JOURNAL_SIZE, 100, 2); - Assert.assertEquals(10, factory.listFiles("tt").size()); + assertEquals(10, factory.listFiles("tt").size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecord(i, (byte) 0, new SimpleEncoding(1, (byte) 0), false); @@ -657,9 +660,9 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100, 2); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); for (int i = 0; i < 10; i++) { journalImpl.appendDeleteRecord(i, false); @@ -671,9 +674,9 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100, 2); - Assert.assertEquals(0, records.size()); + assertEquals(0, records.size()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @Test @@ -682,10 +685,10 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); @@ -727,13 +730,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); + assertEquals(0, records.size()); journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, journalImpl.getDataFilesCount()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @@ -743,8 +746,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1L, i, (byte) 0, new SimpleEncoding(1, (byte) 15)); @@ -773,7 +776,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(1, records.size()); + assertEquals(1, records.size()); } @Test @@ -782,8 +785,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 50; i++) { if (i == 10) { @@ -807,7 +810,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(40, records.size()); + assertEquals(40, records.size()); } @@ -817,8 +820,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); SimpleEncoding xid = new SimpleEncoding(10, (byte) 1); @@ -832,22 +835,22 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(1, transactions.size()); - Assert.assertEquals(1, transactions.get(0).getRecordsToDelete().size()); - Assert.assertEquals(1, records.size()); + assertEquals(1, transactions.size()); + assertEquals(1, transactions.get(0).getRecordsToDelete().size()); + assertEquals(1, records.size()); for (RecordInfo record : transactions.get(0).getRecordsToDelete()) { byte[] data = record.data; - Assert.assertEquals(100, data.length); + assertEquals(100, data.length); for (byte element : data) { - Assert.assertEquals((byte) 'j', element); + assertEquals((byte) 'j', element); } } - Assert.assertEquals(10, transactions.get(0).getExtraData().length); + assertEquals(10, transactions.get(0).getExtraData().length); for (int i = 0; i < 10; i++) { - Assert.assertEquals((byte) 1, transactions.get(0).getExtraData()[i]); + assertEquals((byte) 1, transactions.get(0).getExtraData()[i]); } journalImpl.appendCommitRecord(1L, false); @@ -856,8 +859,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, transactions.size()); - Assert.assertEquals(0, records.size()); + assertEquals(0, transactions.size()); + assertEquals(0, records.size()); } @@ -867,8 +870,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(50, (byte) 1)); @@ -881,29 +884,29 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.appendPrepareRecord(1L, xid1, false); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); setupAndLoadJournal(JOURNAL_SIZE, 1024); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(1, transactions.size()); + assertEquals(0, records.size()); + assertEquals(1, transactions.size()); - Assert.assertEquals(10, transactions.get(0).getExtraData().length); + assertEquals(10, transactions.get(0).getExtraData().length); for (int i = 0; i < 10; i++) { - Assert.assertEquals((byte) 1, transactions.get(0).getExtraData()[i]); + assertEquals((byte) 1, transactions.get(0).getExtraData()[i]); } journalImpl.checkReclaimStatus(); - Assert.assertEquals(10, journalImpl.getDataFilesCount()); + assertEquals(10, journalImpl.getDataFilesCount()); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); journalImpl.appendCommitRecord(1L, false); setupAndLoadJournal(JOURNAL_SIZE, 1024); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); journalImpl.checkReclaimStatus(); @@ -917,24 +920,24 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(1, transactions.size()); + assertEquals(1, transactions.size()); - Assert.assertEquals(15, transactions.get(0).getExtraData().length); + assertEquals(15, transactions.get(0).getExtraData().length); for (byte element : transactions.get(0).getExtraData()) { - Assert.assertEquals(2, element); + assertEquals(2, element); } - Assert.assertEquals(10, journalImpl.getDataFilesCount()); + assertEquals(10, journalImpl.getDataFilesCount()); - Assert.assertEquals(12, factory.listFiles("tt").size()); + assertEquals(12, factory.listFiles("tt").size()); journalImpl.appendCommitRecord(2L, false); setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); journalImpl.forceMoveNextFile(); @@ -950,8 +953,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); for (int i = 0; i < 10; i++) { journalImpl.appendAddRecordTransactional(1, i, (byte) 1, new SimpleEncoding(50, (byte) 1)); @@ -960,8 +963,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.appendPrepareRecord(1L, new SimpleEncoding(13, (byte) 0), false); setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(1, transactions.size()); + assertEquals(0, records.size()); + assertEquals(1, transactions.size()); SequentialFile file = factory.createSequentialFile("tt-1.tt"); @@ -990,8 +993,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); } @Test @@ -1015,13 +1018,13 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, journalImpl.getDataFilesCount()); setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, journalImpl.getDataFilesCount()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @@ -1040,11 +1043,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); } // It should be ok to write records on NIO, and later read then on AIO @@ -1062,11 +1065,11 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 100); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); setupAndLoadJournal(JOURNAL_SIZE, 512); - Assert.assertEquals(10, records.size()); + assertEquals(10, records.size()); } @Test @@ -1083,17 +1086,17 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(1, journalImpl.getDataFilesCount()); + assertEquals(1, journalImpl.getDataFilesCount()); - Assert.assertEquals(1, transactions.size()); + assertEquals(1, transactions.size()); journalImpl.forceMoveNextFile(); setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(1, journalImpl.getDataFilesCount()); + assertEquals(1, journalImpl.getDataFilesCount()); - Assert.assertEquals(1, transactions.size()); + assertEquals(1, transactions.size()); journalImpl.appendCommitRecord(2L, false); @@ -1107,8 +1110,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.debugWait(); journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, transactions.size()); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, transactions.size()); + assertEquals(0, journalImpl.getDataFilesCount()); } @@ -1127,8 +1130,8 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { setupAndLoadJournal(JOURNAL_SIZE, 1); - Assert.assertEquals(0, records.size()); - Assert.assertEquals(0, transactions.size()); + assertEquals(0, records.size()); + assertEquals(0, transactions.size()); final CountDownLatch latchReady = new CountDownLatch(2); final CountDownLatch latchStart = new CountDownLatch(1); @@ -1197,7 +1200,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { t1.join(); t2.join(); - Assert.assertEquals(2, finishedOK.intValue()); + assertEquals(2, finishedOK.intValue()); journalImpl.debugWait(); @@ -1207,9 +1210,9 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.checkReclaimStatus(); - Assert.assertEquals(0, journalImpl.getDataFilesCount()); + assertEquals(0, journalImpl.getDataFilesCount()); - Assert.assertEquals(2, factory.listFiles("tt").size()); + assertEquals(2, factory.listFiles("tt").size()); } @@ -1255,15 +1258,15 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { journalImpl.load(info, trans, null); - Assert.assertEquals(0, info.size()); - Assert.assertEquals(0, trans.size()); + assertEquals(0, info.size()); + assertEquals(0, trans.size()); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -1280,7 +1283,7 @@ public class AlignedJournalImplTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { stopComponent(journalImpl); if (factory != null) diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/BatchCommitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/BatchCommitTest.java index 2e7786e7af..ab901e88f6 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/BatchCommitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/BatchCommitTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.File; import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; @@ -44,10 +47,8 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.SimpleIDGenerator; import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -141,8 +142,8 @@ public class BatchCommitTest extends ActiveMQTestBase { existingRecords.forEach(l -> logger.warn("id {} still in the list", l)); - Assert.assertEquals(0, errors.get()); - Assert.assertEquals(0, existingRecords.size()); + assertEquals(0, errors.get()); + assertEquals(0, existingRecords.size()); return journal; @@ -173,7 +174,7 @@ public class BatchCommitTest extends ActiveMQTestBase { internalTest(JournalType.NIO, "testRunNIO", false); } - @Ignore // TODO: We should fix Mapped eventually for this case + @Disabled // TODO: We should fix Mapped eventually for this case public void testMapped() throws Exception { internalTest(JournalType.MAPPED, "testRunMapped", true); } @@ -185,13 +186,13 @@ public class BatchCommitTest extends ActiveMQTestBase { @Test public void testAIO() throws Exception { - Assume.assumeTrue(LibaioContext.isLoaded()); + assumeTrue(LibaioContext.isLoaded()); internalTest(JournalType.ASYNCIO, "testRunAIO", true); } @Test public void testAIONoSync() throws Exception { - Assume.assumeTrue(LibaioContext.isLoaded()); + assumeTrue(LibaioContext.isLoaded()); internalTest(JournalType.ASYNCIO, "testRunAIO", false); } @@ -219,13 +220,13 @@ public class BatchCommitTest extends ActiveMQTestBase { String dataAsString = new String(r.data); logger.debug("data={}, isUpdate={}, id={}", dataAsString, r.isUpdate, r.id); if (r.isUpdate) { - Assert.assertEquals("up " + r.id, dataAsString); + assertEquals("up " + r.id, dataAsString); } else { - Assert.assertEquals("add " + r.id, dataAsString); + assertEquals("add " + r.id, dataAsString); } }); - Assert.assertEquals(RECORDS * 2, commited.size()); - Assert.assertEquals(0, failedTX.get()); + assertEquals(RECORDS * 2, commited.size()); + assertEquals(0, failedTX.get()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java index bd9ca62e2d..a9e10baed7 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/CleanBufferTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import java.nio.ByteBuffer; @@ -25,8 +27,7 @@ import org.apache.activemq.artemis.core.io.nio.NIOSequentialFileFactory; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CleanBufferTest extends ActiveMQTestBase { @@ -67,7 +68,7 @@ public class CleanBufferTest extends ActiveMQTestBase { buffer.rewind(); for (byte b = 0; b < 100; b++) { - Assert.assertEquals(b, buffer.get()); + assertEquals(b, buffer.get()); } buffer.limit(10); @@ -78,9 +79,9 @@ public class CleanBufferTest extends ActiveMQTestBase { for (byte b = 0; b < 100; b++) { if (b < 10) { - Assert.assertEquals(0, buffer.get()); + assertEquals(0, buffer.get()); } else { - Assert.assertEquals(b, buffer.get()); + assertEquals(b, buffer.get()); } } } finally { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java index 4d81c077e9..654f2a3894 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/FileFactoryTestBase.java @@ -16,13 +16,14 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.ByteBuffer; import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; public abstract class FileFactoryTestBase extends ActiveMQTestBase { @@ -31,7 +32,7 @@ public abstract class FileFactoryTestBase extends ActiveMQTestBase { protected SequentialFileFactory factory; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -53,7 +54,7 @@ public abstract class FileFactoryTestBase extends ActiveMQTestBase { int bytesRead = file.read(bb); - Assert.assertEquals(size, bytesRead); + assertEquals(size, bytesRead); bb.rewind(); @@ -63,7 +64,7 @@ public abstract class FileFactoryTestBase extends ActiveMQTestBase { for (int i = 0; i < size; i++) { // log.debug(" i is {}", i); - Assert.assertEquals(0, bytes[i]); + assertEquals(0, bytes[i]); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournaHistorylBackupTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournaHistorylBackupTest.java index 0c62fb79ae..9462163d76 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournaHistorylBackupTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournaHistorylBackupTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +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.FileOutputStream; import java.io.FilenameFilter; @@ -31,8 +35,7 @@ import org.apache.activemq.artemis.core.journal.impl.JournalFilesRepository; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JournaHistorylBackupTest extends ActiveMQTestBase { @@ -79,7 +82,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { File[] fileList = history.listFiles((a, name) -> name.endsWith(".journal")); - Assert.assertEquals(1, fileList.length); + assertEquals(1, fileList.length); } @Test @@ -91,26 +94,26 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { String fileNameGenerated = journal.getHistoryFileName(1, clebertsBirthday); // I was actually born at 4:30 :) but I need all numbers lower than 2 digits on the test - Assert.assertEquals("cleberts-19720119040507-1.birthday", fileNameGenerated); - Assert.assertEquals("19720119040507", journal.getDatePortion(fileNameGenerated)); + assertEquals("cleberts-19720119040507-1.birthday", fileNameGenerated); + assertEquals("19720119040507", journal.getDatePortion(fileNameGenerated)); long d = journal.getDatePortionMillis(fileNameGenerated); GregorianCalendar compareCalendar = new GregorianCalendar(); compareCalendar.setTimeInMillis(d); - Assert.assertEquals(1972, compareCalendar.get(Calendar.YEAR)); - Assert.assertEquals(0, compareCalendar.get(Calendar.MONTH)); - Assert.assertEquals(19, compareCalendar.get(Calendar.DAY_OF_MONTH)); - Assert.assertEquals(4, compareCalendar.get(Calendar.HOUR_OF_DAY)); - Assert.assertEquals(5, compareCalendar.get(Calendar.MINUTE)); - Assert.assertEquals(7, compareCalendar.get(Calendar.SECOND)); + assertEquals(1972, compareCalendar.get(Calendar.YEAR)); + assertEquals(0, compareCalendar.get(Calendar.MONTH)); + assertEquals(19, compareCalendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(4, compareCalendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(5, compareCalendar.get(Calendar.MINUTE)); + assertEquals(7, compareCalendar.get(Calendar.SECOND)); - Assert.assertFalse(d < clebertsBirthday.getTimeInMillis()); + assertFalse(d < clebertsBirthday.getTimeInMillis()); compareCalendar.set(Calendar.YEAR, 1971); - Assert.assertTrue(compareCalendar.getTimeInMillis() < clebertsBirthday.getTimeInMillis()); + assertTrue(compareCalendar.getTimeInMillis() < clebertsBirthday.getTimeInMillis()); } @@ -121,8 +124,8 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { String withoutBkp = "jrn-1.data"; String withBKP = withoutBkp + ".bkp"; // I was actually born at 4:30 :) but I need all numbers lower than 2 digits on the test - Assert.assertEquals(withoutBkp, journal.removeBackupExtension(withBKP)); - Assert.assertEquals(withoutBkp, journal.removeBackupExtension(withoutBkp)); // it should be possible to do it + assertEquals(withoutBkp, journal.removeBackupExtension(withBKP)); + assertEquals(withoutBkp, journal.removeBackupExtension(withoutBkp)); // it should be possible to do it String withoutBKP = "jrn-1.data"; } @@ -134,7 +137,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { calendar.setTimeInMillis(System.currentTimeMillis()); String fileName = journal.getHistoryFileName(3, calendar); long id = JournalFilesRepository.getFileNameID("jrn", fileName); - Assert.assertEquals(3, id); + assertEquals(3, id); } @Test @@ -179,7 +182,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { File[] files = tempFolder.listFiles(fnf); - Assert.assertEquals(100, files.length); + assertEquals(100, files.length); HashSet hashSet = new HashSet<>(); for (File file : files) { @@ -187,7 +190,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { } for (int i = 0; i < 100; i++) { - Assert.assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); + assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); } } @@ -235,7 +238,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { File[] files = tempFolder.listFiles(fnf); - Assert.assertEquals(200, files.length); + assertEquals(200, files.length); HashSet hashSet = new HashSet<>(); for (File file : files) { @@ -243,11 +246,11 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { } for (int i = 0; i < 100; i++) { - Assert.assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); + assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); } for (int i = 0; i < 100; i++) { - Assert.assertTrue(hashSet.contains(journal.getHistoryFileName(i, oldCalendar))); + assertTrue(hashSet.contains(journal.getHistoryFileName(i, oldCalendar))); } } @@ -295,7 +298,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { File[] files = tempFolder.listFiles(fnf); - Assert.assertEquals(10, files.length); + assertEquals(10, files.length); HashSet hashSet = new HashSet<>(); for (File file : files) { @@ -304,7 +307,7 @@ public class JournaHistorylBackupTest extends ActiveMQTestBase { for (int i = 90; i < 100; i++) { - Assert.assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); + assertTrue(hashSet.contains(journal.getHistoryFileName(i, todayCalendar))); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java index 0162f3266d..74bd3e07e9 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalAsyncTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -27,10 +31,9 @@ import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory; import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.SimpleEncoding; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.After; -import org.junit.Assert; -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; public class JournalAsyncTest extends ActiveMQTestBase { @@ -94,13 +97,13 @@ public class JournalAsyncTest extends ActiveMQTestBase { LocalThread t = new LocalThread(); t.start(); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); Thread.yield(); Thread.sleep(100); - Assert.assertTrue(t.isAlive()); + assertTrue(t.isAlive()); factory.flushAllCallbacks(); @@ -148,19 +151,19 @@ public class JournalAsyncTest extends ActiveMQTestBase { LocalThread t = new LocalThread(); t.start(); - Assert.assertFalse("journal.append with sync true should hold until the write is done", latch.await(100, TimeUnit.MILLISECONDS)); + assertFalse(latch.await(100, TimeUnit.MILLISECONDS), "journal.append with sync true should hold until the write is done"); Thread.yield(); - Assert.assertTrue(t.isAlive()); + assertTrue(t.isAlive()); latchHoldDirect.countDown(); - Assert.assertTrue(latch.await(30, TimeUnit.SECONDS)); + assertTrue(latch.await(30, TimeUnit.SECONDS)); t.join(); - Assert.assertFalse(t.isAlive()); + assertFalse(t.isAlive()); if (t.e != null) { throw t.e; @@ -220,15 +223,15 @@ public class JournalAsyncTest extends ActiveMQTestBase { LocalThread t = new LocalThread(); t.start(); - Assert.assertTrue("journal.append with sync true and IOContext should not hold thread", latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS), "journal.append with sync true and IOContext should not hold thread"); latchHoldDirect.countDown(); - Assert.assertTrue(latch.await(30, TimeUnit.SECONDS)); + assertTrue(latch.await(30, TimeUnit.SECONDS)); t.join(); - Assert.assertFalse(t.isAlive()); + assertFalse(t.isAlive()); if (t.e != null) { throw t.e; @@ -260,7 +263,7 @@ public class JournalAsyncTest extends ActiveMQTestBase { try { journalImpl.appendAddRecordTransactional(1L, 2, (byte) 1, new SimpleEncoding(1, (byte) 0)); journalImpl.appendCommitRecord(1L, true); - Assert.fail("Exception expected"); + fail("Exception expected"); // An exception already happened in one of the elements on this transaction. // We can't accept any more elements on the transaction } catch (Exception ignored) { @@ -278,7 +281,7 @@ public class JournalAsyncTest extends ActiveMQTestBase { try { journalImpl.appendAddRecord(1L, (byte) 0, new SimpleEncoding(1, (byte) 0), true); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (Exception ignored) { } @@ -288,7 +291,7 @@ public class JournalAsyncTest extends ActiveMQTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -303,7 +306,7 @@ public class JournalAsyncTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { if (journalImpl != null) { try { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalFileRepositoryOrderTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalFileRepositoryOrderTest.java index f20eb5eacd..771f2807d1 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalFileRepositoryOrderTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalFileRepositoryOrderTest.java @@ -17,6 +17,9 @@ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.LinkedList; import java.util.concurrent.BlockingDeque; import java.util.concurrent.ExecutorService; @@ -32,8 +35,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JournalFileRepositoryOrderTest extends ActiveMQTestBase { @@ -73,14 +75,14 @@ public class JournalFileRepositoryOrderTest extends ActiveMQTestBase { LinkedList values = new LinkedList<>(); for (int i = 0; i < 5000; i++) { file = repository.openFile(); - Assert.assertNotNull(file); + assertNotNull(file); values.add(file.getRecordID()); dataFiles.push(file); } int previous = Integer.MIN_VALUE; for (Integer v : values) { - Assert.assertTrue(v.intValue() > previous); + assertTrue(v.intValue() > previous); previous = v; } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java index fdae381786..d80caaa9f0 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/ReclaimerTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.apache.activemq.artemis.core.journal.impl.Reclaimer.scan; +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.HashMap; import java.util.Map; @@ -23,18 +28,15 @@ import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.journal.impl.JournalFile; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.apache.activemq.artemis.core.journal.impl.Reclaimer.scan; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ReclaimerTest extends ActiveMQTestBase { private JournalFile[] files; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); } @@ -702,13 +704,13 @@ public class ReclaimerTest extends ActiveMQTestBase { private void assertCanDelete(final int... fileNumber) { for (int num : fileNumber) { - Assert.assertTrue(files[num].isCanReclaim()); + assertTrue(files[num].isCanReclaim()); } } private void assertCantDelete(final int... fileNumber) { for (int num : fileNumber) { - Assert.assertFalse(files[num].isCanReclaim()); + assertFalse(files[num].isCanReclaim()); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java index fb3a962665..cb42f67dc2 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/TimedBufferTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.journal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -35,8 +38,7 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.Env; import org.apache.activemq.artemis.utils.ReusableLatch; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -105,18 +107,18 @@ public class TimedBufferTest extends ActiveMQTestBase { timedBuffer.checkSize(1); - Assert.assertEquals(1, flushTimes.get()); + assertEquals(1, flushTimes.get()); ByteBuffer flushedBuffer = buffers.get(0); - Assert.assertEquals(100, flushedBuffer.limit()); + assertEquals(100, flushedBuffer.limit()); - Assert.assertEquals(100, flushedBuffer.capacity()); + assertEquals(100, flushedBuffer.capacity()); flushedBuffer.rewind(); for (int i = 0; i < 100; i++) { - Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); + assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); } } finally { timedBuffer.stop(); @@ -183,7 +185,7 @@ public class TimedBufferTest extends ActiveMQTestBase { timedBuffer.addBytes(buff, true, callback); Thread.sleep(100); timedBuffer.addBytes(buff, true, callback); - Assert.assertTrue(latchFlushed.await(5, TimeUnit.SECONDS)); + assertTrue(latchFlushed.await(5, TimeUnit.SECONDS)); latchFlushed.setCount(5); @@ -195,17 +197,17 @@ public class TimedBufferTest extends ActiveMQTestBase { timedBuffer.addBytes(buff, true, callback); Thread.sleep(1); } - Assert.assertTrue(latchFlushed.await(5, TimeUnit.SECONDS)); + assertTrue(latchFlushed.await(5, TimeUnit.SECONDS)); // The purpose of the timed buffer is to batch writes up to a millisecond.. or up to the size of the buffer. - Assert.assertTrue("Timed Buffer is not batching accordingly, it was expected to take at least 500 seconds batching multiple writes while it took " + (System.currentTimeMillis() - time) + " milliseconds", System.currentTimeMillis() - time >= 450); + assertTrue(System.currentTimeMillis() - time >= 450, "Timed Buffer is not batching accordingly, it was expected to take at least 500 seconds batching multiple writes while it took " + (System.currentTimeMillis() - time) + " milliseconds"); // ^^ there are some discounts that can happen inside the timed buffer that are still considered valid (like discounting the time it took to perform the operation itself // for that reason the test has been failing (before this commit) at 499 or 480 milliseconds. So, I'm using a reasonable number close to 500 milliseconds that would still be valid for the test // it should be in fact only writing once.. // i will set for 3 just in case there's a GC or anything else happening on the test - Assert.assertTrue("Too many writes were called", flushes.get() <= 3); + assertTrue(flushes.get() <= 3, "Too many writes were called"); } finally { timedBuffer.stop(); } @@ -388,7 +390,7 @@ public class TimedBufferTest extends ActiveMQTestBase { //while it has to be IOPS = 1/timeout logger.debug("elapsed time: {} with timeout: {}", elapsedTime, timeout); final long maxExpected = timeout + deviceTime; - Assert.assertTrue("elapsed = " + elapsedTime + " max expected = " + maxExpected, elapsedTime <= maxExpected); + assertTrue(elapsedTime <= maxExpected, "elapsed = " + elapsedTime + " max expected = " + maxExpected); } finally { timedBuffer.stop(); } @@ -429,7 +431,7 @@ public class TimedBufferTest extends ActiveMQTestBase { //while it has to be IOPS = 1/timeout logger.debug("elapsed time: {} with timeout: {}", elapsedTime, timeout); final long maxExpected = timeout + deviceTime; - Assert.assertTrue("elapsed = " + elapsedTime + " max expected = " + maxExpected, elapsedTime <= maxExpected); + assertTrue(elapsedTime <= maxExpected, "elapsed = " + elapsedTime + " max expected = " + maxExpected); } finally { timedBuffer.stop(); } @@ -483,7 +485,7 @@ public class TimedBufferTest extends ActiveMQTestBase { Thread.sleep(200); int count = flushTimes.get(); - Assert.assertTrue(count < 3); + assertTrue(count < 3); bytes = new byte[10]; for (int j = 0; j < 10; j++) { @@ -509,18 +511,18 @@ public class TimedBufferTest extends ActiveMQTestBase { Thread.sleep(500); - Assert.assertEquals(count + 2, flushTimes.get()); + assertEquals(count + 2, flushTimes.get()); ByteBuffer flushedBuffer = buffers.get(0); - Assert.assertEquals(30, flushedBuffer.limit()); + assertEquals(30, flushedBuffer.limit()); - Assert.assertEquals(30, flushedBuffer.capacity()); + assertEquals(30, flushedBuffer.capacity()); flushedBuffer.rewind(); for (int i = 0; i < 30; i++) { - Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); + assertEquals(ActiveMQTestBase.getSamplebyte(i), flushedBuffer.get()); } } finally { timedBuffer.stop(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java index 8876fc5f13..24ab886124 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessageImplTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.core.message.impl; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; @@ -41,8 +47,7 @@ import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; import org.apache.activemq.artemis.utils.Wait; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -67,11 +72,11 @@ public class MessageImplTest extends ActiveMQTestBase { ICoreMessage message = message1; - Assert.assertEquals(type, message.getType()); - Assert.assertEquals(durable, message.isDurable()); - Assert.assertEquals(expiration, message.getExpiration()); - Assert.assertEquals(timestamp, message.getTimestamp()); - Assert.assertEquals(priority, message.getPriority()); + assertEquals(type, message.getType()); + assertEquals(durable, message.isDurable()); + assertEquals(expiration, message.getExpiration()); + assertEquals(timestamp, message.getTimestamp()); + assertEquals(priority, message.getPriority()); final SimpleString destination = new SimpleString(RandomUtil.randomString()); final boolean durable2 = RandomUtil.randomBoolean(); @@ -80,19 +85,19 @@ public class MessageImplTest extends ActiveMQTestBase { final byte priority2 = RandomUtil.randomByte(); message.setAddress(destination); - Assert.assertEquals(destination, message.getAddressSimpleString()); + assertEquals(destination, message.getAddressSimpleString()); message.setDurable(durable2); - Assert.assertEquals(durable2, message.isDurable()); + assertEquals(durable2, message.isDurable()); message.setExpiration(expiration2); - Assert.assertEquals(expiration2, message.getExpiration()); + assertEquals(expiration2, message.getExpiration()); message.setTimestamp(timestamp2); - Assert.assertEquals(timestamp2, message.getTimestamp()); + assertEquals(timestamp2, message.getTimestamp()); message.setPriority(priority2); - Assert.assertEquals(priority2, message.getPriority()); + assertEquals(priority2, message.getPriority()); } } @@ -101,20 +106,20 @@ public class MessageImplTest extends ActiveMQTestBase { public void testExpired() { Message message = new ClientMessageImpl(); - Assert.assertEquals(0, message.getExpiration()); - Assert.assertFalse(message.isExpired()); + assertEquals(0, message.getExpiration()); + assertFalse(message.isExpired()); message.setExpiration(System.currentTimeMillis() + 1000); - Assert.assertFalse(message.isExpired()); + assertFalse(message.isExpired()); message.setExpiration(System.currentTimeMillis() - 1); - Assert.assertTrue(message.isExpired()); + assertTrue(message.isExpired()); message.setExpiration(System.currentTimeMillis() - 1000); - Assert.assertTrue(message.isExpired()); + assertTrue(message.isExpired()); message.setExpiration(0); - Assert.assertFalse(message.isExpired()); + assertFalse(message.isExpired()); } @Test @@ -158,75 +163,75 @@ public class MessageImplTest extends ActiveMQTestBase { SimpleString val9 = new SimpleString(RandomUtil.randomString()); msg.putStringProperty(prop9, val9); - Assert.assertEquals(9, msg.getPropertyNames().size()); - Assert.assertTrue(msg.getPropertyNames().contains(prop1)); - Assert.assertTrue(msg.getPropertyNames().contains(prop2)); - Assert.assertTrue(msg.getPropertyNames().contains(prop3)); - Assert.assertTrue(msg.getPropertyNames().contains(prop4)); - Assert.assertTrue(msg.getPropertyNames().contains(prop5)); - Assert.assertTrue(msg.getPropertyNames().contains(prop6)); - Assert.assertTrue(msg.getPropertyNames().contains(prop7)); - Assert.assertTrue(msg.getPropertyNames().contains(prop8)); - Assert.assertTrue(msg.getPropertyNames().contains(prop9)); + assertEquals(9, msg.getPropertyNames().size()); + assertTrue(msg.getPropertyNames().contains(prop1)); + assertTrue(msg.getPropertyNames().contains(prop2)); + assertTrue(msg.getPropertyNames().contains(prop3)); + assertTrue(msg.getPropertyNames().contains(prop4)); + assertTrue(msg.getPropertyNames().contains(prop5)); + assertTrue(msg.getPropertyNames().contains(prop6)); + assertTrue(msg.getPropertyNames().contains(prop7)); + assertTrue(msg.getPropertyNames().contains(prop8)); + assertTrue(msg.getPropertyNames().contains(prop9)); - Assert.assertTrue(msg.containsProperty(prop1)); - Assert.assertTrue(msg.containsProperty(prop2)); - Assert.assertTrue(msg.containsProperty(prop3)); - Assert.assertTrue(msg.containsProperty(prop4)); - Assert.assertTrue(msg.containsProperty(prop5)); - Assert.assertTrue(msg.containsProperty(prop6)); - Assert.assertTrue(msg.containsProperty(prop7)); - Assert.assertTrue(msg.containsProperty(prop8)); - Assert.assertTrue(msg.containsProperty(prop9)); + assertTrue(msg.containsProperty(prop1)); + assertTrue(msg.containsProperty(prop2)); + assertTrue(msg.containsProperty(prop3)); + assertTrue(msg.containsProperty(prop4)); + assertTrue(msg.containsProperty(prop5)); + assertTrue(msg.containsProperty(prop6)); + assertTrue(msg.containsProperty(prop7)); + assertTrue(msg.containsProperty(prop8)); + assertTrue(msg.containsProperty(prop9)); - Assert.assertEquals(val1, msg.getObjectProperty(prop1)); - Assert.assertEquals(val2, msg.getObjectProperty(prop2)); - Assert.assertEquals(val3, msg.getObjectProperty(prop3)); - Assert.assertEquals(val4, msg.getObjectProperty(prop4)); - Assert.assertEquals(val5, msg.getObjectProperty(prop5)); - Assert.assertEquals(val6, msg.getObjectProperty(prop6)); - Assert.assertEquals(val7, msg.getObjectProperty(prop7)); - Assert.assertEquals(val8, msg.getObjectProperty(prop8)); - Assert.assertEquals(val9, msg.getObjectProperty(prop9)); + assertEquals(val1, msg.getObjectProperty(prop1)); + assertEquals(val2, msg.getObjectProperty(prop2)); + assertEquals(val3, msg.getObjectProperty(prop3)); + assertEquals(val4, msg.getObjectProperty(prop4)); + assertEquals(val5, msg.getObjectProperty(prop5)); + assertEquals(val6, msg.getObjectProperty(prop6)); + assertEquals(val7, msg.getObjectProperty(prop7)); + assertEquals(val8, msg.getObjectProperty(prop8)); + assertEquals(val9, msg.getObjectProperty(prop9)); SimpleString val10 = new SimpleString(RandomUtil.randomString()); // test overwrite msg.putStringProperty(prop9, val10); - Assert.assertEquals(val10, msg.getObjectProperty(prop9)); + assertEquals(val10, msg.getObjectProperty(prop9)); int val11 = RandomUtil.randomInt(); msg.putIntProperty(prop9, val11); - Assert.assertEquals(val11, msg.getObjectProperty(prop9)); + assertEquals(val11, msg.getObjectProperty(prop9)); msg.removeProperty(prop1); - Assert.assertEquals(8, msg.getPropertyNames().size()); - Assert.assertTrue(msg.getPropertyNames().contains(prop2)); - Assert.assertTrue(msg.getPropertyNames().contains(prop3)); - Assert.assertTrue(msg.getPropertyNames().contains(prop4)); - Assert.assertTrue(msg.getPropertyNames().contains(prop5)); - Assert.assertTrue(msg.getPropertyNames().contains(prop6)); - Assert.assertTrue(msg.getPropertyNames().contains(prop7)); - Assert.assertTrue(msg.getPropertyNames().contains(prop8)); - Assert.assertTrue(msg.getPropertyNames().contains(prop9)); + assertEquals(8, msg.getPropertyNames().size()); + assertTrue(msg.getPropertyNames().contains(prop2)); + assertTrue(msg.getPropertyNames().contains(prop3)); + assertTrue(msg.getPropertyNames().contains(prop4)); + assertTrue(msg.getPropertyNames().contains(prop5)); + assertTrue(msg.getPropertyNames().contains(prop6)); + assertTrue(msg.getPropertyNames().contains(prop7)); + assertTrue(msg.getPropertyNames().contains(prop8)); + assertTrue(msg.getPropertyNames().contains(prop9)); msg.removeProperty(prop2); - Assert.assertEquals(7, msg.getPropertyNames().size()); - Assert.assertTrue(msg.getPropertyNames().contains(prop3)); - Assert.assertTrue(msg.getPropertyNames().contains(prop4)); - Assert.assertTrue(msg.getPropertyNames().contains(prop5)); - Assert.assertTrue(msg.getPropertyNames().contains(prop6)); - Assert.assertTrue(msg.getPropertyNames().contains(prop7)); - Assert.assertTrue(msg.getPropertyNames().contains(prop8)); - Assert.assertTrue(msg.getPropertyNames().contains(prop9)); + assertEquals(7, msg.getPropertyNames().size()); + assertTrue(msg.getPropertyNames().contains(prop3)); + assertTrue(msg.getPropertyNames().contains(prop4)); + assertTrue(msg.getPropertyNames().contains(prop5)); + assertTrue(msg.getPropertyNames().contains(prop6)); + assertTrue(msg.getPropertyNames().contains(prop7)); + assertTrue(msg.getPropertyNames().contains(prop8)); + assertTrue(msg.getPropertyNames().contains(prop9)); msg.removeProperty(prop9); - Assert.assertEquals(6, msg.getPropertyNames().size()); - Assert.assertTrue(msg.getPropertyNames().contains(prop3)); - Assert.assertTrue(msg.getPropertyNames().contains(prop4)); - Assert.assertTrue(msg.getPropertyNames().contains(prop5)); - Assert.assertTrue(msg.getPropertyNames().contains(prop6)); - Assert.assertTrue(msg.getPropertyNames().contains(prop7)); - Assert.assertTrue(msg.getPropertyNames().contains(prop8)); + assertEquals(6, msg.getPropertyNames().size()); + assertTrue(msg.getPropertyNames().contains(prop3)); + assertTrue(msg.getPropertyNames().contains(prop4)); + assertTrue(msg.getPropertyNames().contains(prop5)); + assertTrue(msg.getPropertyNames().contains(prop6)); + assertTrue(msg.getPropertyNames().contains(prop7)); + assertTrue(msg.getPropertyNames().contains(prop8)); msg.removeProperty(prop3); msg.removeProperty(prop4); @@ -234,7 +239,7 @@ public class MessageImplTest extends ActiveMQTestBase { msg.removeProperty(prop6); msg.removeProperty(prop7); msg.removeProperty(prop8); - Assert.assertEquals(0, msg.getPropertyNames().size()); + assertEquals(0, msg.getPropertyNames().size()); } } @@ -400,7 +405,7 @@ public class MessageImplTest extends ActiveMQTestBase { t.join(); } - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } private void simulateRead(ActiveMQBuffer buf) { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessagePropertyTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessagePropertyTest.java index d0e5d2417d..f1beb4bfc7 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessagePropertyTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/message/impl/MessagePropertyTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.message.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; @@ -27,8 +32,8 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class MessagePropertyTest extends ActiveMQTestBase { @@ -41,7 +46,7 @@ public class MessagePropertyTest extends ActiveMQTestBase { private static final SimpleString SIMPLE_STRING_KEY = new SimpleString("StringToSimpleString"); @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); server = createServer(true); @@ -93,7 +98,7 @@ public class MessagePropertyTest extends ActiveMQTestBase { try (ClientConsumer consumer = session.createConsumer(ADDRESS)) { for (int i = 0; i < numMessages; i++) { ClientMessage message = consumer.receive(100); - assertNotNull("Expecting a message " + i, message); + assertNotNull(message, "Expecting a message " + i); assertMessageBody(i, message); assertEquals(i, message.getIntProperty("int").intValue()); assertEquals((short) i, message.getShortProperty("short").shortValue()); @@ -108,7 +113,7 @@ public class MessagePropertyTest extends ActiveMQTestBase { message.acknowledge(); } - assertNull("no more messages", consumer.receive(50)); + assertNull(consumer.receive(50), "no more messages"); } session.commit(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java index de7c66b258..e8b229651c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagePositionTest.java @@ -17,7 +17,7 @@ package org.apache.activemq.artemis.tests.unit.core.paging.impl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PagePositionTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java index 7d4dbecb44..dd0e19dac3 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PageTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.paging.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.ExecutorService; @@ -44,14 +47,13 @@ import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.collections.LinkedList; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; import org.apache.activemq.artemis.utils.critical.EmptyCriticalAnalyzer; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class PageTest extends ActiveMQTestBase { - @Before + @BeforeEach public void registerProtocols() { MessagePersister.registerPersister(CoreMessagePersister.getInstance()); MessagePersister.registerPersister(AMQPMessagePersister.getInstance()); @@ -124,11 +126,11 @@ public class PageTest extends ActiveMQTestBase { Page page = new Page(new SimpleString("something"), storageManager, factory, file, 10); - Assert.assertEquals(10, page.getPageId()); + assertEquals(10, page.getPageId()); page.open(true); - Assert.assertEquals(1, factory.listFiles("page").size()); + assertEquals(1, factory.listFiles("page").size()); SimpleString simpleDestination = new SimpleString("Test"); @@ -145,33 +147,33 @@ public class PageTest extends ActiveMQTestBase { LinkedList msgs = page.read(storageManager, largeMessages); - Assert.assertEquals(numberOfElements, msgs.size()); + assertEquals(numberOfElements, msgs.size()); - Assert.assertEquals(numberOfElements, page.getNumberOfMessages()); + assertEquals(numberOfElements, page.getNumberOfMessages()); for (int i = 0; i < msgs.size(); i++) { final PagedMessage pagedMessage = msgs.get(i); - Assert.assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); - Assert.assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); - Assert.assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); - Assert.assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); + assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); + assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); + assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); + assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); } if (!largeMessages) { Page tmpPage = new Page(new SimpleString("something"), storageManager, factory, file, 10); - Assert.assertEquals(0, tmpPage.read(storageManager, true).size()); - Assert.assertEquals(numberOfElements, tmpPage.getNumberOfMessages()); + assertEquals(0, tmpPage.read(storageManager, true).size()); + assertEquals(numberOfElements, tmpPage.getNumberOfMessages()); } - Assert.assertTrue(page.delete(msgs)); + assertTrue(page.delete(msgs)); try (LinkedListIterator iter = msgs.iterator()) { while (iter.hasNext()) { PagedMessage pagedMessage = iter.next(); - Assert.assertEquals(0, pagedMessage.getMessage().getUsage()); + assertEquals(0, pagedMessage.getMessage().getUsage()); } } - Assert.assertEquals(0, factory.listFiles(".page").size()); + assertEquals(0, factory.listFiles(".page").size()); } @@ -181,11 +183,11 @@ public class PageTest extends ActiveMQTestBase { Page page = new Page(new SimpleString("something"), new NullStorageManager(), factory, file, 10); - Assert.assertEquals(10, page.getPageId()); + assertEquals(10, page.getPageId()); page.open(true); - Assert.assertEquals(1, factory.listFiles("page").size()); + assertEquals(1, factory.listFiles("page").size()); SimpleString simpleDestination = new SimpleString("Test"); @@ -224,20 +226,20 @@ public class PageTest extends ActiveMQTestBase { LinkedList msgs = page1.read(new NullStorageManager()); - Assert.assertEquals(numberOfElements, msgs.size()); + assertEquals(numberOfElements, msgs.size()); - Assert.assertEquals(numberOfElements, page1.getNumberOfMessages()); + assertEquals(numberOfElements, page1.getNumberOfMessages()); for (int i = 0; i < msgs.size(); i++) { - Assert.assertEquals(simpleDestination, msgs.get(i).getMessage().getAddressSimpleString()); + assertEquals(simpleDestination, msgs.get(i).getMessage().getAddressSimpleString()); } page.close(false); page1.delete(null); - Assert.assertEquals(0, factory.listFiles("page").size()); + assertEquals(0, factory.listFiles("page").size()); - Assert.assertEquals(1, factory.listFiles("invalidPage").size()); + assertEquals(1, factory.listFiles("invalidPage").size()); } @@ -264,11 +266,11 @@ public class PageTest extends ActiveMQTestBase { Page page = new Page(new SimpleString("something"), storageManager, factory, file, 10); - Assert.assertEquals(10, page.getPageId()); + assertEquals(10, page.getPageId()); page.open(true); - Assert.assertEquals(1, factory.listFiles("page").size()); + assertEquals(1, factory.listFiles("page").size()); SimpleString simpleDestination = new SimpleString("Test"); @@ -286,37 +288,37 @@ public class PageTest extends ActiveMQTestBase { LinkedList msgs = page.getMessages(); - Assert.assertEquals(numberOfElements, msgs.size()); + assertEquals(numberOfElements, msgs.size()); - Assert.assertEquals(numberOfElements, page.getNumberOfMessages()); + assertEquals(numberOfElements, page.getNumberOfMessages()); for (int i = 0; i < msgs.size(); i++) { final PagedMessage pagedMessage = msgs.get(i); - Assert.assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); - Assert.assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); - Assert.assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); - Assert.assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); + assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); + assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); + assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); + assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); } for (int i = 0; i < msgs.size(); i++) { final PagedMessage pagedMessage = msgsBefore.get(i); - Assert.assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); - Assert.assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); - Assert.assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); - Assert.assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); + assertEquals(simpleDestination, pagedMessage.getMessage().getAddressSimpleString()); + assertEquals(largeMessages, pagedMessage.getMessage().isLargeMessage()); + assertEquals(startMessageID + i, pagedMessage.getMessage().getMessageID()); + assertEquals(largeMessages ? 1 : 0, pagedMessage.getMessage().getUsage()); } - Assert.assertTrue(page.delete(msgs)); + assertTrue(page.delete(msgs)); try (LinkedListIterator iter = msgs.iterator()) { while (iter.hasNext()) { PagedMessage pagedMessage = iter.next(); - Assert.assertEquals(0, pagedMessage.getMessage().getUsage()); + assertEquals(0, pagedMessage.getMessage().getUsage()); } } - Assert.assertEquals(0, factory.listFiles(".page").size()); + assertEquals(0, factory.listFiles(".page").size()); } @@ -347,7 +349,7 @@ public class PageTest extends ActiveMQTestBase { for (int i = 0; i < numberOfElements; i++) { writeMessage(storageManager, largeMessages, startMessageID + i, simpleDestination, content, page); - Assert.assertEquals(initialNumberOfMessages + i + 1, page.getNumberOfMessages()); + assertEquals(initialNumberOfMessages + i + 1, page.getNumberOfMessages()); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java index 68024e4fce..355330c2b4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingManagerImplTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.paging.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.ByteBuffer; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -39,9 +44,8 @@ import org.apache.activemq.artemis.core.settings.impl.HierarchicalObjectReposito import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.collections.LinkedList; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class PagingManagerImplTest extends ActiveMQTestBase { @@ -68,11 +72,11 @@ public class PagingManagerImplTest extends ActiveMQTestBase { ICoreMessage msg = createMessage(1L, new SimpleString("simple-test"), createRandomBuffer(10)); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertFalse(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); + assertFalse(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); store.startPaging(); - Assert.assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); + assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); Page page = store.depage(); @@ -82,21 +86,21 @@ public class PagingManagerImplTest extends ActiveMQTestBase { page.close(false, false); - Assert.assertEquals(1, msgs.size()); + assertEquals(1, msgs.size()); ActiveMQTestBase.assertEqualsByteArrays(msg.getBodyBuffer().writerIndex(), msg.getBodyBuffer().toByteBuffer().array(), (msgs.get(0).getMessage()).toCore().getBodyBuffer().toByteBuffer().array()); - Assert.assertTrue(store.isPaging()); + assertTrue(store.isPaging()); - Assert.assertNull(store.depage()); + assertNull(store.depage()); final RoutingContextImpl ctx2 = new RoutingContextImpl(null); - Assert.assertFalse(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); + assertFalse(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); File fileJournalDir = new File(getJournalDir()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java index 79bef75369..08d627310f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/paging/impl/PagingStoreImplTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.core.paging.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -78,10 +84,10 @@ import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; import org.apache.activemq.artemis.utils.collections.LinkedList; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -114,7 +120,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { trans.increment(1, 0); } - Assert.assertEquals(nr1, trans.getNumberOfMessages()); + assertEquals(nr1, trans.getNumberOfMessages()); ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(trans.getEncodeSize()); @@ -123,9 +129,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase { PageTransactionInfo trans2 = new PageTransactionInfoImpl(id1); trans2.decode(buffer); - Assert.assertEquals(id2, trans2.getTransactionID()); + assertEquals(id2, trans2.getTransactionID()); - Assert.assertEquals(nr1, trans2.getNumberOfMessages()); + assertEquals(nr1, trans2.getNumberOfMessages()); } @@ -164,11 +170,11 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); storeImpl.startPaging(); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); List buffers = new ArrayList<>(); @@ -179,12 +185,12 @@ public class PagingStoreImplTest extends ActiveMQTestBase { Message msg = createMessage(1, storeImpl, destination, buffer); - Assert.assertTrue(storeImpl.isPaging()); + assertTrue(storeImpl.isPaging()); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); + assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); storeImpl.addSyncPoint(OperationContextImpl.getContext()); @@ -192,7 +198,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); storeImpl.stop(); } @@ -209,7 +215,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); storeImpl.startPaging(); @@ -225,11 +231,11 @@ public class PagingStoreImplTest extends ActiveMQTestBase { Message msg = createMessage(i, storeImpl, destination, buffer); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); + assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); } - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); storeImpl.addSyncPoint(OperationContextImpl.getContext()); @@ -239,15 +245,15 @@ public class PagingStoreImplTest extends ActiveMQTestBase { LinkedList msg = page.read(new NullStorageManager()); - Assert.assertEquals(numMessages, msg.size()); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(numMessages, msg.size()); + assertEquals(1, storeImpl.getNumberOfPages()); page.close(false); page = storeImpl.depage(); - Assert.assertNull(page); + assertNull(page); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); for (int i = 0; i < numMessages; i++) { ActiveMQBuffer horn1 = buffers.get(i); @@ -255,7 +261,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { horn1.resetReaderIndex(); horn2.resetReaderIndex(); for (int j = 0; j < horn1.writerIndex(); j++) { - Assert.assertEquals(horn1.readByte(), horn2.readByte()); + assertEquals(horn1.readByte(), horn2.readByte()); } } @@ -280,7 +286,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { logger.debug("#repeat {}", repeat); storeImpl.startPaging(); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); storeImpl.getCursorProvider().disableCleanup(); int numMessages = 100; @@ -295,23 +301,23 @@ public class PagingStoreImplTest extends ActiveMQTestBase { msg.putIntProperty("page", page); final RoutingContextImpl ctx = new RoutingContextImpl(null); ctx.addQueue(fakeQueue.getName(), fakeQueue); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); + assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); if (i > 0 && i % 10 == 0) { storeImpl.forceAnotherPage(); page++; - Assert.assertEquals(page, storeImpl.getNumberOfPages()); + assertEquals(page, storeImpl.getNumberOfPages()); } } } - Assert.assertEquals(numMessages / 10, storeImpl.getNumberOfPages()); + assertEquals(numMessages / 10, storeImpl.getNumberOfPages()); PageIterator iterator = subscription.iterator(); for (int i = 0; i < numMessages; i++) { - Assert.assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); PagedReference reference = iterator.next(); - Assert.assertNotNull(reference); - Assert.assertEquals(i, reference.getPagedMessage().getMessage().getIntProperty("i").intValue()); + assertNotNull(reference); + assertEquals(i, reference.getPagedMessage().getMessage().getIntProperty("i").intValue()); int pageOnMsg = reference.getMessage().getIntProperty("page").intValue(); if (pageOnMsg > 2 && pageOnMsg < 10) { subscription.ack(reference); @@ -325,7 +331,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { PageCursorProviderTestAccessor.cleanup(storeImpl.getCursorProvider()); - Assert.assertTrue(storeImpl.isPaging()); + assertTrue(storeImpl.isPaging()); int messagesRead = 0; iterator = subscription.iterator(); @@ -335,28 +341,28 @@ public class PagingStoreImplTest extends ActiveMQTestBase { break; } - Assert.assertTrue(subscription.contains(reference)); + assertTrue(subscription.contains(reference)); logger.debug("#received message {}, {}", messagesRead, reference); messagesRead++; int pageOnMsg = reference.getMessage().getIntProperty("page"); - Assert.assertTrue("received " + reference, pageOnMsg <= 2 || pageOnMsg >= 10); + assertTrue(pageOnMsg <= 2 || pageOnMsg >= 10, "received " + reference); subscription.ack(reference); } iterator.close(); - Assert.assertEquals(30, messagesRead); + assertEquals(30, messagesRead); - Assert.assertEquals(3, storeImpl.getNumberOfPages()); + assertEquals(3, storeImpl.getNumberOfPages()); PageCursorProviderTestAccessor.cleanup(storeImpl.getCursorProvider()); - Assert.assertFalse(storeImpl.isPaging()); + assertFalse(storeImpl.isPaging()); - Assert.assertEquals(1, PagingStoreTestAccessor.getUsedPagesSize(storeImpl)); + assertEquals(1, PagingStoreTestAccessor.getUsedPagesSize(storeImpl)); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); } } @@ -412,7 +418,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { msg.putIntProperty("page", page); final RoutingContextImpl ctx = new RoutingContextImpl(null); ctx.addQueue(fakeQueue.getName(), fakeQueue); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); + assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); if (i > 0 && i % 10 == 0) { storeImpl.forceAnotherPage(); page++; @@ -420,17 +426,17 @@ public class PagingStoreImplTest extends ActiveMQTestBase { } } - Assert.assertEquals(10, storeImpl.getNumberOfPages()); + assertEquals(10, storeImpl.getNumberOfPages()); - Assert.assertEquals(10, factory.listFiles("page").size()); + assertEquals(10, factory.listFiles("page").size()); int messagesRead = 0; PageIterator iterator = subscription.iterator(); for (int i = 1; i <= numMessages; i++) { - Assert.assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); PagedReference reference = iterator.next(); - Assert.assertNotNull(reference); - Assert.assertEquals(i, reference.getPagedMessage().getMessage().getIntProperty("i").intValue()); + assertNotNull(reference); + assertEquals(i, reference.getPagedMessage().getMessage().getIntProperty("i").intValue()); int pageOnMsg = reference.getMessage().getIntProperty("page").intValue(); if (pageOnMsg == 10) { messagesRead++; @@ -439,25 +445,25 @@ public class PagingStoreImplTest extends ActiveMQTestBase { } iterator.close(); - Assert.assertEquals(7, messagesRead); + assertEquals(7, messagesRead); PageCursorProviderTestAccessor.cleanup(storeImpl.getCursorProvider()); - Assert.assertEquals(10, factory.listFiles("page").size()); + assertEquals(10, factory.listFiles("page").size()); - Assert.assertTrue(storeImpl.isPaging()); + assertTrue(storeImpl.isPaging()); storeImpl.forceAnotherPage(); - Assert.assertEquals(11, factory.listFiles("page").size()); + assertEquals(11, factory.listFiles("page").size()); PageCursorProviderTestAccessor.cleanup(storeImpl.getCursorProvider()); - Assert.assertEquals(10, factory.listFiles("page").size()); + assertEquals(10, factory.listFiles("page").size()); - Assert.assertEquals(10, storeImpl.getNumberOfPages()); + assertEquals(10, storeImpl.getNumberOfPages()); - Assert.assertEquals(11 + 10 * repeat, storeImpl.getCurrentWritingPage()); + assertEquals(11 + 10 * repeat, storeImpl.getCurrentWritingPage()); messagesRead = 0; iterator = subscription.iterator(); @@ -468,17 +474,17 @@ public class PagingStoreImplTest extends ActiveMQTestBase { } messagesRead++; int pageOnMsg = reference.getMessage().getIntProperty("page"); - Assert.assertTrue(pageOnMsg != 10); + assertTrue(pageOnMsg != 10); subscription.ack(reference); } iterator.close(); - Assert.assertEquals(90, messagesRead); + assertEquals(90, messagesRead); PageCursorProviderTestAccessor.cleanup(storeImpl.getCursorProvider()); - Assert.assertFalse(storeImpl.isPaging()); + assertFalse(storeImpl.isPaging()); } } @@ -508,12 +514,12 @@ public class PagingStoreImplTest extends ActiveMQTestBase { msg.putIntProperty("page", 1); final RoutingContextImpl ctx = new RoutingContextImpl(null); ctx.addQueue(fakeQueue.getName(), fakeQueue); - Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); + assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()))); } - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); - Assert.assertEquals(1, factory.listFiles("page").size()); + assertEquals(1, factory.listFiles("page").size()); String fileName = storeImpl.createFileName(1); @@ -525,9 +531,9 @@ public class PagingStoreImplTest extends ActiveMQTestBase { int size = PageReadWriter.readFromSequentialFile(storageManager, storeImpl.getStoreName(), factory, file, 1, messages::add, PageReadWriter.SKIP_ALL, null, null); file.close(); - Assert.assertEquals(0, messages.size()); + assertEquals(0, messages.size()); - Assert.assertEquals(10, size); + assertEquals(10, size); } @@ -542,11 +548,11 @@ public class PagingStoreImplTest extends ActiveMQTestBase { store.start(); - Assert.assertEquals(0, store.getNumberOfPages()); + assertEquals(0, store.getNumberOfPages()); store.startPaging(); - Assert.assertEquals(1, store.getNumberOfPages()); + assertEquals(1, store.getNumberOfPages()); List buffers = new ArrayList<>(); @@ -563,10 +569,10 @@ public class PagingStoreImplTest extends ActiveMQTestBase { Message msg = createMessage(i, store, destination, buffer); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); + assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); } - Assert.assertEquals(2, store.getNumberOfPages()); + assertEquals(2, store.getNumberOfPages()); store.addSyncPoint(OperationContextImpl.getContext()); @@ -583,72 +589,72 @@ public class PagingStoreImplTest extends ActiveMQTestBase { page.close(false, false); - Assert.assertEquals(5, msg.size()); + assertEquals(5, msg.size()); for (int i = 0; i < 5; i++) { - Assert.assertEquals(sequence++, msg.get(i).getMessage().getMessageID()); + assertEquals(sequence++, msg.get(i).getMessage().getMessageID()); ActiveMQTestBase.assertEqualsBuffers(18, buffers.get(pageNr * 5 + i), msg.get(i).getMessage().toCore().getBodyBuffer()); } } - Assert.assertEquals(1, store.getNumberOfPages()); + assertEquals(1, store.getNumberOfPages()); - Assert.assertTrue(store.isPaging()); + assertTrue(store.isPaging()); Message msg = createMessage(1, store, destination, buffers.get(0)); final RoutingContextImpl ctx = new RoutingContextImpl(null); - Assert.assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); + assertTrue(store.page(msg, ctx.getTransaction(), ctx.getContextListing(store.getStoreName()))); Page newPage = store.depage(); newPage.open(true); - Assert.assertEquals(1, newPage.read(new NullStorageManager()).size()); + assertEquals(1, newPage.read(new NullStorageManager()).size()); newPage.delete(null); - Assert.assertEquals(1, store.getNumberOfPages()); + assertEquals(1, store.getNumberOfPages()); - Assert.assertTrue(store.isPaging()); + assertTrue(store.isPaging()); - Assert.assertNull(store.depage()); + assertNull(store.depage()); - Assert.assertFalse(store.isPaging()); + assertFalse(store.isPaging()); { final RoutingContextImpl ctx2 = new RoutingContextImpl(null); - Assert.assertFalse(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); + assertFalse(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); } store.startPaging(); { final RoutingContextImpl ctx2 = new RoutingContextImpl(null); - Assert.assertTrue(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); + assertTrue(store.page(msg, ctx2.getTransaction(), ctx2.getContextListing(store.getStoreName()))); } Page page = store.depage(); - Assert.assertNotNull(page); + assertNotNull(page); page.open(true); LinkedList msgs = page.read(new NullStorageManager()); - Assert.assertEquals(1, msgs.size()); + assertEquals(1, msgs.size()); - Assert.assertEquals(1L, msgs.get(0).getMessage().getMessageID()); + assertEquals(1L, msgs.get(0).getMessage().getMessageID()); ActiveMQTestBase.assertEqualsBuffers(18, buffers.get(0), msgs.get(0).getMessage().toCore().getBodyBuffer()); - Assert.assertEquals(1, store.getNumberOfPages()); + assertEquals(1, store.getNumberOfPages()); - Assert.assertTrue(store.isPaging()); + assertTrue(store.isPaging()); - Assert.assertNull(store.depage()); + assertNull(store.depage()); - Assert.assertEquals(0, store.getNumberOfPages()); + assertEquals(0, store.getNumberOfPages()); page.open(true); page.close(false); @@ -684,12 +690,12 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); // Marked the store to be paged storeImpl.startPaging(); - Assert.assertEquals(1, storeImpl.getNumberOfPages()); + assertEquals(1, storeImpl.getNumberOfPages()); final SimpleString destination = new SimpleString("test"); @@ -793,23 +799,23 @@ public class PagingStoreImplTest extends ActiveMQTestBase { Message msgWritten = buffers.remove(id); buffers2.put(id, msg.getMessage()); - Assert.assertNotNull(msgWritten); - Assert.assertEquals(msg.getMessage().getAddress(), msgWritten.getAddress()); + assertNotNull(msgWritten); + assertEquals(msg.getMessage().getAddress(), msgWritten.getAddress()); ActiveMQTestBase.assertEqualsBuffers(10, msgWritten.toCore().getBodyBuffer(), msg.getMessage().toCore().getBodyBuffer()); } } } - Assert.assertEquals(0, buffers.size()); + assertEquals(0, buffers.size()); List files = factory.listFiles("page"); - Assert.assertTrue(files.size() != 0); + assertTrue(files.size() != 0); for (String file : files) { SequentialFile fileTmp = factory.createSequentialFile(file); fileTmp.open(); - Assert.assertTrue("The page file size (" + fileTmp.size() + ") shouldn't be > " + MAX_SIZE, fileTmp.size() <= MAX_SIZE); + assertTrue(fileTmp.size() <= MAX_SIZE, "The page file size (" + fileTmp.size() + ") shouldn't be > " + MAX_SIZE); fileTmp.close(); } @@ -817,13 +823,13 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl2.start(); long numberOfPages = storeImpl2.getNumberOfPages(); - Assert.assertTrue(numberOfPages != 0); + assertTrue(numberOfPages != 0); storeImpl2.startPaging(); storeImpl2.startPaging(); - Assert.assertEquals(numberOfPages, storeImpl2.getNumberOfPages()); + assertEquals(numberOfPages, storeImpl2.getNumberOfPages()); long lastMessageId = messageIdGenerator.incrementAndGet(); Message lastMsg = createMessage(lastMessageId, storeImpl, destination, createRandomBuffer(lastMessageId, 5)); @@ -852,8 +858,8 @@ public class PagingStoreImplTest extends ActiveMQTestBase { msgs.forEach((msg) -> { long id = msg.getMessage().toCore().getBodyBuffer().readLong(); Message msgWritten = buffers2.remove(id); - Assert.assertNotNull(msgWritten); - Assert.assertEquals(msg.getMessage().getAddress(), msgWritten.getAddress()); + assertNotNull(msgWritten); + assertEquals(msg.getMessage().getAddress(), msgWritten.getAddress()); ActiveMQTestBase.assertEqualsByteArrays(msgWritten.toCore().getBodyBuffer().writerIndex(), msgWritten.toCore().getBodyBuffer().toByteBuffer().array(), msg.getMessage().toCore().getBodyBuffer().toByteBuffer().array()); }); } @@ -861,14 +867,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase { lastPage.open(true); LinkedList lastMessages = lastPage.read(new NullStorageManager()); lastPage.close(false, false); - Assert.assertEquals(1, lastMessages.size()); + assertEquals(1, lastMessages.size()); lastMessages.get(0).getMessage().toCore().getBodyBuffer().resetReaderIndex(); - Assert.assertEquals(lastMessages.get(0).getMessage().toCore().getBodyBuffer().readLong(), lastMessageId); + assertEquals(lastMessages.get(0).getMessage().toCore().getBodyBuffer().readLong(), lastMessageId); - Assert.assertEquals(0, buffers2.size()); + assertEquals(0, buffers2.size()); - Assert.assertEquals(0, storeImpl.getAddressSize()); + assertEquals(0, storeImpl.getAddressSize()); storeImpl.stop(); } @@ -888,18 +894,18 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); // Marked the store to be paged storeImpl.startPaging(); storeImpl.depage(); - Assert.assertNull(storeImpl.getCurrentPage()); + assertNull(storeImpl.getCurrentPage()); storeImpl.startPaging(); - Assert.assertNotNull(storeImpl.getCurrentPage()); + assertNotNull(storeImpl.getCurrentPage()); storeImpl.stop(); } @@ -921,12 +927,12 @@ public class PagingStoreImplTest extends ActiveMQTestBase { store.start(); - Assert.assertEquals(0, store.getNumberOfPages()); + assertEquals(0, store.getNumberOfPages()); // Marked the store to be paged store.startPaging(); - Assert.assertEquals(1, store.getNumberOfPages()); + assertEquals(1, store.getNumberOfPages()); final SimpleString destination = new SimpleString("test"); @@ -957,7 +963,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { } }); - Assert.assertTrue(done.await(10, TimeUnit.SECONDS)); + assertTrue(done.await(10, TimeUnit.SECONDS)); done.countUp(); executorService.execute(() -> { @@ -971,10 +977,10 @@ public class PagingStoreImplTest extends ActiveMQTestBase { page.open(true); LinkedList messages = page.read(new NullStorageManager()); messages.forEach(pgmsg -> { - Assert.assertEquals(countOnPage.getAndIncrement(), pgmsg.getMessageNumber()); + assertEquals(countOnPage.getAndIncrement(), pgmsg.getMessageNumber()); Message msg = pgmsg.getMessage(); - Assert.assertEquals(msgsRead.getAndIncrement(), msg.getMessageID()); - Assert.assertEquals(msg.getMessageID(), msg.getLongProperty("count").longValue()); + assertEquals(msgsRead.getAndIncrement(), msg.getMessageID()); + assertEquals(msg.getMessageID(), msg.getLongProperty("count").longValue()); }); page.close(false, false); @@ -990,7 +996,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { }); - Assert.assertTrue(done.await(10, TimeUnit.SECONDS)); + assertTrue(done.await(10, TimeUnit.SECONDS)); store.stop(); @@ -1018,7 +1024,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { storeImpl.start(); - Assert.assertEquals(0, storeImpl.getNumberOfPages()); + assertEquals(0, storeImpl.getNumberOfPages()); // Marked the store to be paged storeImpl.startPaging(); @@ -1056,14 +1062,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase { while (msgsRead.get() < num1 + num2) { page = storeImpl.depage(); - assertNotNull("no page after read " + msgsRead + " msg", page); + assertNotNull(page, "no page after read " + msgsRead + " msg"); page.open(true); LinkedList messages = page.read(new NullStorageManager()); messages.forEach(pgmsg -> { Message msg = pgmsg.getMessage(); - Assert.assertEquals(msgsRead.longValue(), msg.getMessageID()); - Assert.assertEquals(msg.getMessageID(), msg.getLongProperty("count").longValue()); + assertEquals(msgsRead.longValue(), msg.getMessageID()); + assertEquals(msg.getMessageID(), msg.getLongProperty("count").longValue()); msgsRead.incrementAndGet(); }); page.close(false); @@ -1089,7 +1095,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { store.startPaging(); store.stopPaging(); - Assert.assertTrue(loggerHandler.findText("AMQ222038")); + assertTrue(loggerHandler.findText("AMQ222038")); } } @@ -1109,7 +1115,7 @@ public class PagingStoreImplTest extends ActiveMQTestBase { try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { store.startPaging(); store.stopPaging(); - Assert.assertTrue(loggerHandler.findText("AMQ224108")); + assertTrue(loggerHandler.findText("AMQ224108")); } } @@ -1304,21 +1310,21 @@ public class PagingStoreImplTest extends ActiveMQTestBase { assertEquals(100, store.getAddressLimitPercent()); store.checkMemory(trackMemoryChecks, null); - assertEquals("no change", 3, calls.get()); - assertEquals("no change to be sure to be sure!", 3, calls.get()); + assertEquals(3, calls.get(), "no change"); + assertEquals(3, calls.get(), "no change to be sure to be sure!"); store.unblock(); - assertEquals("no change after unblock", 3, calls.get()); + assertEquals(3, calls.get(), "no change after unblock"); store.addSize(-900); assertEquals(10, store.getAddressLimitPercent()); - assertTrue("change", Wait.waitFor(new Wait.Condition() { + assertTrue(Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisfied() throws Exception { return 4 == calls.get(); } - }, 1000, 50)); + }, 1000, 50), "change"); } finally { @@ -1379,14 +1385,14 @@ public class PagingStoreImplTest extends ActiveMQTestBase { // Protected ---------------------------------------------------- @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); executor = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())); } @Override - @After + @AfterEach public void tearDown() throws Exception { executor.shutdown(); super.tearDown(); @@ -1471,7 +1477,8 @@ public class PagingStoreImplTest extends ActiveMQTestBase { } } - @Test(timeout = 10000) + @Test + @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testCheckExecutionIsNotRepeated() throws Exception { SequentialFileFactory factory = new FakeSequentialFileFactory(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java index 4c87e47341..fc8f290e17 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/persistence/impl/BatchIDGeneratorUnitTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.persistence.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.ArrayList; @@ -31,8 +34,7 @@ import org.apache.activemq.artemis.core.persistence.impl.journal.BatchingIDGener import org.apache.activemq.artemis.core.persistence.impl.journal.JournalRecordIds; import org.apache.activemq.artemis.core.persistence.impl.nullpm.NullStorageManager; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { @@ -49,7 +51,7 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { long id1 = batch.generateID(); long id2 = batch.generateID(); - Assert.assertTrue(id2 > id1); + assertTrue(id2 > id1); journal.stop(); batch = new BatchingIDGenerator(0, 1000, getJournalStorageManager(journal)); @@ -57,11 +59,11 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { long id3 = batch.generateID(); - Assert.assertEquals(1001, id3); + assertEquals(1001, id3); long id4 = batch.generateID(); - Assert.assertTrue(id4 > id3 && id4 < 2000); + assertTrue(id4 > id3 && id4 < 2000); batch.persistCurrentID(); @@ -70,7 +72,7 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { loadIDs(journal, batch); long id5 = batch.generateID(); - Assert.assertTrue(id5 > id4 && id5 < 2000); + assertTrue(id5 > id4 && id5 < 2000); long lastId = id5; @@ -91,7 +93,7 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { long id = batch.generateID(); - Assert.assertTrue(id > lastId); + assertTrue(id > lastId); lastId = id; } @@ -107,7 +109,7 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { batch = new BatchingIDGenerator(0, 1000, getJournalStorageManager(journal)); loadIDs(journal, batch); - Assert.assertEquals("No Ids were generated, so the currentID was supposed to stay the same", lastId, batch.getCurrentID()); + assertEquals(lastId, batch.getCurrentID(), "No Ids were generated, so the currentID was supposed to stay the same"); journal.stop(); @@ -120,9 +122,9 @@ public class BatchIDGeneratorUnitTest extends ActiveMQTestBase { journal.start(); journal.load(records, tx, null); - Assert.assertEquals(0, tx.size()); + assertEquals(0, tx.size()); - Assert.assertTrue("Contains " + records.size(), records.size() > 0); + assertTrue(records.size() > 0, "Contains " + records.size()); for (RecordInfo record : records) { if (record.userRecordType == JournalRecordIds.ID_COUNTER_RECORD) { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java index b969d788f5..6989078d97 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressImplTest.java @@ -16,12 +16,14 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.postoffice.Address; import org.apache.activemq.artemis.core.postoffice.impl.AddressImpl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AddressImplTest extends ActiveMQTestBase { @@ -31,7 +33,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s2 = new SimpleString("abcde"); Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); - Assert.assertTrue(a1.matches(a2)); + assertTrue(a1.matches(a2)); } @Test @@ -40,7 +42,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s2 = new SimpleString("a.b"); Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); - Assert.assertTrue(a1.matches(a2)); + assertTrue(a1.matches(a2)); } @Test @@ -49,7 +51,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s2 = new SimpleString("a.b.c.d.e.f.g.h.i.j.k.l.m.n.*"); Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); - Assert.assertFalse(a1.matches(a2)); + assertFalse(a1.matches(a2)); } @Test @@ -60,8 +62,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -72,8 +74,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -84,8 +86,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -96,8 +98,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -108,8 +110,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertTrue(a2.matches(w)); + assertTrue(a1.matches(w)); + assertTrue(a2.matches(w)); } @Test @@ -120,8 +122,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertTrue(a2.matches(w)); + assertTrue(a1.matches(w)); + assertTrue(a2.matches(w)); } @Test @@ -132,8 +134,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertTrue(a2.matches(w)); + assertTrue(a1.matches(w)); + assertTrue(a2.matches(w)); } @Test @@ -144,8 +146,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertTrue(a2.matches(w)); + assertTrue(a1.matches(w)); + assertTrue(a2.matches(w)); } @Test @@ -156,8 +158,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -168,8 +170,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertTrue(a2.matches(w)); + assertTrue(a1.matches(w)); + assertTrue(a2.matches(w)); } @Test @@ -180,8 +182,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -192,8 +194,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -204,8 +206,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -216,8 +218,8 @@ public class AddressImplTest extends ActiveMQTestBase { Address a1 = new AddressImpl(s1); Address a2 = new AddressImpl(s2); Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); - Assert.assertFalse(a2.matches(w)); + assertTrue(a1.matches(w)); + assertFalse(a2.matches(w)); } @Test @@ -226,7 +228,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("a.b.c#"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } @Test @@ -235,7 +237,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("#a.b.c"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } @Test @@ -244,7 +246,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("#*a.b.c"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } @Test @@ -253,7 +255,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("a.b.c*"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } @Test @@ -262,7 +264,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("*a.b.c"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } @Test @@ -271,7 +273,7 @@ public class AddressImplTest extends ActiveMQTestBase { SimpleString s3 = new SimpleString("*a.b.c"); Address a1 = new AddressImpl(s1); Address w = new AddressImpl(s3); - Assert.assertFalse(a1.matches(w)); + assertFalse(a1.matches(w)); } /** @@ -283,6 +285,6 @@ public class AddressImplTest extends ActiveMQTestBase { final SimpleString s3 = new SimpleString("a.b.#.d"); final Address a1 = new AddressImpl(s1); final Address w = new AddressImpl(s3); - Assert.assertTrue(a1.matches(w)); + assertTrue(a1.matches(w)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressMapUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressMapUnitTest.java index 7b7494234a..4ea35ce88c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressMapUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/AddressMapUnitTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +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.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.api.core.SimpleString; @@ -23,11 +27,7 @@ import org.apache.activemq.artemis.core.postoffice.Address; import org.apache.activemq.artemis.core.postoffice.impl.AddressImpl; import org.apache.activemq.artemis.core.postoffice.impl.AddressMap; import org.apache.activemq.artemis.core.postoffice.impl.AddressMapVisitor; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class AddressMapUnitTest { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java index 6fc59acb8d..682d87160f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/BindingsImplTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import javax.transaction.xa.Xid; import java.util.Collections; import java.util.List; @@ -47,7 +49,7 @@ import org.apache.activemq.artemis.core.transaction.TransactionOperation; import org.apache.activemq.artemis.selector.filter.Filterable; import org.apache.activemq.artemis.tests.unit.core.postoffice.impl.fakes.FakeQueue; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BindingsImplTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java index 80f676c725..1bbe1816ea 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -44,10 +46,9 @@ import org.apache.activemq.artemis.utils.ExecutorFactory; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory; import org.apache.activemq.artemis.utils.critical.EmptyCriticalAnalyzer; -import org.junit.After; -import org.junit.Assert; -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; public class DuplicateDetectionUnitTest extends ActiveMQTestBase { @@ -57,14 +58,14 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase { ExecutorFactory factory; @Override - @After + @AfterEach public void tearDown() throws Exception { executor.shutdown(); super.tearDown(); } @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); executor = Executors.newFixedThreadPool(10, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())); @@ -98,7 +99,7 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase { FakePagingManager pagingManager = new FakePagingManager(); journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(null, 0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); - Assert.assertEquals(0, mapDups.size()); + assertEquals(0, mapDups.size()); DuplicateIDCache cacheID = DuplicateIDCaches.persistent(ADDRESS, 10, journal); @@ -114,11 +115,11 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase { journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(null, 0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); - Assert.assertEquals(1, mapDups.size()); + assertEquals(1, mapDups.size()); List> values = mapDups.get(ADDRESS); - Assert.assertEquals(10, values.size()); + assertEquals(10, values.size()); cacheID = DuplicateIDCaches.persistent(ADDRESS, 10, journal); cacheID.load(values); @@ -137,11 +138,11 @@ public class DuplicateDetectionUnitTest extends ActiveMQTestBase { journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(null, 0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null)); - Assert.assertEquals(1, mapDups.size()); + assertEquals(1, mapDups.size()); values = mapDups.get(ADDRESS); - Assert.assertEquals(10, values.size()); + assertEquals(10, values.size()); scheduledThreadPool.shutdown(); } finally { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java index 4df49bf559..00ac5fc798 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/QueueComparatorTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -24,8 +26,7 @@ import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.impl.ScaleDownHandler; import org.apache.activemq.artemis.tests.unit.core.postoffice.impl.fakes.FakeQueue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class QueueComparatorTest { @@ -43,14 +44,14 @@ public class QueueComparatorTest { queues.add(queue2); queues.add(queue3); - Assert.assertEquals(1, queues.get(0).getMessageCount()); - Assert.assertEquals(2, queues.get(1).getMessageCount()); - Assert.assertEquals(3, queues.get(2).getMessageCount()); + assertEquals(1, queues.get(0).getMessageCount()); + assertEquals(2, queues.get(1).getMessageCount()); + assertEquals(3, queues.get(2).getMessageCount()); Collections.sort(queues, new ScaleDownHandler.OrderQueueByNumberOfReferencesComparator()); - Assert.assertEquals(3, queues.get(0).getMessageCount()); - Assert.assertEquals(2, queues.get(1).getMessageCount()); - Assert.assertEquals(1, queues.get(2).getMessageCount()); + assertEquals(3, queues.get(0).getMessageCount()); + assertEquals(2, queues.get(1).getMessageCount()); + assertEquals(1, queues.get(2).getMessageCount()); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerPerfTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerPerfTest.java index b9858f788b..21abcca38c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerPerfTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerPerfTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -35,15 +37,13 @@ import org.apache.activemq.artemis.core.postoffice.impl.BindingsImpl; import org.apache.activemq.artemis.core.postoffice.impl.WildcardAddressManager; import org.apache.activemq.artemis.core.server.Bindable; import org.apache.activemq.artemis.core.server.RoutingContext; -import org.junit.Ignore; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class WildcardAddressManagerPerfTest { @Test - @Ignore + @Disabled public void testConcurrencyAndEfficiency() throws Exception { System.out.println("Type so we can go on.."); @@ -104,7 +104,7 @@ public class WildcardAddressManagerPerfTest { } executorService.shutdown(); - assertTrue("finished on time", executorService.awaitTermination(10, TimeUnit.MINUTES)); + assertTrue(executorService.awaitTermination(10, TimeUnit.MINUTES), "finished on time"); final AtomicLong addresses = new AtomicLong(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java index e967a047dd..66d8745191 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/WildcardAddressManagerUnitTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.postoffice.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +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 java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; @@ -41,11 +46,11 @@ import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.apache.activemq.artemis.core.server.impl.AddressInfo; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; + import java.util.function.BiConsumer; /** @@ -81,7 +86,7 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { e.printStackTrace(); } - assertEquals("Exception happened during the process", 0, errors); + assertEquals(0, errors, "Exception happened during the process"); } @Test @@ -111,7 +116,7 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { e.printStackTrace(); } - assertEquals("Exception happened during the process", 0, errors); + assertEquals(0, errors, "Exception happened during the process"); } /** @@ -143,7 +148,7 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { ad.addAddressInfo(new AddressInfo(SimpleString.toSimpleString("Queue1.#"), RoutingType.ANYCAST)); BindingFake bindingFake = new BindingFake("Queue1.#", "one"); - Assert.assertTrue(ad.addBinding(bindingFake)); + assertTrue(ad.addBinding(bindingFake)); assertEquals(1, ad.getBindingsForRoutingAddress(address).getBindings().size()); @@ -154,12 +159,14 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { } - @Test(expected = ActiveMQQueueExistsException.class) + @Test public void testWildCardAddAlreadyExistingBindingShouldThrowException() throws Exception { - WildcardAddressManager ad = new WildcardAddressManager(new BindingFactoryFake(), null, null); - ad.addAddressInfo(new AddressInfo(SimpleString.toSimpleString("Queue1.#"), RoutingType.ANYCAST)); - ad.addBinding(new BindingFake("Queue1.#", "one")); - ad.addBinding(new BindingFake("Queue1.#", "one")); + assertThrows(ActiveMQQueueExistsException.class, () -> { + WildcardAddressManager ad = new WildcardAddressManager(new BindingFactoryFake(), null, null); + ad.addAddressInfo(new AddressInfo(SimpleString.toSimpleString("Queue1.#"), RoutingType.ANYCAST)); + ad.addBinding(new BindingFake("Queue1.#", "one")); + ad.addBinding(new BindingFake("Queue1.#", "one")); + }); } @Test @@ -369,8 +376,8 @@ public class WildcardAddressManagerUnitTest extends ActiveMQTestBase { } executorService.shutdown(); - assertTrue("finished on time", executorService.awaitTermination(10, TimeUnit.MINUTES)); - assertNull("no exceptions", oops.get()); + assertTrue(executorService.awaitTermination(10, TimeUnit.MINUTES), "finished on time"); + assertNull(oops.get(), "no exceptions"); } static class BindingFactoryFake implements BindingsFactory { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/AcceptorsTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/AcceptorsTest.java index 6889393eae..1b3c124105 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/AcceptorsTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/AcceptorsTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -26,7 +28,7 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.unit.core.remoting.server.impl.fake.FakeAcceptorFactory; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AcceptorsTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java index 78ea231e1a..7be76d5822 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/ActiveMQBufferTestBase.java @@ -16,14 +16,19 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.After; -import org.junit.Assert; -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; public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { @@ -31,7 +36,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { private ActiveMQBuffer wrapper; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -39,7 +44,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { wrapper = null; @@ -50,15 +55,15 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { @Test public void testNullString() throws Exception { - Assert.assertNull(putAndGetNullableString(null)); + assertNull(putAndGetNullableString(null)); } @Test public void testEmptyString() throws Exception { String result = putAndGetNullableString(""); - Assert.assertNotNull(result); - Assert.assertEquals("", result); + assertNotNull(result); + assertEquals("", result); } @Test @@ -67,13 +72,13 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { String result = putAndGetNullableString(junk); - Assert.assertNotNull(result); - Assert.assertEquals(junk, result); + assertNotNull(result); + assertEquals(junk, result); } @Test public void testNullSimpleString() throws Exception { - Assert.assertNull(putAndGetNullableSimpleString(null)); + assertNull(putAndGetNullableSimpleString(null)); } @Test @@ -81,7 +86,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { SimpleString emptySimpleString = new SimpleString(""); SimpleString result = putAndGetNullableSimpleString(emptySimpleString); - Assert.assertNotNull(result); + assertNotNull(result); ActiveMQTestBase.assertEqualsByteArrays(emptySimpleString.getData(), result.getData()); } @@ -90,7 +95,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { SimpleString junk = RandomUtil.randomSimpleString(); SimpleString result = putAndGetNullableSimpleString(junk); - Assert.assertNotNull(result); + assertNotNull(result); ActiveMQTestBase.assertEqualsByteArrays(junk.getData(), result.getData()); } @@ -99,7 +104,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { byte b = RandomUtil.randomByte(); wrapper.writeByte(b); - Assert.assertEquals(b, wrapper.readByte()); + assertEquals(b, wrapper.readByte()); } @Test @@ -107,12 +112,12 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { byte b = (byte) 0xff; wrapper.writeByte(b); - Assert.assertEquals(255, wrapper.readUnsignedByte()); + assertEquals(255, wrapper.readUnsignedByte()); b = (byte) 0xf; wrapper.writeByte(b); - Assert.assertEquals(b, wrapper.readUnsignedByte()); + assertEquals(b, wrapper.readUnsignedByte()); } @Test @@ -140,42 +145,42 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { public void testPutTrueBoolean() throws Exception { wrapper.writeBoolean(true); - Assert.assertTrue(wrapper.readBoolean()); + assertTrue(wrapper.readBoolean()); } @Test public void testPutFalseBoolean() throws Exception { wrapper.writeBoolean(false); - Assert.assertFalse(wrapper.readBoolean()); + assertFalse(wrapper.readBoolean()); } @Test public void testPutNullableTrueBoolean() throws Exception { wrapper.writeNullableBoolean(true); - Assert.assertTrue(wrapper.readNullableBoolean()); + assertTrue(wrapper.readNullableBoolean()); } @Test public void testPutNullableFalseBoolean() throws Exception { wrapper.writeNullableBoolean(false); - Assert.assertFalse(wrapper.readNullableBoolean()); + assertFalse(wrapper.readNullableBoolean()); } @Test public void testNullBoolean() throws Exception { wrapper.writeNullableBoolean(null); - Assert.assertNull(wrapper.readNullableBoolean()); + assertNull(wrapper.readNullableBoolean()); } @Test public void testChar() throws Exception { wrapper.writeChar('a'); - Assert.assertEquals('a', wrapper.readChar()); + assertEquals('a', wrapper.readChar()); } @Test @@ -183,7 +188,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { int i = RandomUtil.randomInt(); wrapper.writeInt(i); - Assert.assertEquals(i, wrapper.readInt()); + assertEquals(i, wrapper.readInt()); } @Test @@ -196,8 +201,8 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { // rewrite firstInt at the beginning wrapper.setInt(0, firstInt); - Assert.assertEquals(firstInt, wrapper.readInt()); - Assert.assertEquals(secondInt, wrapper.readInt()); + assertEquals(firstInt, wrapper.readInt()); + assertEquals(secondInt, wrapper.readInt()); } @Test @@ -205,7 +210,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { long l = RandomUtil.randomLong(); wrapper.writeLong(l); - Assert.assertEquals(l, wrapper.readLong()); + assertEquals(l, wrapper.readLong()); } @Test @@ -213,14 +218,14 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { Long l = RandomUtil.randomLong(); wrapper.writeNullableLong(l); - Assert.assertEquals(l, wrapper.readNullableLong()); + assertEquals(l, wrapper.readNullableLong()); } @Test public void testNullLong() throws Exception { wrapper.writeNullableLong(null); - Assert.assertNull(wrapper.readNullableLong()); + assertNull(wrapper.readNullableLong()); } @Test @@ -231,7 +236,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { int s2 = wrapper.readUnsignedShort(); - Assert.assertEquals(s1, s2); + assertEquals(s1, s2); s1 = Short.MIN_VALUE; @@ -239,7 +244,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { s2 = wrapper.readUnsignedShort(); - Assert.assertEquals(s1 * -1, s2); + assertEquals(s1 * -1, s2); s1 = -1; @@ -249,14 +254,14 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { // / The max of an unsigned short // (http://en.wikipedia.org/wiki/Unsigned_short) - Assert.assertEquals(s2, 65535); + assertEquals(s2, 65535); } @Test public void testShort() throws Exception { wrapper.writeShort((short) 1); - Assert.assertEquals((short) 1, wrapper.readShort()); + assertEquals((short) 1, wrapper.readShort()); } @Test @@ -264,7 +269,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { double d = RandomUtil.randomDouble(); wrapper.writeDouble(d); - Assert.assertEquals(d, wrapper.readDouble(), 0.000001); + assertEquals(d, wrapper.readDouble(), 0.000001); } @Test @@ -272,7 +277,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { float f = RandomUtil.randomFloat(); wrapper.writeFloat(f); - Assert.assertEquals(f, wrapper.readFloat(), 0.000001); + assertEquals(f, wrapper.readFloat(), 0.000001); } @Test @@ -280,7 +285,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { String str = RandomUtil.randomString(); wrapper.writeUTF(str); - Assert.assertEquals(str, wrapper.readUTF()); + assertEquals(str, wrapper.readUTF()); } @Test @@ -289,7 +294,7 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { wrapper.writeBytes(bytes); byte[] array = wrapper.toByteBuffer().array(); - Assert.assertEquals(wrapper.capacity(), array.length); + assertEquals(wrapper.capacity(), array.length); ActiveMQTestBase.assertEqualsByteArrays(128, bytes, wrapper.toByteBuffer().array()); } @@ -298,11 +303,11 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { int i = RandomUtil.randomInt(); wrapper.writeInt(i); - Assert.assertEquals(i, wrapper.readInt()); + assertEquals(i, wrapper.readInt()); wrapper.resetReaderIndex(); - Assert.assertEquals(i, wrapper.readInt()); + assertEquals(i, wrapper.readInt()); } @Test @@ -315,20 +320,20 @@ public abstract class ActiveMQBufferTestBase extends ActiveMQTestBase { wrapper.writeBytes(bytes); // check the remaining is 2/3 - Assert.assertEquals(capacity - fill, wrapper.writableBytes()); + assertEquals(capacity - fill, wrapper.writableBytes()); } @Test public void testPosition() throws Exception { - Assert.assertEquals(0, wrapper.writerIndex()); + assertEquals(0, wrapper.writerIndex()); byte[] bytes = RandomUtil.randomBytes(128); wrapper.writeBytes(bytes); - Assert.assertEquals(bytes.length, wrapper.writerIndex()); + assertEquals(bytes.length, wrapper.writerIndex()); wrapper.writerIndex(0); - Assert.assertEquals(0, wrapper.writerIndex()); + assertEquals(0, wrapper.writerIndex()); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectionTest.java index e19b915390..dc71038968 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectionTest.java @@ -16,18 +16,18 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.invm; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnection; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory; import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class InVMConnectionTest { @Test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java index 0e4e18198a..a3d8275384 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/invm/InVMConnectorFactoryTest.java @@ -16,15 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.invm; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnector; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class InVMConnectorFactoryTest { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java index 4a99ef092a..b2c6846f0e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorFactoryTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; @@ -33,8 +35,7 @@ import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.spi.core.remoting.ServerConnectionLifeCycleListener; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class NettyAcceptorFactoryTest extends ActiveMQTestBase { @@ -74,6 +75,6 @@ public class NettyAcceptorFactoryTest extends ActiveMQTestBase { Acceptor acceptor = factory.createAcceptor("netty", null, params, handler, listener, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), new HashMap()); - Assert.assertTrue(acceptor instanceof NettyAcceptor); + assertTrue(acceptor instanceof NettyAcceptor); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java index 29267a3754..25e9ce731f 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyAcceptorTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -33,15 +37,14 @@ import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.spi.core.remoting.ServerConnectionLifeCycleListener; +import org.apache.activemq.artemis.tests.extensions.PortCheckExtension; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -import org.apache.activemq.artemis.utils.PortCheckRule; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.Wait; -import org.junit.After; -import org.junit.Assert; -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; public class NettyAcceptorTest extends ActiveMQTestBase { @@ -49,13 +52,13 @@ public class NettyAcceptorTest extends ActiveMQTestBase { private ExecutorService pool3; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); } @Override - @After + @AfterEach public void tearDown() throws Exception { if (pool3 != null) pool3.shutdown(); @@ -102,16 +105,16 @@ public class NettyAcceptorTest extends ActiveMQTestBase { addActiveMQComponent(acceptor); acceptor.start(); - Assert.assertTrue(acceptor.isStarted()); + assertTrue(acceptor.isStarted()); acceptor.stop(); - Assert.assertFalse(acceptor.isStarted()); - Assert.assertTrue(PortCheckRule.checkAvailable(TransportConstants.DEFAULT_PORT)); + assertFalse(acceptor.isStarted()); + assertTrue(PortCheckExtension.checkAvailable(TransportConstants.DEFAULT_PORT)); acceptor.start(); - Assert.assertTrue(acceptor.isStarted()); + assertTrue(acceptor.isStarted()); acceptor.stop(); - Assert.assertFalse(acceptor.isStarted()); - Assert.assertTrue(PortCheckRule.checkAvailable(TransportConstants.DEFAULT_PORT)); + assertFalse(acceptor.isStarted()); + assertTrue(PortCheckExtension.checkAvailable(TransportConstants.DEFAULT_PORT)); } @Test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java index 3c27719f26..dc9c875ae4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectionTest.java @@ -16,6 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +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 java.nio.ByteBuffer; import java.util.Collections; import java.util.HashMap; @@ -36,8 +41,7 @@ import org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleLi import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class NettyConnectionTest extends ActiveMQTestBase { @@ -48,7 +52,7 @@ public class NettyConnectionTest extends ActiveMQTestBase { Channel channel = createChannel(); NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); - Assert.assertEquals(channel.id(), conn.getID()); + assertEquals(channel.id(), conn.getID()); } @Test @@ -56,12 +60,12 @@ public class NettyConnectionTest extends ActiveMQTestBase { ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(128)); EmbeddedChannel channel = createChannel(); - Assert.assertEquals(0, channel.outboundMessages().size()); + assertEquals(0, channel.outboundMessages().size()); NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); conn.write(buff); channel.runPendingTasks(); - Assert.assertEquals(1, channel.outboundMessages().size()); + assertEquals(1, channel.outboundMessages().size()); } @Test @@ -73,18 +77,20 @@ public class NettyConnectionTest extends ActiveMQTestBase { ActiveMQBuffer buff = conn.createTransportBuffer(size); buff.writeByte((byte) 0x00); // Netty buffer does lazy initialization. - Assert.assertEquals(size, buff.capacity()); + assertEquals(size, buff.capacity()); } - @Test(expected = IllegalStateException.class) + @Test public void throwsExceptionOnBlockUntilWritableIfClosed() { - EmbeddedChannel channel = createChannel(); - NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); - conn.close(); - //to make sure the channel is closed it needs to run the pending tasks - channel.runPendingTasks(); - conn.blockUntilWritable(0, TimeUnit.NANOSECONDS); + assertThrows(IllegalStateException.class, () -> { + EmbeddedChannel channel = createChannel(); + NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false); + conn.close(); + //to make sure the channel is closed it needs to run the pending tasks + channel.runPendingTasks(); + conn.blockUntilWritable(0, TimeUnit.NANOSECONDS); + }); } @Test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java index e4c7cd7fa6..34f3f3cde4 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorFactoryTest.java @@ -16,15 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class NettyConnectorFactoryTest { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java index fcc918b85b..e85dd80efb 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyConnectorTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -41,9 +47,9 @@ import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; import org.apache.activemq.artemis.utils.SensitiveDataCodec; -import org.junit.Assert; -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; /** * See the tests/security-resources/build.sh script for details on the security resources used. @@ -54,7 +60,7 @@ public class NettyConnectorTest extends ActiveMQTestBase { private ExecutorService executorService; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); executorService = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())); @@ -73,6 +79,7 @@ public class NettyConnectorTest extends ActiveMQTestBase { waitForServerToStart(server); } + @AfterEach @Override public void tearDown() throws Exception { executorService.shutdown(); @@ -111,9 +118,9 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -128,7 +135,7 @@ public class NettyConnectorTest extends ActiveMQTestBase { try { new NettyConnector(params, null, listener, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); - Assert.fail("Should throw Exception"); + fail("Should throw Exception"); } catch (IllegalArgumentException e) { // Ok } @@ -136,7 +143,7 @@ public class NettyConnectorTest extends ActiveMQTestBase { try { new NettyConnector(params, handler, null, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); - Assert.fail("Should throw Exception"); + fail("Should throw Exception"); } catch (IllegalArgumentException e) { // Ok } @@ -165,12 +172,12 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); c.close(); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @@ -198,12 +205,12 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); c.close(); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @@ -231,10 +238,10 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); - Assert.assertNull(connector.createConnection()); + assertTrue(connector.isStarted()); + assertNull(connector.createConnection()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @@ -262,13 +269,13 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); //Should have failed because SSL props override transport config options assertNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -295,14 +302,14 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); //Should not fail because SSL props override transport config options assertNotNull(c); c.close(); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -330,14 +337,14 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); //Should not fail because forceSSLParameters is set assertNotNull(c); c.close(); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -363,7 +370,7 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, executorService, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = null; try { @@ -394,11 +401,11 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, "securepass"); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -421,11 +428,11 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, PasswordMaskingUtil.wrap(codec.encode("securepass"))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -448,10 +455,10 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, PasswordMaskingUtil.wrap(codec.encode("bad password"))); connector.start(); - Assert.assertTrue(connector.isStarted()); - Assert.assertNull(connector.createConnection()); + assertTrue(connector.isStarted()); + assertNull(connector.createConnection()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } public static class NettyConnectorTestPasswordCodec implements SensitiveDataCodec { @@ -497,11 +504,11 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, PasswordMaskingUtil.wrap(codec.encode("securepass"))); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -523,11 +530,11 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, "securepass"); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -551,10 +558,10 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME, PasswordMaskingUtil.wrap(codec.encode("securepass"))); connector.start(); - Assert.assertTrue(connector.isStarted()); - Assert.assertNull(connector.createConnection()); + assertTrue(connector.isStarted()); + assertNull(connector.createConnection()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -580,11 +587,11 @@ public class NettyConnectorTest extends ActiveMQTestBase { System.setProperty(NettyConnector.JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME, "bad password"); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); Connection c = connector.createConnection(); assertNotNull(c); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -601,10 +608,10 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); - Assert.assertNull(connector.createConnection()); + assertTrue(connector.isStarted()); + assertNull(connector.createConnection()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -621,10 +628,10 @@ public class NettyConnectorTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())), Executors.newScheduledThreadPool(5, ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()))); connector.start(); - Assert.assertTrue(connector.isStarted()); - Assert.assertNull(connector.createConnection()); + assertTrue(connector.isStarted()); + assertNull(connector.createConnection()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -640,14 +647,14 @@ public class NettyConnectorTest extends ActiveMQTestBase { connector.start(); final Connection connection = connector.createConnection(future -> { future.awaitUninterruptibly(); - Assert.assertTrue(future.isSuccess()); + assertTrue(future.isSuccess()); final ChannelPipeline pipeline = future.channel().pipeline(); final ActiveMQChannelHandler activeMQChannelHandler = pipeline.get(ActiveMQChannelHandler.class); - Assert.assertNotNull(activeMQChannelHandler); + assertNotNull(activeMQChannelHandler); pipeline.remove(activeMQChannelHandler); - Assert.assertNull(pipeline.get(ActiveMQChannelHandler.class)); + assertNull(pipeline.get(ActiveMQChannelHandler.class)); }); - Assert.assertNull(connection); + assertNull(connection); connector.close(); } finally { closeExecutor.shutdownNow(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyHandshakeTimeoutTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyHandshakeTimeoutTest.java index 4f6ecadf9a..56ab1f8d49 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyHandshakeTimeoutTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/NettyHandshakeTimeoutTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.URI; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -31,7 +33,7 @@ import org.apache.activemq.artemis.utils.Wait; import org.apache.activemq.transport.netty.NettyTransport; import org.apache.activemq.transport.netty.NettyTransportFactory; import org.apache.activemq.transport.netty.NettyTransportListener; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class NettyHandshakeTimeoutTest extends ActiveMQTestBase { @@ -67,7 +69,7 @@ public class NettyHandshakeTimeoutTest extends ActiveMQTestBase { try { transport.connect(); - assertTrue("Connection should be closed now", Wait.waitFor(() -> !transport.isConnected(), TimeUnit.SECONDS.toMillis(handshakeTimeout + 10))); + assertTrue(Wait.waitFor(() -> !transport.isConnected(), TimeUnit.SECONDS.toMillis(handshakeTimeout + 10)), "Connection should be closed now"); } finally { transport.close(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/SocksProxyTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/SocksProxyTest.java index 2e7cd0d819..afb14ace36 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/SocksProxyTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/netty/SocksProxyTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty; +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.junit.jupiter.api.Assumptions.assumeTrue; + import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; @@ -47,11 +54,9 @@ import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -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; public class SocksProxyTest extends ActiveMQTestBase { @@ -65,7 +70,7 @@ public class SocksProxyTest extends ActiveMQTestBase { private NioEventLoopGroup workerGroup; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -77,7 +82,7 @@ public class SocksProxyTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { closeExecutor.shutdownNow(); threadPool.shutdownNow(); @@ -91,7 +96,7 @@ public class SocksProxyTest extends ActiveMQTestBase { @Test public void testSocksProxyHandlerAdded() throws Exception { InetAddress address = getNonLoopbackAddress(); - Assume.assumeTrue("Cannot find non-loopback address", address != null); + assumeTrue(address != null, "Cannot find non-loopback address"); BufferHandler handler = (connectionID, buffer) -> { }; @@ -124,13 +129,13 @@ public class SocksProxyTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, closeExecutor, threadPool, scheduledThreadPool); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); ChannelPipeline pipeline = connector.getBootStrap().register().await().channel().pipeline(); - Assert.assertNotNull(pipeline.get(Socks5ProxyHandler.class)); + assertNotNull(pipeline.get(Socks5ProxyHandler.class)); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } private InetAddress getNonLoopbackAddress() throws SocketException { @@ -187,13 +192,13 @@ public class SocksProxyTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, closeExecutor, threadPool, scheduledThreadPool); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); ChannelPipeline pipeline = connector.getBootStrap().register().await().channel().pipeline(); - Assert.assertNull(pipeline.get(Socks5ProxyHandler.class)); + assertNull(pipeline.get(Socks5ProxyHandler.class)); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } @Test @@ -231,31 +236,31 @@ public class SocksProxyTest extends ActiveMQTestBase { NettyConnector connector = new NettyConnector(params, handler, listener, closeExecutor, threadPool, scheduledThreadPool); connector.start(); - Assert.assertTrue(connector.isStarted()); + assertTrue(connector.isStarted()); connector.getBootStrap().register().await().channel().pipeline(); AddressResolverGroup resolver = connector.getBootStrap().config().resolver(); - Assert.assertSame(resolver, NoopAddressResolverGroup.INSTANCE); + assertSame(resolver, NoopAddressResolverGroup.INSTANCE); Connection connection = connector.createConnection(future -> { future.awaitUninterruptibly(); - Assert.assertTrue(future.isSuccess()); + assertTrue(future.isSuccess()); Socks5ProxyHandler socks5Handler = future.channel().pipeline().get(Socks5ProxyHandler.class); - Assert.assertNotNull(socks5Handler); + assertNotNull(socks5Handler); InetSocketAddress remoteAddress = (InetSocketAddress)socks5Handler.destinationAddress(); - Assert.assertTrue(remoteAddress.isUnresolved()); + assertTrue(remoteAddress.isUnresolved()); }); - Assert.assertNotNull(connection); + assertNotNull(connection); - Assert.assertTrue(connection.isOpen()); + assertTrue(connection.isOpen()); connection.close(); - Assert.assertFalse(connection.isOpen()); + assertFalse(connection.isOpen()); connector.close(); - Assert.assertFalse(connector.isStarted()); + assertFalse(connector.isStarted()); } private void startSocksProxy() throws Exception { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java index 7ac846a9fe..d44f02ff28 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java @@ -16,6 +16,9 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.impl.ssl; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.net.URL; import java.util.Arrays; @@ -23,20 +26,20 @@ import java.util.Collection; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.remoting.impl.ssl.SSLSupport; +import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension; +import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; /** * See the tests/security-resources/build.sh script for details on the security resources used. */ -@RunWith(value = Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SSLSupportTest extends ActiveMQTestBase { - @Parameterized.Parameters(name = "storeProvider={0}, storeType={1}") + @Parameters(name = "storeProvider={0}, storeType={1}") public static Collection getParameters() { if (System.getProperty("java.vendor").contains("IBM")) { return Arrays.asList(new Object[][]{ @@ -80,14 +83,14 @@ public class SSLSupportTest extends ActiveMQTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); keyStorePassword = "securepass"; trustStorePassword = keyStorePassword; } - @Test + @TestTemplate public void testContextWithRightParameters() throws Exception { new SSLSupport() .setKeystoreProvider(storeProvider) @@ -102,12 +105,12 @@ public class SSLSupportTest extends ActiveMQTestBase { } // This is valid as it will create key and trust managers with system defaults - @Test + @TestTemplate public void testContextWithNullParameters() throws Exception { new SSLSupport().createContext(); } - @Test + @TestTemplate public void testContextWithKeyStorePathAsURL() throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource(keyStorePath); new SSLSupport() @@ -122,7 +125,7 @@ public class SSLSupportTest extends ActiveMQTestBase { .createContext(); } - @Test + @TestTemplate public void testContextWithKeyStorePathAsFile() throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource(keyStorePath); File file = new File(url.toURI()); @@ -138,7 +141,7 @@ public class SSLSupportTest extends ActiveMQTestBase { .createContext(); } - @Test + @TestTemplate public void testContextWithBadKeyStorePath() throws Exception { try { new SSLSupport() @@ -151,12 +154,12 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePath(trustStorePath) .setTruststorePassword(trustStorePassword) .createContext(); - Assert.fail(); + fail(); } catch (Exception e) { } } - @Test + @TestTemplate public void testContextWithNullKeyStorePath() throws Exception { try { new SSLSupport() @@ -170,11 +173,11 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePassword(trustStorePassword) .createContext(); } catch (Exception e) { - Assert.fail(); + fail(); } } - @Test + @TestTemplate public void testContextWithKeyStorePathAsRelativePath() throws Exception { // this test is dependent on a path relative to the tests directory. // it will fail if launch from somewhere else (or from an IDE) @@ -195,7 +198,7 @@ public class SSLSupportTest extends ActiveMQTestBase { .createContext(); } - @Test + @TestTemplate public void testContextWithBadKeyStorePassword() throws Exception { try { new SSLSupport() @@ -208,12 +211,12 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePath(trustStorePath) .setTruststorePassword(trustStorePassword) .createContext(); - Assert.fail(); + fail(); } catch (Exception e) { } } - @Test + @TestTemplate public void testContextWithNullKeyStorePassword() throws Exception { try { new SSLSupport() @@ -226,13 +229,13 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePath(trustStorePath) .setTruststorePassword(trustStorePassword) .createContext(); - Assert.fail(); + fail(); } catch (Exception e) { assertFalse(e instanceof NullPointerException); } } - @Test + @TestTemplate public void testContextWithBadTrustStorePath() throws Exception { try { new SSLSupport() @@ -245,12 +248,12 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePath("not a trust store") .setTruststorePassword(trustStorePassword) .createContext(); - Assert.fail(); + fail(); } catch (Exception e) { } } - @Test + @TestTemplate public void testContextWithBadTrustStorePassword() throws Exception { try { new SSLSupport() @@ -263,12 +266,12 @@ public class SSLSupportTest extends ActiveMQTestBase { .setTruststorePath(trustStorePath) .setTruststorePassword("bad passord") .createContext(); - Assert.fail(); + fail(); } catch (Exception e) { } } - @Test + @TestTemplate public void testContextWithTrustAll() throws Exception { //This is using a bad password but should not fail because the trust store should be ignored with //the trustAll flag set to true diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java index 37a2b940b4..d6be8fcbe9 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/remoting/server/impl/RemotingServiceImplTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.unit.core.remoting.server.impl; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -29,10 +31,8 @@ import org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl import org.apache.activemq.artemis.core.server.ServiceRegistry; import org.apache.activemq.artemis.core.server.impl.ServiceRegistryImpl; import org.apache.activemq.artemis.tests.unit.core.remoting.server.impl.fake.FakeInterceptor; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class RemotingServiceImplTest { @@ -42,7 +42,7 @@ public class RemotingServiceImplTest { private Configuration configuration; - @Before + @BeforeEach public void setUp() throws Exception { serviceRegistry = new ServiceRegistryImpl(); configuration = new ConfigurationImpl(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java index c0b9d12f61..b4bb07d5b8 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/security/impl/ActiveMQSecurityManagerImplTest.java @@ -16,16 +16,19 @@ */ package org.apache.activemq.artemis.tests.unit.core.security.impl; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.HashSet; import org.apache.activemq.artemis.core.security.CheckType; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.After; -import org.junit.Assert; -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; /** * tests ActiveMQSecurityManagerImpl @@ -35,7 +38,7 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { private ActiveMQSecurityManagerImpl securityManager; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -43,7 +46,7 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { securityManager = null; @@ -55,46 +58,46 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { securityManager.getConfiguration().addUser("guest", "password"); securityManager.getConfiguration().addRole("guest", "guest"); securityManager.getConfiguration().setDefaultUser("guest"); - Assert.assertTrue(securityManager.validateUser(null, null)); - Assert.assertTrue(securityManager.validateUser("guest", "password")); - Assert.assertFalse(securityManager.validateUser(null, "wrongpass")); + assertTrue(securityManager.validateUser(null, null)); + assertTrue(securityManager.validateUser("guest", "password")); + assertFalse(securityManager.validateUser(null, "wrongpass")); HashSet roles = new HashSet<>(); roles.add(new Role("guest", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); roles = new HashSet<>(); roles.add(new Role("guest", true, true, false, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); roles = new HashSet<>(); roles.add(new Role("guest", true, false, false, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); - Assert.assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); + assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); roles = new HashSet<>(); roles.add(new Role("guest", false, false, false, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); - Assert.assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE_DURABLE_QUEUE)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CONSUME)); } @Test public void testAddingUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); - Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); - Assert.assertFalse(securityManager.validateUser("newuser1", "guest")); - Assert.assertFalse(securityManager.validateUser("newuser1", null)); + assertTrue(securityManager.validateUser("newuser1", "newpassword1")); + assertFalse(securityManager.validateUser("newuser1", "guest")); + assertFalse(securityManager.validateUser("newuser1", null)); try { securityManager.getConfiguration().addUser("newuser2", null); - Assert.fail("password cannot be null"); + fail("password cannot be null"); } catch (IllegalArgumentException e) { // pass } try { securityManager.getConfiguration().addUser(null, "newpassword2"); - Assert.fail("password cannot be null"); + fail("password cannot be null"); } catch (IllegalArgumentException e) { // pass } @@ -103,17 +106,17 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { @Test public void testRemovingUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); - Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); + assertTrue(securityManager.validateUser("newuser1", "newpassword1")); securityManager.getConfiguration().removeUser("newuser1"); - Assert.assertFalse(securityManager.validateUser("newuser1", "newpassword1")); + assertFalse(securityManager.validateUser("newuser1", "newpassword1")); } @Test public void testRemovingInvalidUsers() { securityManager.getConfiguration().addUser("newuser1", "newpassword1"); - Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); + assertTrue(securityManager.validateUser("newuser1", "newpassword1")); securityManager.getConfiguration().removeUser("nonuser"); - Assert.assertTrue(securityManager.validateUser("newuser1", "newpassword1")); + assertTrue(securityManager.validateUser("newuser1", "newpassword1")); } @Test @@ -125,19 +128,19 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { securityManager.getConfiguration().addRole("newuser1", "role4"); HashSet roles = new HashSet<>(); roles.add(new Role("role1", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role2", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role3", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role4", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role5", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); } @Test @@ -151,18 +154,18 @@ public class ActiveMQSecurityManagerImplTest extends ActiveMQTestBase { securityManager.getConfiguration().removeRole("newuser1", "role4"); HashSet roles = new HashSet<>(); roles.add(new Role("role1", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role2", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role3", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role4", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); roles = new HashSet<>(); roles.add(new Role("role5", true, true, true, true, true, true, true, true, true, true, false, false)); - Assert.assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); + assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.SEND)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java index c0114c6bc9..ae307f3b9d 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/ClusterConnectionBridgeTest.java @@ -16,10 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.core.server.cluster.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.management.ManagementHelper; import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionBridge; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ClusterConnectionBridgeTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java index 743efe4d85..84ca9f58e6 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/cluster/impl/RemoteQueueBindImplTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.core.server.cluster.impl; +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.ArrayList; import java.util.List; import java.util.function.IntFunction; @@ -27,7 +31,7 @@ import org.apache.activemq.artemis.core.server.cluster.impl.RemoteQueueBindingIm import org.apache.activemq.artemis.tests.unit.core.postoffice.impl.fakes.FakeQueue; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RemoteQueueBindImplTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/group/impl/SystemPropertyOverrideTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/group/impl/SystemPropertyOverrideTest.java index 5a002cc7d4..a23a185cf9 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/group/impl/SystemPropertyOverrideTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/group/impl/SystemPropertyOverrideTest.java @@ -16,15 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.core.server.group.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.group.impl.GroupingHandlerConfiguration; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SystemPropertyOverrideTest extends ActiveMQTestBase { - - @Test public void testSystemPropertyOverride() throws Exception { final String groupTimeoutPropertyValue = "1234"; diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/FileLockTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/FileLockTest.java index ac67c5cf73..dc17859657 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/FileLockTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/FileLockTest.java @@ -29,16 +29,21 @@ import org.apache.activemq.artemis.core.server.impl.FileLockNodeManager; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static java.util.stream.Collectors.toSet; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FileLockTest extends ActiveMQTestBase { @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); File file = new File(getTestDir()); @@ -72,20 +77,20 @@ public class FileLockTest extends ActiveMQTestBase { Set files = Arrays.stream(managerDirectory.listFiles(pathname -> pathname.isFile())).collect(toSet()); final Set expectedFileNames = Arrays.stream(new String[]{FileLockNodeManager.SERVER_LOCK_NAME, "serverlock.1", "serverlock.2"}) .collect(toSet()); - Assert.assertEquals(expectedFileNames, files.stream().map(File::getName).collect(toSet())); + assertEquals(expectedFileNames, files.stream().map(File::getName).collect(toSet())); final File nodeIdFile = files.stream().filter(file -> file.getName().equals(FileLockNodeManager.SERVER_LOCK_NAME)).findFirst().get(); final byte[] encodedNodeId = manager.getUUID().asBytes(); try (FileChannel serverLock = FileChannel.open(nodeIdFile.toPath(), StandardOpenOption.READ)) { - Assert.assertEquals(16, encodedNodeId.length); - Assert.assertEquals(19, serverLock.size()); + assertEquals(16, encodedNodeId.length); + assertEquals(19, serverLock.size()); final ByteBuffer readNodeId = ByteBuffer.allocate(16); serverLock.read(readNodeId, 3); readNodeId.flip(); - Assert.assertArrayEquals(encodedNodeId, readNodeId.array()); + assertArrayEquals(encodedNodeId, readNodeId.array()); } - Assert.assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.getNodeActivationSequence()); - Assert.assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.readNodeActivationSequence()); - Assert.assertEquals(3, managerDirectory.listFiles(pathname -> pathname.isFile()).length); + assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.getNodeActivationSequence()); + assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.readNodeActivationSequence()); + assertEquals(3, managerDirectory.listFiles(pathname -> pathname.isFile()).length); manager.stop(); } @@ -95,12 +100,12 @@ public class FileLockTest extends ActiveMQTestBase { FileLockNodeManager manager = new FileLockNodeManager(managerDirectory, true); manager.start(); Set files = Arrays.stream(managerDirectory.listFiles(pathname -> pathname.isFile())).collect(toSet()); - Assert.assertTrue(files.isEmpty()); - Assert.assertNull(manager.getNodeId()); - Assert.assertNull(manager.getUUID()); - Assert.assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.getNodeActivationSequence()); - Assert.assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.readNodeActivationSequence()); - Assert.assertEquals(0, managerDirectory.listFiles(pathname -> pathname.isFile()).length); + assertTrue(files.isEmpty()); + assertNull(manager.getNodeId()); + assertNull(manager.getUUID()); + assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.getNodeActivationSequence()); + assertEquals(NodeManager.NULL_NODE_ACTIVATION_SEQUENCE, manager.readNodeActivationSequence()); + assertEquals(0, managerDirectory.listFiles(pathname -> pathname.isFile()).length); manager.stop(); } @@ -108,16 +113,16 @@ public class FileLockTest extends ActiveMQTestBase { public void testReplicatedStopBackupPersistence() throws Exception { final FileLockNodeManager manager = new FileLockNodeManager(getTestDirfile(), false); manager.start(); - Assert.assertNotNull(manager.getUUID()); + assertNotNull(manager.getUUID()); manager.writeNodeActivationSequence(1); final long nodeActivationSequence = manager.getNodeActivationSequence(); - Assert.assertEquals(1, nodeActivationSequence); + assertEquals(1, nodeActivationSequence); manager.stop(); // replicated manager read activation sequence (if any) but ignore NodeId final FileLockNodeManager replicatedManager = new FileLockNodeManager(getTestDirfile(), true); replicatedManager.start(); - Assert.assertNull(replicatedManager.getUUID()); - Assert.assertEquals(1, replicatedManager.getNodeActivationSequence()); + assertNull(replicatedManager.getUUID()); + assertEquals(1, replicatedManager.getNodeActivationSequence()); UUID storedNodeId = UUIDGenerator.getInstance().generateUUID(); replicatedManager.setNodeID(storedNodeId.toString()); replicatedManager.setNodeActivationSequence(2); @@ -127,8 +132,8 @@ public class FileLockTest extends ActiveMQTestBase { replicatedManager.stop(); // start read whatever has been persisted by stopBackup manager.start(); - Assert.assertEquals(storedNodeId, manager.getUUID()); - Assert.assertEquals(2, manager.getNodeActivationSequence()); + assertEquals(storedNodeId, manager.getUUID()); + assertEquals(2, manager.getNodeActivationSequence()); manager.stop(); } @@ -137,15 +142,15 @@ public class FileLockTest extends ActiveMQTestBase { final FileLockNodeManager manager = new FileLockNodeManager(getTestDirfile(), false); manager.start(); UUID id = manager.getUUID(); - Assert.assertNotNull(manager.getUUID()); + assertNotNull(manager.getUUID()); manager.writeNodeActivationSequence(1); final long nodeActivationSequence = manager.getNodeActivationSequence(); - Assert.assertEquals(1, nodeActivationSequence); + assertEquals(1, nodeActivationSequence); manager.stop(); final FileLockNodeManager otherManager = new FileLockNodeManager(getTestDirfile(), false); otherManager.start(); - Assert.assertEquals(id, otherManager.getUUID()); - Assert.assertEquals(1, otherManager.getNodeActivationSequence()); + assertEquals(id, otherManager.getUUID()); + assertEquals(1, otherManager.getNodeActivationSequence()); otherManager.stop(); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/QueueImplTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/QueueImplTest.java index f9c2bc74ac..10b9d79a66 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/QueueImplTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/server/impl/QueueImplTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.core.server.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; @@ -56,10 +62,9 @@ import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.FutureLatch; import org.apache.activemq.artemis.utils.actors.ArtemisExecutor; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; -import org.junit.After; -import org.junit.Assert; -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.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -76,7 +81,7 @@ public class QueueImplTest extends ActiveMQTestBase { private ActiveMQServer defaultServer; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); scheduledExecutor = Executors.newSingleThreadScheduledExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName())); @@ -86,7 +91,7 @@ public class QueueImplTest extends ActiveMQTestBase { } @Override - @After + @AfterEach public void tearDown() throws Exception { scheduledExecutor.shutdownNow(); executor.shutdownNow(); @@ -103,18 +108,18 @@ public class QueueImplTest extends ActiveMQTestBase { QueueImpl queue = getNamedQueue(name); - Assert.assertEquals(name, queue.getName()); + assertEquals(name, queue.getName()); } @Test public void testDurable() { QueueImpl queue = getNonDurableQueue(); - Assert.assertFalse(queue.isDurable()); + assertFalse(queue.isDurable()); queue = getDurableQueue(); - Assert.assertTrue(queue.isDurable()); + assertTrue(queue.isDurable()); } @Test @@ -127,15 +132,15 @@ public class QueueImplTest extends ActiveMQTestBase { QueueImpl queue = getTemporaryQueue(); - Assert.assertEquals(0, queue.getConsumerCount()); + assertEquals(0, queue.getConsumerCount()); queue.addConsumer(cons1); - Assert.assertEquals(1, queue.getConsumerCount()); + assertEquals(1, queue.getConsumerCount()); queue.removeConsumer(cons1); - Assert.assertEquals(0, queue.getConsumerCount()); + assertEquals(0, queue.getConsumerCount()); queue.addConsumer(cons1); @@ -143,23 +148,23 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addConsumer(cons3); - Assert.assertEquals(3, queue.getConsumerCount()); + assertEquals(3, queue.getConsumerCount()); queue.removeConsumer(new FakeConsumer()); - Assert.assertEquals(3, queue.getConsumerCount()); + assertEquals(3, queue.getConsumerCount()); queue.removeConsumer(cons1); - Assert.assertEquals(2, queue.getConsumerCount()); + assertEquals(2, queue.getConsumerCount()); queue.removeConsumer(cons2); - Assert.assertEquals(1, queue.getConsumerCount()); + assertEquals(1, queue.getConsumerCount()); queue.removeConsumer(cons3); - Assert.assertEquals(0, queue.getConsumerCount()); + assertEquals(0, queue.getConsumerCount()); queue.removeConsumer(cons3); } @@ -168,7 +173,7 @@ public class QueueImplTest extends ActiveMQTestBase { public void testGetFilter() { QueueImpl queue = getTemporaryQueue(); - Assert.assertNull(queue.getFilter()); + assertNull(queue.getFilter()); Filter filter = new Filter() { @Override @@ -194,7 +199,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue = getFilteredQueue(filter); - Assert.assertEquals(filter, queue.getFilter()); + assertEquals(filter, queue.getFilter()); } @@ -210,9 +215,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); } @@ -234,7 +239,7 @@ public class QueueImplTest extends ActiveMQTestBase { getRate.setAccessible(true); float rate = (float) getRate.invoke(queue, null); - Assert.assertTrue(rate <= 10.0f); + assertTrue(rate <= 10.0f); logger.debug("Rate: {}", rate); } @@ -254,25 +259,25 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); // Now add a consumer FakeConsumer consumer = new FakeConsumer(); queue.addConsumer(consumer); - Assert.assertTrue(consumer.getReferences().isEmpty()); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); + assertTrue(consumer.getReferences().isEmpty()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); queue.deliverNow(); assertRefListsIdenticalRefs(refs, consumer.getReferences()); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages, queue.getDeliveringCount()); } @Test @@ -297,25 +302,25 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); queue.deliverNow(); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); consumer.setStatusImmediate(HandleStatus.HANDLED); queue.deliverNow(); assertRefListsIdenticalRefs(refs, consumer.getReferences()); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(10, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(10, queue.getDeliveringCount()); } @Test @@ -340,16 +345,16 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); queue.deliverNow(); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); @@ -359,10 +364,10 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(20, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(20, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); consumer.setStatusImmediate(HandleStatus.HANDLED); @@ -377,9 +382,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); assertRefListsIdenticalRefs(refs, consumer.getReferences()); - Assert.assertEquals(30, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(30, queue.getDeliveringCount()); + assertEquals(30, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(30, queue.getDeliveringCount()); } @Test @@ -449,9 +454,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); FakeConsumer cons1 = new FakeConsumer(); @@ -459,9 +464,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages, queue.getDeliveringCount()); assertRefListsIdenticalRefs(refs, cons1.getReferences()); @@ -469,7 +474,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addConsumer(cons2); - Assert.assertEquals(2, queue.getConsumerCount()); + assertEquals(2, queue.getConsumerCount()); cons1.getReferences().clear(); @@ -490,13 +495,13 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages * 2, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages * 2, queue.getDeliveringCount()); + assertEquals(numMessages * 2, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages * 2, queue.getDeliveringCount()); - Assert.assertEquals(numMessages, cons1.getReferences().size()); + assertEquals(numMessages, cons1.getReferences().size()); - Assert.assertEquals(numMessages, cons2.getReferences().size()); + assertEquals(numMessages, cons2.getReferences().size()); cons1.getReferences().clear(); cons2.getReferences().clear(); @@ -510,7 +515,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addConsumer(cons3); - Assert.assertEquals(3, queue.getConsumerCount()); + assertEquals(3, queue.getConsumerCount()); for (int i = 0; i < 3 * numMessages; i++) { MessageReference ref = generateReference(queue, i); @@ -522,15 +527,15 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages * 3, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages * 3, queue.getDeliveringCount()); + assertEquals(numMessages * 3, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages * 3, queue.getDeliveringCount()); - Assert.assertEquals(numMessages, cons1.getReferences().size()); + assertEquals(numMessages, cons1.getReferences().size()); - Assert.assertEquals(numMessages, cons2.getReferences().size()); + assertEquals(numMessages, cons2.getReferences().size()); - Assert.assertEquals(numMessages, cons3.getReferences().size()); + assertEquals(numMessages, cons3.getReferences().size()); queue.removeConsumer(cons1); @@ -552,13 +557,13 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages * 2, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages * 2, queue.getDeliveringCount()); + assertEquals(numMessages * 2, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages * 2, queue.getDeliveringCount()); - Assert.assertEquals(numMessages, cons2.getReferences().size()); + assertEquals(numMessages, cons2.getReferences().size()); - Assert.assertEquals(numMessages, cons3.getReferences().size()); + assertEquals(numMessages, cons3.getReferences().size()); queue.removeConsumer(cons3); @@ -579,11 +584,11 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages, queue.getDeliveringCount()); - Assert.assertEquals(numMessages, cons2.getReferences().size()); + assertEquals(numMessages, cons2.getReferences().size()); } @@ -627,16 +632,16 @@ public class QueueImplTest extends ActiveMQTestBase { Thread.sleep(1); } - Assert.assertEquals(numMessages / 2, cons1.getReferences().size()); + assertEquals(numMessages / 2, cons1.getReferences().size()); - Assert.assertEquals(numMessages / 2, cons2.getReferences().size()); + assertEquals(numMessages / 2, cons2.getReferences().size()); for (int i = 0; i < numMessages; i++) { MessageReference ref; ref = i % 2 == 0 ? cons1.getReferences().get(i / 2) : cons2.getReferences().get(i / 2); - Assert.assertEquals(refs.get(i), ref); + assertEquals(refs.get(i), ref); } } @@ -670,10 +675,10 @@ public class QueueImplTest extends ActiveMQTestBase { // Should be in reverse order - Assert.assertEquals(refs.size(), receivedRefs.size()); + assertEquals(refs.size(), receivedRefs.size()); for (int i = 0; i < numMessages; i++) { - Assert.assertEquals(refs.get(i), receivedRefs.get(9 - i)); + assertEquals(refs.get(i), receivedRefs.get(9 - i)); } } @@ -713,7 +718,7 @@ public class QueueImplTest extends ActiveMQTestBase { refs.add(ref); } - Assert.assertEquals(numMessages, getMessageCount(queue)); + assertEquals(numMessages, getMessageCount(queue)); Iterator iterator = queue.iterator(); List list = new ArrayList<>(); @@ -758,13 +763,13 @@ public class QueueImplTest extends ActiveMQTestBase { refs.add(ref2); - Assert.assertEquals(2, getMessageCount(queue)); + assertEquals(2, getMessageCount(queue)); awaitExecution(); - Assert.assertEquals(1, consumer.getReferences().size()); + assertEquals(1, consumer.getReferences().size()); - Assert.assertEquals(1, queue.getDeliveringCount()); + assertEquals(1, queue.getDeliveringCount()); assertRefListsIdenticalRefs(refs, consumer.getReferences()); @@ -794,13 +799,13 @@ public class QueueImplTest extends ActiveMQTestBase { refs.add(ref4); - Assert.assertEquals(3, getMessageCount(queue)); + assertEquals(3, getMessageCount(queue)); awaitExecution(); - Assert.assertEquals(1, consumer.getReferences().size()); + assertEquals(1, consumer.getReferences().size()); - Assert.assertEquals(1, queue.getDeliveringCount()); + assertEquals(1, queue.getDeliveringCount()); assertRefListsIdenticalRefs(refs, consumer.getReferences()); } @@ -827,9 +832,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); queue.deliverNow(); @@ -840,7 +845,7 @@ public class QueueImplTest extends ActiveMQTestBase { List receeivedRefs = consumer.getReferences(); int currId = 0; for (MessageReference receeivedRef : receeivedRefs) { - Assert.assertEquals("messages received out of order", receeivedRef.getMessage().getMessageID(), currId++); + assertEquals(receeivedRef.getMessage().getMessageID(), currId++, "messages received out of order"); } } @@ -866,16 +871,16 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); queue.deliverNow(); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); @@ -885,10 +890,10 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(20, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(20, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); consumer.setStatusImmediate(null); @@ -902,15 +907,15 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(numMessages, consumer.getReferences().size()); - Assert.assertEquals(30, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(10, queue.getDeliveringCount()); + assertEquals(numMessages, consumer.getReferences().size()); + assertEquals(30, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(10, queue.getDeliveringCount()); List receeivedRefs = consumer.getReferences(); int currId = 10; for (MessageReference receeivedRef : receeivedRefs) { - Assert.assertEquals("messages received out of order", receeivedRef.getMessage().getMessageID(), currId++); + assertEquals(receeivedRef.getMessage().getMessageID(), currId++, "messages received out of order"); } } @@ -929,15 +934,15 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); queue.deliverNow(); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); for (int i = numMessages; i < numMessages * 2; i++) { MessageReference ref = generateReference(queue, i); @@ -953,9 +958,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(20, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(10, queue.getDeliveringCount()); + assertEquals(20, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(10, queue.getDeliveringCount()); for (int i = numMessages * 2; i < numMessages * 3; i++) { MessageReference ref = generateReference(queue, i); @@ -967,10 +972,10 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(20, consumer.getReferences().size()); - Assert.assertEquals(30, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(20, queue.getDeliveringCount()); + assertEquals(20, consumer.getReferences().size()); + assertEquals(30, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(20, queue.getDeliveringCount()); } @@ -989,10 +994,10 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } - Assert.assertEquals(numMessages, getMessageCount(queue)); + assertEquals(numMessages, getMessageCount(queue)); queue.deliverNow(); - Assert.assertEquals(numMessages, getMessageCount(queue)); + assertEquals(numMessages, getMessageCount(queue)); FakeConsumer consumer = new FakeConsumer(FilterImpl.createFilter("color = 'green'")); queue.addConsumer(consumer); @@ -1001,8 +1006,8 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addConsumer(consumer2); queue.deliverNow(); - Assert.assertEquals(0, consumer.getReferences().size()); - Assert.assertEquals(0, consumer2.getReferences().size()); + assertEquals(0, consumer.getReferences().size()); + assertEquals(0, consumer2.getReferences().size()); // verify redistributor is doing some work.... try { @@ -1018,9 +1023,9 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(0, consumer.getReferences().size()); - Assert.assertEquals(0, consumer2.getReferences().size()); - Assert.assertEquals(0, consumer3.getReferences().size()); + assertEquals(0, consumer.getReferences().size()); + assertEquals(0, consumer2.getReferences().size()); + assertEquals(0, consumer3.getReferences().size()); // verify redistributor not yet needed, only consumer3 gets to // peek at pending @@ -1043,7 +1048,7 @@ public class QueueImplTest extends ActiveMQTestBase { } catch (NullPointerException expected) { } - Assert.assertEquals(numMessages + 1, getMessageCount(queue)); + assertEquals(numMessages + 1, getMessageCount(queue)); } @Test @@ -1063,7 +1068,7 @@ public class QueueImplTest extends ActiveMQTestBase { ref.getMessage().putStringProperty("color", "blue"); queue.addTail(ref); - Assert.assertEquals(3, getMessageCount(queue)); + assertEquals(3, getMessageCount(queue)); FakeConsumer consumerRed = new FakeConsumer(FilterImpl.createFilter("color = 'red'")); queue.addConsumer(consumerRed); @@ -1072,8 +1077,8 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addConsumer(consumerOrange); queue.deliverNow(); - Assert.assertEquals(2, consumerRed.getReferences().size()); - Assert.assertEquals(0, consumerOrange.getReferences().size()); + assertEquals(2, consumerRed.getReferences().size()); + assertEquals(0, consumerOrange.getReferences().size()); // verify redistributor is doing some work.... try { @@ -1090,7 +1095,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.setInternalQueue(true); queue.addRedistributor(0); - Assert.assertNull(queue.getRedistributor()); + assertNull(queue.getRedistributor()); } private void testConsumerWithFilters(final boolean direct) throws Exception { @@ -1152,13 +1157,13 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); } - Assert.assertEquals(6, getMessageCount(queue)); + assertEquals(6, getMessageCount(queue)); awaitExecution(); - Assert.assertEquals(2, consumer.getReferences().size()); + assertEquals(2, consumer.getReferences().size()); - Assert.assertEquals(2, queue.getDeliveringCount()); + assertEquals(2, queue.getDeliveringCount()); assertRefListsIdenticalRefs(refs, consumer.getReferences()); @@ -1173,11 +1178,11 @@ public class QueueImplTest extends ActiveMQTestBase { queue.deliverNow(); - Assert.assertEquals(4, getMessageCount(queue)); + assertEquals(4, getMessageCount(queue)); - Assert.assertEquals(4, consumer.getReferences().size()); + assertEquals(4, consumer.getReferences().size()); - Assert.assertEquals(4, queue.getDeliveringCount()); + assertEquals(4, queue.getDeliveringCount()); } @Test @@ -1191,14 +1196,14 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(messageReference2); queue.addHead(messageReference3, false); - Assert.assertEquals(0, consumer.getReferences().size()); + assertEquals(0, consumer.getReferences().size()); queue.addConsumer(consumer); queue.deliverNow(); - Assert.assertEquals(3, consumer.getReferences().size()); - Assert.assertEquals(messageReference3, consumer.getReferences().get(0)); - Assert.assertEquals(messageReference, consumer.getReferences().get(1)); - Assert.assertEquals(messageReference2, consumer.getReferences().get(2)); + assertEquals(3, consumer.getReferences().size()); + assertEquals(messageReference3, consumer.getReferences().get(0)); + assertEquals(messageReference, consumer.getReferences().get(1)); + assertEquals(messageReference2, consumer.getReferences().get(2)); } @Test @@ -1210,7 +1215,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(messageReference); queue.addTail(messageReference2); queue.addTail(messageReference3); - Assert.assertEquals(getMessagesAdded(queue), 3); + assertEquals(getMessagesAdded(queue), 3); } @Test @@ -1222,7 +1227,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addHead(messageReference, false); queue.addHead(messageReference2, false); queue.addHead(messageReference3, false); - Assert.assertEquals(queue.getReference(2), messageReference2); + assertEquals(queue.getReference(2), messageReference2); } @@ -1235,7 +1240,7 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addHead(messageReference, false); queue.addHead(messageReference2, false); queue.addHead(messageReference3, false); - Assert.assertNull(queue.getReference(5)); + assertNull(queue.getReference(5)); } @@ -1263,34 +1268,34 @@ public class QueueImplTest extends ActiveMQTestBase { queue.addTail(ref); } // even as this queue is paused, it will receive the messages anyway - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); // Now add a consumer FakeConsumer consumer = new FakeConsumer(); queue.addConsumer(consumer); - Assert.assertTrue(consumer.getReferences().isEmpty()); - Assert.assertEquals(10, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); + assertTrue(consumer.getReferences().isEmpty()); + assertEquals(10, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); // explicit order of delivery queue.deliverNow(); // As the queue is paused, even an explicit order of delivery will not work. - Assert.assertEquals(0, consumer.getReferences().size()); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); + assertEquals(0, consumer.getReferences().size()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); // resuming work queue.resume(); awaitExecution(); // after resuming the delivery begins. assertRefListsIdenticalRefs(refs, consumer.getReferences()); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(numMessages, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(numMessages, queue.getDeliveringCount()); } @@ -1325,10 +1330,10 @@ public class QueueImplTest extends ActiveMQTestBase { // the queue even if it's paused will receive the message but won't forward // directly to the consumer until resumed. - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(0, queue.getScheduledCount()); - Assert.assertEquals(0, queue.getDeliveringCount()); - Assert.assertTrue(consumer.getReferences().isEmpty()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(0, queue.getScheduledCount()); + assertEquals(0, queue.getDeliveringCount()); + assertTrue(consumer.getReferences().isEmpty()); // brings the queue to resumed state. queue.resume(); @@ -1337,8 +1342,8 @@ public class QueueImplTest extends ActiveMQTestBase { // resuming delivery of messages assertRefListsIdenticalRefs(refs, consumer.getReferences()); - Assert.assertEquals(numMessages, getMessageCount(queue)); - Assert.assertEquals(numMessages, queue.getDeliveringCount()); + assertEquals(numMessages, getMessageCount(queue)); + assertEquals(numMessages, queue.getDeliveringCount()); } @@ -1349,9 +1354,9 @@ public class QueueImplTest extends ActiveMQTestBase { MessageReference messageReference2 = generateReference(queue, 2); queue.addTail(messageReference); queue.addTail(messageReference2); - Assert.assertEquals(2, getMessagesAdded(queue)); + assertEquals(2, getMessagesAdded(queue)); queue.resetMessagesAdded(); - Assert.assertEquals(0, getMessagesAdded(queue)); + assertEquals(0, getMessagesAdded(queue)); } class AddtoQueueRunner implements Runnable { @@ -1427,7 +1432,7 @@ public class QueueImplTest extends ActiveMQTestBase { int i = 0; while (totalIterator.hasNext()) { MessageReference ref = totalIterator.next(); - Assert.assertEquals(i++, ref.getMessage().getIntProperty("order").intValue()); + assertEquals(i++, ref.getMessage().getIntProperty("order").intValue()); } } finally { totalIterator.close(); @@ -1469,7 +1474,7 @@ public class QueueImplTest extends ActiveMQTestBase { final Consumer noConsumer = new FakeConsumer() { @Override public synchronized HandleStatus handle(MessageReference reference) { - Assert.fail("this consumer isn't allowed to consume any message"); + fail("this consumer isn't allowed to consume any message"); throw new AssertionError(); } }; @@ -1485,13 +1490,13 @@ public class QueueImplTest extends ActiveMQTestBase { final MessageReference secondMessageReference = generateReference(queue, 2); secondMessageReference.getMessage().putStringProperty(Message.HDR_GROUP_ID, groupName); queue.addTail(firstMessageReference, true); - Assert.assertTrue("first message isn't handled", firstMessageHandled.await(3000, TimeUnit.MILLISECONDS)); - Assert.assertEquals("group consumer isn't correctly set", groupConsumer, queue.getGroups().get(groupName)); + assertTrue(firstMessageHandled.await(3000, TimeUnit.MILLISECONDS), "first message isn't handled"); + assertEquals(groupConsumer, queue.getGroups().get(groupName), "group consumer isn't correctly set"); queue.addTail(secondMessageReference, true); final boolean atLeastTwoDeliverAttempts = finished.await(3000, TimeUnit.MILLISECONDS); - Assert.assertTrue(atLeastTwoDeliverAttempts); + assertTrue(atLeastTwoDeliverAttempts); Thread.sleep(1000); - Assert.assertEquals("The second message should be in the queue", 1, queue.getMessageCount()); + assertEquals(1, queue.getMessageCount(), "The second message should be in the queue"); } private QueueImpl getNonDurableQueue() { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilDistributionTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilDistributionTest.java index 6e148fc44c..c141996f93 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilDistributionTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilDistributionTest.java @@ -16,14 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.core.util; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashSet; -import org.apache.activemq.artemis.tests.rules.SpawnedVMCheck; +import org.apache.activemq.artemis.tests.extensions.SpawnedVMCheckExtension; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.SpawnedVMSupport; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -34,8 +35,8 @@ import java.lang.invoke.MethodHandles; public class RandomUtilDistributionTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - @Rule - public SpawnedVMCheck check = new SpawnedVMCheck(); + @RegisterExtension + public SpawnedVMCheckExtension check = new SpawnedVMCheckExtension(); public static void main(String[] arg) { @@ -71,7 +72,7 @@ public class RandomUtilDistributionTest { int minimumExpected = (int) ((iterations * numberOfStarts) * 0.80); logger.debug("values = {}, minimum expected = {}", value, minimumExpected); - Assert.assertTrue("The Random distribution is pretty bad. Many tries have returned duplicated randoms. Number of different values=" + value + ", minimum expected = " + minimumExpected, value >= minimumExpected); + assertTrue(value >= minimumExpected, "The Random distribution is pretty bad. Many tries have returned duplicated randoms. Number of different values=" + value + ", minimum expected = " + minimumExpected); } private int internalDistributionTest(int numberOfTries) throws Exception { @@ -87,7 +88,7 @@ public class RandomUtilDistributionTest { for (int i = 0; i < numberOfTries; i++) { value[i] = process[i].waitFor(); - Assert.assertTrue(value[i] >= 0); + assertTrue(value[i] >= 0); valueSet.add(process[i].exitValue()); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilTest.java index 73a552c548..6ebc2407af 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/util/RandomUtilTest.java @@ -16,9 +16,11 @@ */ package org.apache.activemq.artemis.tests.unit.core.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RandomUtilTest { @@ -26,14 +28,14 @@ public class RandomUtilTest { @Test public void testInterval() { int i = RandomUtil.randomInterval(0, 1000); - Assert.assertTrue(i <= 1000); - Assert.assertTrue(i >= 0); + assertTrue(i <= 1000); + assertTrue(i >= 0); i = RandomUtil.randomInterval(0, 0); - Assert.assertEquals(0, i); + assertEquals(0, i); i = RandomUtil.randomInterval(10, 10); - Assert.assertEquals(10, i); + assertEquals(10, i); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java index 9c6ae10857..029cf7b16a 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/ActiveMQDestinationTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.tests.unit.jms; +import static org.apache.activemq.artemis.jms.client.ActiveMQDestination.QUEUE_QUALIFIED_PREFIX; +import static org.apache.activemq.artemis.jms.client.ActiveMQDestination.TOPIC_QUALIFIED_PREFIX; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Destination; import javax.jms.Queue; import javax.jms.Topic; @@ -25,11 +32,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.apache.activemq.artemis.jms.client.ActiveMQTopic; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; - -import static org.apache.activemq.artemis.jms.client.ActiveMQDestination.QUEUE_QUALIFIED_PREFIX; -import static org.apache.activemq.artemis.jms.client.ActiveMQDestination.TOPIC_QUALIFIED_PREFIX; +import org.junit.jupiter.api.Test; public class ActiveMQDestinationTest extends ActiveMQTestBase { @@ -43,10 +46,10 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { ActiveMQDestination sameDestination = (ActiveMQDestination) ActiveMQDestination.fromPrefixedName(address); ActiveMQDestination differentDestination = (ActiveMQDestination) ActiveMQDestination.fromPrefixedName(address + RandomUtil.randomString()); - Assert.assertFalse(destination.equals(null)); - Assert.assertTrue(destination.equals(destination)); - Assert.assertTrue(destination.equals(sameDestination)); - Assert.assertFalse(destination.equals(differentDestination)); + assertFalse(destination.equals(null)); + assertTrue(destination.equals(destination)); + assertTrue(destination.equals(sameDestination)); + assertFalse(destination.equals(differentDestination)); } @Test @@ -54,8 +57,8 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { String destinationName = RandomUtil.randomString(); String address = QUEUE_QUALIFIED_PREFIX + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromPrefixedName(address); - Assert.assertTrue(destination instanceof Queue); - Assert.assertEquals(destinationName, ((Queue) destination).getQueueName()); + assertTrue(destination instanceof Queue); + assertEquals(destinationName, ((Queue) destination).getQueueName()); } @Test @@ -63,8 +66,8 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { String destinationName = RandomUtil.randomString(); String address = TOPIC_QUALIFIED_PREFIX + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromPrefixedName(address); - Assert.assertTrue(destination instanceof Topic); - Assert.assertEquals(destinationName, ((Topic) destination).getTopicName()); + assertTrue(destination instanceof Topic); + assertEquals(destinationName, ((Topic) destination).getTopicName()); } @Test @@ -73,7 +76,7 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { String destinationName = RandomUtil.randomString(); String address = invalidPrefix + destinationName; ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromPrefixedName(address); - Assert.assertTrue(destination instanceof Destination); + assertTrue(destination instanceof Destination); } @Test @@ -82,7 +85,7 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { try { System.out.println("Destination: " + destination.toString()); } catch (NullPointerException npe) { - Assert.fail("Caught NPE!"); + fail("Caught NPE!"); } } @@ -92,7 +95,7 @@ public class ActiveMQDestinationTest extends ActiveMQTestBase { try { System.out.println("Destination: " + destination.toString()); } catch (NullPointerException npe) { - Assert.fail("Caught NPE!"); + fail("Caught NPE!"); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java index bf113d9624..4ee96ed3a0 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQMapMessageTest.java @@ -16,14 +16,19 @@ */ package org.apache.activemq.artemis.tests.unit.jms.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.MessageFormatException; import org.apache.activemq.artemis.jms.client.ActiveMQMapMessage; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ActiveMQMapMessageTest extends ActiveMQTestBase { @@ -31,7 +36,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { private String itemName; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -45,17 +50,17 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setBoolean(itemName, true); - Assert.assertTrue(message.itemExists(itemName)); + assertTrue(message.itemExists(itemName)); message.clearBody(); - Assert.assertFalse(message.itemExists(itemName)); + assertFalse(message.itemExists(itemName)); } @Test public void testGetType() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - Assert.assertEquals(ActiveMQMapMessage.TYPE, message.getType()); + assertEquals(ActiveMQMapMessage.TYPE, message.getType()); } @Test @@ -63,7 +68,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); try { message.setBoolean(null, true); - Assert.fail("item name can not be null"); + fail("item name can not be null"); } catch (IllegalArgumentException e) { } @@ -74,7 +79,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); try { message.setBoolean("", true); - Assert.fail("item name can not be empty"); + fail("item name can not be empty"); } catch (IllegalArgumentException e) { } @@ -87,13 +92,13 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setBoolean(itemName, value); - Assert.assertEquals(value, message.getBoolean(itemName)); + assertEquals(value, message.getBoolean(itemName)); } @Test public void testGetBooleanFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - Assert.assertEquals(false, message.getBoolean(itemName)); + assertFalse(message.getBoolean(itemName)); } @Test @@ -103,7 +108,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Boolean.toString(value)); - Assert.assertEquals(value, message.getBoolean(itemName)); + assertEquals(value, message.getBoolean(itemName)); } @Test @@ -113,7 +118,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getBoolean(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -125,7 +130,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setByte(itemName, value); - Assert.assertEquals(value, message.getByte(itemName)); + assertEquals(value, message.getByte(itemName)); } @Test @@ -134,7 +139,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getByte(itemName); - Assert.fail("NumberFormatException"); + fail("NumberFormatException"); } catch (NumberFormatException e) { } } @@ -146,7 +151,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Byte.toString(value)); - Assert.assertEquals(value, message.getByte(itemName)); + assertEquals(value, message.getByte(itemName)); } @Test @@ -156,7 +161,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getByte(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -168,7 +173,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setByte(itemName, value); - Assert.assertEquals(value, message.getShort(itemName)); + assertEquals(value, message.getShort(itemName)); } @Test @@ -178,7 +183,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setShort(itemName, value); - Assert.assertEquals(value, message.getShort(itemName)); + assertEquals(value, message.getShort(itemName)); } @Test @@ -187,7 +192,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getShort(itemName); - Assert.fail("NumberFormatException"); + fail("NumberFormatException"); } catch (NumberFormatException e) { } } @@ -199,7 +204,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Short.toString(value)); - Assert.assertEquals(value, message.getShort(itemName)); + assertEquals(value, message.getShort(itemName)); } @Test @@ -209,7 +214,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getShort(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -221,7 +226,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setByte(itemName, value); - Assert.assertEquals(value, message.getInt(itemName)); + assertEquals(value, message.getInt(itemName)); } @Test @@ -231,7 +236,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setShort(itemName, value); - Assert.assertEquals(value, message.getInt(itemName)); + assertEquals(value, message.getInt(itemName)); } @Test @@ -241,7 +246,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setInt(itemName, value); - Assert.assertEquals(value, message.getInt(itemName)); + assertEquals(value, message.getInt(itemName)); } @Test @@ -250,7 +255,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getInt(itemName); - Assert.fail("NumberFormatException"); + fail("NumberFormatException"); } catch (NumberFormatException e) { } } @@ -262,7 +267,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Integer.toString(value)); - Assert.assertEquals(value, message.getInt(itemName)); + assertEquals(value, message.getInt(itemName)); } @Test @@ -272,7 +277,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getInt(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -284,7 +289,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setChar(itemName, value); - Assert.assertEquals(value, message.getChar(itemName)); + assertEquals(value, message.getChar(itemName)); } @Test @@ -293,7 +298,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getChar(itemName); - Assert.fail("NullPointerException"); + fail("NullPointerException"); } catch (NullPointerException e) { } } @@ -305,7 +310,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getChar(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -317,7 +322,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setByte(itemName, value); - Assert.assertEquals(value, message.getLong(itemName)); + assertEquals(value, message.getLong(itemName)); } @Test @@ -327,7 +332,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setShort(itemName, value); - Assert.assertEquals(value, message.getLong(itemName)); + assertEquals(value, message.getLong(itemName)); } @Test @@ -337,7 +342,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setInt(itemName, value); - Assert.assertEquals(value, message.getLong(itemName)); + assertEquals(value, message.getLong(itemName)); } @Test @@ -347,7 +352,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setLong(itemName, value); - Assert.assertEquals(value, message.getLong(itemName)); + assertEquals(value, message.getLong(itemName)); } @Test @@ -356,7 +361,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getLong(itemName); - Assert.fail("NumberFormatException"); + fail("NumberFormatException"); } catch (NumberFormatException e) { } } @@ -368,7 +373,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Long.toString(value)); - Assert.assertEquals(value, message.getLong(itemName)); + assertEquals(value, message.getLong(itemName)); } @Test @@ -378,7 +383,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getLong(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -390,7 +395,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, value); - Assert.assertEquals(value, message.getFloat(itemName), 0.000001); + assertEquals(value, message.getFloat(itemName), 0.000001); } @Test @@ -399,7 +404,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getFloat(itemName); - Assert.fail("NullPointerException"); + fail("NullPointerException"); } catch (NullPointerException e) { } } @@ -411,7 +416,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Float.toString(value)); - Assert.assertEquals(value, message.getFloat(itemName), 0.000001); + assertEquals(value, message.getFloat(itemName), 0.000001); } @Test @@ -421,7 +426,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getFloat(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -433,7 +438,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, value); - Assert.assertEquals(Float.valueOf(value).doubleValue(), message.getDouble(itemName), 0.000001); + assertEquals(Float.valueOf(value).doubleValue(), message.getDouble(itemName), 0.000001); } @Test @@ -443,7 +448,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setDouble(itemName, value); - Assert.assertEquals(value, message.getDouble(itemName), 0.000001); + assertEquals(value, message.getDouble(itemName), 0.000001); } @Test @@ -452,7 +457,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getDouble(itemName); - Assert.fail("NullPointerException"); + fail("NullPointerException"); } catch (NullPointerException e) { } } @@ -464,7 +469,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, Double.toString(value)); - Assert.assertEquals(value, message.getDouble(itemName), 0.000001); + assertEquals(value, message.getDouble(itemName), 0.000001); } @Test @@ -474,7 +479,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getDouble(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -486,7 +491,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setBoolean(itemName, value); - Assert.assertEquals(Boolean.toString(value), message.getString(itemName)); + assertEquals(Boolean.toString(value), message.getString(itemName)); } @Test @@ -496,7 +501,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setByte(itemName, value); - Assert.assertEquals(Byte.toString(value), message.getString(itemName)); + assertEquals(Byte.toString(value), message.getString(itemName)); } @Test @@ -506,7 +511,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setChar(itemName, value); - Assert.assertEquals(Character.toString(value), message.getString(itemName)); + assertEquals(Character.toString(value), message.getString(itemName)); } @Test @@ -516,7 +521,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setShort(itemName, value); - Assert.assertEquals(Short.toString(value), message.getString(itemName)); + assertEquals(Short.toString(value), message.getString(itemName)); } @Test @@ -526,7 +531,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setInt(itemName, value); - Assert.assertEquals(Integer.toString(value), message.getString(itemName)); + assertEquals(Integer.toString(value), message.getString(itemName)); } @Test @@ -536,7 +541,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setLong(itemName, value); - Assert.assertEquals(Long.toString(value), message.getString(itemName)); + assertEquals(Long.toString(value), message.getString(itemName)); } @Test @@ -546,7 +551,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setFloat(itemName, value); - Assert.assertEquals(Float.toString(value), message.getString(itemName)); + assertEquals(Float.toString(value), message.getString(itemName)); } @Test @@ -556,14 +561,14 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setDouble(itemName, value); - Assert.assertEquals(Double.toString(value), message.getString(itemName)); + assertEquals(Double.toString(value), message.getString(itemName)); } @Test public void testGetStringFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - Assert.assertNull(message.getString(itemName)); + assertNull(message.getString(itemName)); } @Test @@ -573,7 +578,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setString(itemName, value); - Assert.assertEquals(value, message.getString(itemName)); + assertEquals(value, message.getString(itemName)); } @Test @@ -589,7 +594,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { public void testGetBytesFromNull() throws Exception { ActiveMQMapMessage message = new ActiveMQMapMessage(); - Assert.assertNull(message.getBytes(itemName)); + assertNull(message.getBytes(itemName)); } @Test @@ -599,7 +604,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { try { message.getBytes(itemName); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -610,7 +615,7 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setObject(itemName, value); - Assert.assertEquals(value, message.getObject(itemName)); + assertEquals(value, message.getObject(itemName)); } @Test @@ -662,6 +667,6 @@ public class ActiveMQMapMessageTest extends ActiveMQTestBase { ActiveMQMapMessage message = new ActiveMQMapMessage(); message.setObject(itemName, value); - Assert.assertEquals(value, message.getObject(itemName)); + assertEquals(value, message.getObject(itemName)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java index d019077265..adeaf54dec 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/ActiveMQStreamMessageTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.jms.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.MessageEOFException; import javax.jms.MessageFormatException; import java.util.ArrayList; @@ -23,17 +27,14 @@ import java.util.ArrayList; import org.apache.activemq.artemis.jms.client.ActiveMQStreamMessage; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ActiveMQStreamMessageTest extends ActiveMQTestBase { - - @Test public void testGetType() throws Exception { ActiveMQStreamMessage message = new ActiveMQStreamMessage(); - Assert.assertEquals(ActiveMQStreamMessage.TYPE, message.getType()); + assertEquals(ActiveMQStreamMessage.TYPE, message.getType()); } @Test @@ -44,7 +45,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeBoolean(value); message.reset(); - Assert.assertEquals(value, message.readBoolean()); + assertEquals(value, message.readBoolean()); } @Test @@ -55,7 +56,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Boolean.toString(value)); message.reset(); - Assert.assertEquals(value, message.readBoolean()); + assertEquals(value, message.readBoolean()); } @Test @@ -106,7 +107,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeByte(value); message.reset(); - Assert.assertEquals(value, message.readByte()); + assertEquals(value, message.readByte()); } @Test @@ -117,7 +118,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Byte.toString(value)); message.reset(); - Assert.assertEquals(value, message.readByte()); + assertEquals(value, message.readByte()); } @Test @@ -197,7 +198,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeByte(value); message.reset(); - Assert.assertEquals(value, message.readShort()); + assertEquals(value, message.readShort()); } @Test @@ -208,7 +209,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeShort(value); message.reset(); - Assert.assertEquals(value, message.readShort()); + assertEquals(value, message.readShort()); } @Test @@ -219,7 +220,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Short.toString(value)); message.reset(); - Assert.assertEquals(value, message.readShort()); + assertEquals(value, message.readShort()); } @Test @@ -250,7 +251,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeByte(value); message.reset(); - Assert.assertEquals(value, message.readInt()); + assertEquals(value, message.readInt()); } @Test @@ -261,7 +262,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeShort(value); message.reset(); - Assert.assertEquals(value, message.readInt()); + assertEquals(value, message.readInt()); } @Test @@ -272,7 +273,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeInt(value); message.reset(); - Assert.assertEquals(value, message.readInt()); + assertEquals(value, message.readInt()); } @Test @@ -283,7 +284,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Integer.toString(value)); message.reset(); - Assert.assertEquals(value, message.readInt()); + assertEquals(value, message.readInt()); } @Test @@ -314,7 +315,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeChar(value); message.reset(); - Assert.assertEquals(value, message.readChar()); + assertEquals(value, message.readChar()); } @Test @@ -339,7 +340,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeByte(value); message.reset(); - Assert.assertEquals(value, message.readLong()); + assertEquals(value, message.readLong()); } @Test @@ -350,7 +351,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeShort(value); message.reset(); - Assert.assertEquals(value, message.readLong()); + assertEquals(value, message.readLong()); } @Test @@ -361,7 +362,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeInt(value); message.reset(); - Assert.assertEquals(value, message.readLong()); + assertEquals(value, message.readLong()); } @Test @@ -372,7 +373,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeLong(value); message.reset(); - Assert.assertEquals(value, message.readLong()); + assertEquals(value, message.readLong()); } @Test @@ -383,7 +384,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Long.toString(value)); message.reset(); - Assert.assertEquals(value, message.readLong()); + assertEquals(value, message.readLong()); } @Test @@ -414,7 +415,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeFloat(value); message.reset(); - Assert.assertEquals(value, message.readFloat(), 0.000001); + assertEquals(value, message.readFloat(), 0.000001); } @Test @@ -425,7 +426,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Float.toString(value)); message.reset(); - Assert.assertEquals(value, message.readFloat(), 0.000001); + assertEquals(value, message.readFloat(), 0.000001); } @Test @@ -456,7 +457,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeFloat(value); message.reset(); - Assert.assertEquals(Float.valueOf(value).doubleValue(), message.readDouble(), 0.000001); + assertEquals(Float.valueOf(value).doubleValue(), message.readDouble(), 0.000001); } @Test @@ -467,7 +468,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeDouble(value); message.reset(); - Assert.assertEquals(value, message.readDouble(), 0.000001); + assertEquals(value, message.readDouble(), 0.000001); } @Test @@ -478,7 +479,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(Double.toString(value)); message.reset(); - Assert.assertEquals(value, message.readDouble(), 0.000001); + assertEquals(value, message.readDouble(), 0.000001); } @Test @@ -509,7 +510,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeBoolean(value); message.reset(); - Assert.assertEquals(Boolean.toString(value), message.readString()); + assertEquals(Boolean.toString(value), message.readString()); } @Test @@ -520,7 +521,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeChar(value); message.reset(); - Assert.assertEquals(Character.toString(value), message.readString()); + assertEquals(Character.toString(value), message.readString()); } @Test @@ -531,7 +532,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeByte(value); message.reset(); - Assert.assertEquals(Byte.toString(value), message.readString()); + assertEquals(Byte.toString(value), message.readString()); } @Test @@ -549,7 +550,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { } // we can read the String without resetting the message - Assert.assertEquals(value, message.readString()); + assertEquals(value, message.readString()); } @Test @@ -560,7 +561,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeShort(value); message.reset(); - Assert.assertEquals(Short.toString(value), message.readString()); + assertEquals(Short.toString(value), message.readString()); } @Test @@ -571,7 +572,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeInt(value); message.reset(); - Assert.assertEquals(Integer.toString(value), message.readString()); + assertEquals(Integer.toString(value), message.readString()); } @Test @@ -582,7 +583,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeLong(value); message.reset(); - Assert.assertEquals(Long.toString(value), message.readString()); + assertEquals(Long.toString(value), message.readString()); } @Test @@ -593,7 +594,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeFloat(value); message.reset(); - Assert.assertEquals(Float.toString(value), message.readString()); + assertEquals(Float.toString(value), message.readString()); } @Test @@ -604,7 +605,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeDouble(value); message.reset(); - Assert.assertEquals(Double.toString(value), message.readString()); + assertEquals(Double.toString(value), message.readString()); } @Test @@ -615,7 +616,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(value); message.reset(); - Assert.assertEquals(value, message.readString()); + assertEquals(value, message.readString()); } @Test @@ -625,7 +626,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.writeString(null); message.reset(); - Assert.assertNull(message.readString()); + assertNull(message.readString()); } @Test @@ -754,7 +755,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { try { message.writeObject(new ArrayList()); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -767,7 +768,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -778,7 +779,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -789,7 +790,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -812,7 +813,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -823,7 +824,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -834,7 +835,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -845,7 +846,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -856,7 +857,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @Test @@ -867,7 +868,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { message.reset(); - Assert.assertEquals(value, message.readObject()); + assertEquals(value, message.readObject()); } @@ -877,7 +878,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { try { reader.readType(message); - Assert.fail("MessageEOFException"); + fail("MessageEOFException"); } catch (MessageEOFException e) { } } @@ -890,7 +891,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { try { reader.readType(message); - Assert.fail("MessageFormatException"); + fail("MessageFormatException"); } catch (MessageFormatException e) { } } @@ -905,7 +906,7 @@ public class ActiveMQStreamMessageTest extends ActiveMQTestBase { if (value instanceof byte[]) { ActiveMQTestBase.assertEqualsByteArrays((byte[]) value, (byte[]) v); } else { - Assert.assertEquals(value, v); + assertEquals(value, v); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java index 945b64707d..a415ad2821 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/JMSExceptionHelperTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.jms.client; +import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.CONNECTION_TIMEDOUT; +import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.GENERIC_EXCEPTION; +import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.INVALID_FILTER_EXPRESSION; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import javax.jms.IllegalStateException; import javax.jms.InvalidDestinationException; import javax.jms.InvalidSelectorException; @@ -26,17 +32,10 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.jms.client.JMSExceptionHelper; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; - -import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.CONNECTION_TIMEDOUT; -import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.GENERIC_EXCEPTION; -import static org.apache.activemq.artemis.api.core.ActiveMQExceptionType.INVALID_FILTER_EXPRESSION; +import org.junit.jupiter.api.Test; public class JMSExceptionHelperTest extends ActiveMQTestBase { - - @Test public void testCONNECTION_TIMEDOUT() throws Exception { doConvertException(CONNECTION_TIMEDOUT, JMSException.class); @@ -96,7 +95,7 @@ public class JMSExceptionHelperTest extends ActiveMQTestBase { final Class expectedException) { ActiveMQException me = new ActiveMQException(errorCode); Exception e = JMSExceptionHelper.convertFromActiveMQException(me); - Assert.assertNotNull(e); - Assert.assertTrue(e.getClass().isAssignableFrom(expectedException)); + assertNotNull(e); + assertTrue(e.getClass().isAssignableFrom(expectedException)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java index da7da4cea2..4e1ee05e14 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/client/SelectorTranslatorTest.java @@ -16,49 +16,51 @@ */ package org.apache.activemq.artemis.tests.unit.jms.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.SelectorTranslator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SelectorTranslatorTest extends ActiveMQTestBase { @Test public void testParseNull() { - Assert.assertNull(SelectorTranslator.convertToActiveMQFilterString(null)); + assertNull(SelectorTranslator.convertToActiveMQFilterString(null)); } @Test public void testParseSimple() { final String selector = "color = 'red'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test public void testParseMoreComplex() { final String selector = "color = 'red' OR cheese = 'stilton' OR (age = 3 AND shoesize = 12)"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); } @Test public void testParseJMSDeliveryMode() { String selector = "JMSDeliveryMode='NON_PERSISTENT'"; - Assert.assertEquals("AMQDurable='NON_DURABLE'", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQDurable='NON_DURABLE'", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "JMSDeliveryMode='PERSISTENT'"; - Assert.assertEquals("AMQDurable='DURABLE'", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQDurable='DURABLE'", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "color = 'red' AND 'NON_PERSISTENT' = JMSDeliveryMode"; - Assert.assertEquals("color = 'red' AND 'NON_DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("color = 'red' AND 'NON_DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "color = 'red' AND 'PERSISTENT' = JMSDeliveryMode"; - Assert.assertEquals("color = 'red' AND 'DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("color = 'red' AND 'DURABLE' = AMQDurable", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSDeliveryMode"); } @@ -67,21 +69,21 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSPriority() { String selector = "JMSPriority=5"; - Assert.assertEquals("AMQPriority=5", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQPriority=5", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSPriority = 7"; - Assert.assertEquals(" AMQPriority = 7", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQPriority = 7", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSPriority = 7 OR 1 = JMSPriority AND (JMSPriority= 1 + 4)"; - Assert.assertEquals(" AMQPriority = 7 OR 1 = AMQPriority AND (AMQPriority= 1 + 4)", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQPriority = 7 OR 1 = AMQPriority AND (AMQPriority= 1 + 4)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSPriority"); selector = "animal = 'lion' JMSPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'"; - Assert.assertEquals("animal = 'lion' AMQPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("animal = 'lion' AMQPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @@ -89,23 +91,23 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSMessageID() { String selector = "JMSMessageID='ID:AMQ-12435678"; - Assert.assertEquals("AMQUserID='ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQUserID='ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSMessageID='ID:AMQ-12435678"; - Assert.assertEquals(" AMQUserID='ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQUserID='ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSMessageID = 'ID:AMQ-12435678"; - Assert.assertEquals(" AMQUserID = 'ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQUserID = 'ID:AMQ-12435678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSMessageID"; - Assert.assertEquals(" myHeader = AMQUserID", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" myHeader = AMQUserID", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSMessageID OR (JMSMessageID = 'ID-AMQ' + '12345')"; - Assert.assertEquals(" myHeader = AMQUserID OR (AMQUserID = 'ID-AMQ' + '12345')", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" myHeader = AMQUserID OR (AMQUserID = 'ID-AMQ' + '12345')", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSMessageID"); } @@ -114,21 +116,21 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSTimestamp() { String selector = "JMSTimestamp=12345678"; - Assert.assertEquals("AMQTimestamp=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQTimestamp=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSTimestamp=12345678"; - Assert.assertEquals(" AMQTimestamp=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQTimestamp=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSTimestamp=12345678 OR 78766 = JMSTimestamp AND (JMSTimestamp= 1 + 4878787)"; - Assert.assertEquals(" AMQTimestamp=12345678 OR 78766 = AMQTimestamp AND (AMQTimestamp= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQTimestamp=12345678 OR 78766 = AMQTimestamp AND (AMQTimestamp= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSTimestamp"); selector = "animal = 'lion' JMSTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'"; - Assert.assertEquals("animal = 'lion' AMQTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("animal = 'lion' AMQTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @@ -136,21 +138,21 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSExpiration() { String selector = "JMSExpiration=12345678"; - Assert.assertEquals("AMQExpiration=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("AMQExpiration=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSExpiration=12345678"; - Assert.assertEquals(" AMQExpiration=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQExpiration=12345678", SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSExpiration=12345678 OR 78766 = JMSExpiration AND (JMSExpiration= 1 + 4878787)"; - Assert.assertEquals(" AMQExpiration=12345678 OR 78766 = AMQExpiration AND (AMQExpiration= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(" AMQExpiration=12345678 OR 78766 = AMQExpiration AND (AMQExpiration= 1 + 4878787)", SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSExpiration"); selector = "animal = 'lion' JMSExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'"; - Assert.assertEquals("animal = 'lion' AMQExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals("animal = 'lion' AMQExpiration = 321 OR animal_name = 'xyzJMSExpirationxyz'", SelectorTranslator.convertToActiveMQFilterString(selector)); } @@ -158,23 +160,23 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSCorrelationID() { String selector = "JMSCorrelationID='ID:AMQ-12435678"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSCorrelationID='ID:AMQ-12435678"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSCorrelationID = 'ID:AMQ-12435678"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSCorrelationID"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSCorrelationID OR (JMSCorrelationID = 'ID-AMQ' + '12345')"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSCorrelationID"); } @@ -183,23 +185,23 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { public void testParseJMSType() { String selector = "JMSType='aardvark'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSType='aardvark'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " JMSType = 'aardvark'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSType"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = " myHeader = JMSType OR (JMSType = 'aardvark' + 'sandwich')"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); checkNoSubstitute("JMSType"); } @@ -207,43 +209,43 @@ public class SelectorTranslatorTest extends ActiveMQTestBase { private void checkNoSubstitute(final String fieldName) { String selector = "Other" + fieldName + " = 767868"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "cheese = 'cheddar' AND Wrong" + fieldName + " = 54"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "fruit = 'pomegranate' AND " + fieldName + "NotThisOne = 'tuesday'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = '" + fieldName + "'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = ' " + fieldName + "'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = ' " + fieldName + " '"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = 'xyz " + fieldName + "'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = 'xyz" + fieldName + "'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = '" + fieldName + "xyz'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); selector = "animal = 'lion' AND animal_name = 'xyz" + fieldName + "xyz'"; - Assert.assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); + assertEquals(selector, SelectorTranslator.convertToActiveMQFilterString(selector)); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/ObjectFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/ObjectFactoryTest.java index fedf9ce1b4..f511222099 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/ObjectFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/ObjectFactoryTest.java @@ -16,13 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.jms.jndi; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import javax.naming.Reference; import javax.naming.StringRefAddr; import java.net.URI; import java.util.Map; +import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; @@ -32,12 +34,13 @@ import org.apache.activemq.artemis.jndi.JNDIReferenceFactory; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.uri.URISupport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class ObjectFactoryTest { - @Test(timeout = 1000) + @Test + @Timeout(value = 1000, unit = TimeUnit.MILLISECONDS) public void testConnectionFactory() throws Exception { // Create sample connection factory ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://0"); @@ -99,33 +102,34 @@ public class ObjectFactoryTest { temp = (ActiveMQConnectionFactory)refFactory.getObjectInstance(ref, null, null, null); // Check settings - Assert.assertEquals(clientID, temp.getClientID()); - Assert.assertEquals(user, temp.getUser()); - Assert.assertEquals(password, temp.getPassword()); - Assert.assertEquals(clientFailureCheckPeriod, temp.getClientFailureCheckPeriod()); - Assert.assertEquals(connectionTTL, temp.getConnectionTTL()); - Assert.assertEquals(callTimeout, temp.getCallTimeout()); - Assert.assertEquals(minLargeMessageSize, temp.getMinLargeMessageSize()); - Assert.assertEquals(consumerWindowSize, temp.getConsumerWindowSize()); - Assert.assertEquals(consumerMaxRate, temp.getConsumerMaxRate()); - Assert.assertEquals(confirmationWindowSize, temp.getConfirmationWindowSize()); - Assert.assertEquals(producerMaxRate, temp.getProducerMaxRate()); - Assert.assertEquals(blockOnAcknowledge, temp.isBlockOnAcknowledge()); - Assert.assertEquals(blockOnDurableSend, temp.isBlockOnDurableSend()); - Assert.assertEquals(blockOnNonDurableSend, temp.isBlockOnNonDurableSend()); - Assert.assertEquals(autoGroup, temp.isAutoGroup()); - Assert.assertEquals(preAcknowledge, temp.isPreAcknowledge()); - Assert.assertEquals(loadBalancingPolicyClassName, temp.getConnectionLoadBalancingPolicyClassName()); - Assert.assertEquals(useGlobalPools, temp.isUseGlobalPools()); - Assert.assertEquals(scheduledThreadPoolMaxSize, temp.getScheduledThreadPoolMaxSize()); - Assert.assertEquals(threadPoolMaxSize, temp.getThreadPoolMaxSize()); - Assert.assertEquals(retryInterval, temp.getRetryInterval()); - Assert.assertEquals(retryIntervalMultiplier, temp.getRetryIntervalMultiplier(), 0.0001); - Assert.assertEquals(reconnectAttempts, temp.getReconnectAttempts()); + assertEquals(clientID, temp.getClientID()); + assertEquals(user, temp.getUser()); + assertEquals(password, temp.getPassword()); + assertEquals(clientFailureCheckPeriod, temp.getClientFailureCheckPeriod()); + assertEquals(connectionTTL, temp.getConnectionTTL()); + assertEquals(callTimeout, temp.getCallTimeout()); + assertEquals(minLargeMessageSize, temp.getMinLargeMessageSize()); + assertEquals(consumerWindowSize, temp.getConsumerWindowSize()); + assertEquals(consumerMaxRate, temp.getConsumerMaxRate()); + assertEquals(confirmationWindowSize, temp.getConfirmationWindowSize()); + assertEquals(producerMaxRate, temp.getProducerMaxRate()); + assertEquals(blockOnAcknowledge, temp.isBlockOnAcknowledge()); + assertEquals(blockOnDurableSend, temp.isBlockOnDurableSend()); + assertEquals(blockOnNonDurableSend, temp.isBlockOnNonDurableSend()); + assertEquals(autoGroup, temp.isAutoGroup()); + assertEquals(preAcknowledge, temp.isPreAcknowledge()); + assertEquals(loadBalancingPolicyClassName, temp.getConnectionLoadBalancingPolicyClassName()); + assertEquals(useGlobalPools, temp.isUseGlobalPools()); + assertEquals(scheduledThreadPoolMaxSize, temp.getScheduledThreadPoolMaxSize()); + assertEquals(threadPoolMaxSize, temp.getThreadPoolMaxSize()); + assertEquals(retryInterval, temp.getRetryInterval()); + assertEquals(retryIntervalMultiplier, temp.getRetryIntervalMultiplier(), 0.0001); + assertEquals(reconnectAttempts, temp.getReconnectAttempts()); } - @Test(timeout = 1000) + @Test + @Timeout(value = 1000, unit = TimeUnit.MILLISECONDS) public void testDestination() throws Exception { // Create sample destination ActiveMQDestination dest = (ActiveMQDestination) ActiveMQJMSClient.createQueue(RandomUtil.randomString()); @@ -159,11 +163,11 @@ public class ObjectFactoryTest { URI uri = cf.toURI(); Map params = URISupport.parseParameters(uri); - Assert.assertEquals("true", params.get(TransportConstants.SSL_ENABLED_PROP_NAME)); - Assert.assertEquals("/path/to/trustStore", params.get(TransportConstants.TRUSTSTORE_PATH_PROP_NAME)); - Assert.assertEquals("trustStorePassword", params.get(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME)); - Assert.assertEquals("/path/to/keyStore", params.get(TransportConstants.KEYSTORE_PATH_PROP_NAME)); - Assert.assertEquals("keyStorePassword", params.get(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME)); - Assert.assertNull(params.get("doesnotexist")); + assertEquals("true", params.get(TransportConstants.SSL_ENABLED_PROP_NAME)); + assertEquals("/path/to/trustStore", params.get(TransportConstants.TRUSTSTORE_PATH_PROP_NAME)); + assertEquals("trustStorePassword", params.get(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME)); + assertEquals("/path/to/keyStore", params.get(TransportConstants.KEYSTORE_PATH_PROP_NAME)); + assertEquals("keyStorePassword", params.get(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME)); + assertNull(params.get("doesnotexist")); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/StringRefAddrReferenceTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/StringRefAddrReferenceTest.java index 0060a40548..faafd72b31 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/StringRefAddrReferenceTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/jms/jndi/StringRefAddrReferenceTest.java @@ -16,19 +16,21 @@ */ package org.apache.activemq.artemis.tests.unit.jms.jndi; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; import java.util.Enumeration; import java.util.Properties; +import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.apache.activemq.artemis.jms.client.ActiveMQTopic; import org.apache.activemq.artemis.jndi.JNDIReferenceFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; /** * Test to simulate JNDI references created using String properties in containers such as Apache Tomcat. @@ -38,7 +40,8 @@ public class StringRefAddrReferenceTest { private static final String FACTORY = "factory"; private static final String TYPE = "type"; - @Test(timeout = 10000) + @Test + @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testActiveMQQueueFromPropertiesJNDI() throws Exception { Properties properties = new Properties(); properties.setProperty(TYPE, ActiveMQQueue.class.getName()); @@ -55,7 +58,8 @@ public class StringRefAddrReferenceTest { } - @Test(timeout = 10000) + @Test + @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testActiveMQTopicFromPropertiesJNDI() throws Exception { Properties properties = new Properties(); properties.setProperty(TYPE, ActiveMQTopic.class.getName()); @@ -72,7 +76,8 @@ public class StringRefAddrReferenceTest { } - @Test(timeout = 10000) + @Test + @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testActiveMQConnectionFactoryFromPropertiesJNDI() throws Exception { Properties properties = new Properties(); properties.setProperty(TYPE, ActiveMQConnectionFactory.class.getName()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/logging/AssertionLoggerTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/logging/AssertionLoggerTest.java index 1eeaf2ae77..8019209d47 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/logging/AssertionLoggerTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/logging/AssertionLoggerTest.java @@ -16,13 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.logging; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.artemis.logs.AssertionLoggerHandler; import org.apache.activemq.artemis.protocol.amqp.broker.ActiveMQProtonRemotingConnection; import org.apache.activemq.artemis.protocol.amqp.logger.ActiveMQAMQPProtocolLogger; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,7 +49,7 @@ public class AssertionLoggerTest { public void testInfoAMQP() throws Exception { try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { ActiveMQAMQPProtocolLogger.LOGGER.retryConnection("test", "test", 1, 1); - Assert.assertTrue(loggerHandler.findText("AMQ111002")); + assertTrue(loggerHandler.findText("AMQ111002")); } } @@ -56,21 +58,21 @@ public class AssertionLoggerTest { Logger logging = LoggerFactory.getLogger(clazz); try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { logging.warn(randomLogging); - Assert.assertTrue(loggerHandler.findText(randomLogging)); + assertTrue(loggerHandler.findText(randomLogging)); } try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { for (int i = 0; i < 10; i++) { logging.warn(randomLogging); } - Assert.assertEquals(10, loggerHandler.countText(randomLogging)); + assertEquals(10, loggerHandler.countText(randomLogging)); } try (AssertionLoggerHandler loggerHandler = new AssertionLoggerHandler()) { for (int i = 0; i < 10; i++) { logging.info(randomLogging); } - Assert.assertEquals(10, loggerHandler.countText(randomLogging)); + assertEquals(10, loggerHandler.countText(randomLogging)); } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQActivationsSpecTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQActivationsSpecTest.java index 640bad15b6..04a6031716 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQActivationsSpecTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQActivationsSpecTest.java @@ -16,46 +16,57 @@ */ package org.apache.activemq.artemis.tests.unit.ra; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import javax.jms.Session; import javax.resource.spi.InvalidPropertyException; import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationValidationUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ActiveMQActivationsSpecTest { - @Test(expected = InvalidPropertyException.class) + @Test public void nullDestinationName() throws InvalidPropertyException { - ActiveMQActivationValidationUtils.validate(null, "destinationType", false, "subscriptionName"); + assertThrows(InvalidPropertyException.class, () -> { + ActiveMQActivationValidationUtils.validate(null, "destinationType", false, "subscriptionName"); + }); } - @Test(expected = InvalidPropertyException.class) + @Test public void emptyDestinationName() throws InvalidPropertyException { - ActiveMQActivationValidationUtils.validate(null, "destinationType", false, "subscriptionName"); + assertThrows(InvalidPropertyException.class, () -> { + ActiveMQActivationValidationUtils.validate(null, "destinationType", false, "subscriptionName"); + }); } public void nullDestinationType() throws InvalidPropertyException { ActiveMQActivationValidationUtils.validate("destinationName", null, false, "subscriptionName"); } - @Test(expected = InvalidPropertyException.class) + @Test public void emptyDestinationType() throws InvalidPropertyException { - ActiveMQActivationValidationUtils.validate("destinationName", "", false, "subscriptionName"); + assertThrows(InvalidPropertyException.class, () -> { + ActiveMQActivationValidationUtils.validate("destinationName", "", false, "subscriptionName"); + }); } - @Test(expected = InvalidPropertyException.class) + @Test public void subscriptionDurableButNoName() throws InvalidPropertyException { - ActiveMQActivationValidationUtils.validate("", "", true, "subscriptionName"); + assertThrows(InvalidPropertyException.class, () -> { + ActiveMQActivationValidationUtils.validate("", "", true, "subscriptionName"); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void validateAcknowledgeMode() { - assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("DUPS_OK_ACKNOWLEDGE"), Session.DUPS_OK_ACKNOWLEDGE); - assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("Dups-ok-acknowledge"), Session.DUPS_OK_ACKNOWLEDGE); - assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("AUTO_ACKNOWLEDGE"), Session.AUTO_ACKNOWLEDGE); - assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("Auto-acknowledge"), Session.AUTO_ACKNOWLEDGE); - ActiveMQActivationValidationUtils.validateAcknowledgeMode("Invalid Acknowledge Mode"); + assertThrows(IllegalArgumentException.class, () -> { + assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("DUPS_OK_ACKNOWLEDGE"), Session.DUPS_OK_ACKNOWLEDGE); + assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("Dups-ok-acknowledge"), Session.DUPS_OK_ACKNOWLEDGE); + assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("AUTO_ACKNOWLEDGE"), Session.AUTO_ACKNOWLEDGE); + assertEquals(ActiveMQActivationValidationUtils.validateAcknowledgeMode("Auto-acknowledge"), Session.AUTO_ACKNOWLEDGE); + ActiveMQActivationValidationUtils.validateAcknowledgeMode("Invalid Acknowledge Mode"); + }); } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java index 5a9ca8b53a..bafbdd91d9 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQResourceAdapterConfigTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.ra; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + import javax.xml.parsers.DocumentBuilder; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -26,7 +30,7 @@ import java.util.Map; import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.XmlProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; @@ -472,14 +476,14 @@ public class ActiveMQResourceAdapterConfigTest extends ActiveMQTestBase { for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); NodeList elementsByTagName = el.getElementsByTagName("config-property-name"); - assertEquals(el.toString(), elementsByTagName.getLength(), 1); + assertEquals(elementsByTagName.getLength(), 1, el.toString()); Node configPropertyNameNode = elementsByTagName.item(0); String configPropertyName = configPropertyNameNode.getTextContent(); Method setter = methodList.remove("set" + configPropertyName); - assertNotNull("setter " + configPropertyName + " does not exist", setter); + assertNotNull(setter, "setter " + configPropertyName + " does not exist"); Class c = lookupType(setter); elementsByTagName = el.getElementsByTagName("config-property-type"); - assertEquals("setter " + configPropertyName + " has no type set", elementsByTagName.getLength(), 1); + assertEquals(elementsByTagName.getLength(), 1, "setter " + configPropertyName + " has no type set"); Node configPropertyTypeNode = elementsByTagName.item(0); String configPropertyTypeName = configPropertyTypeNode.getTextContent(); assertEquals(configPropertyTypeName, c.getName()); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQXAResourceWrapperTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQXAResourceWrapperTest.java index 8734182fa0..3b3dedd65e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQXAResourceWrapperTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ActiveMQXAResourceWrapperTest.java @@ -17,19 +17,23 @@ package org.apache.activemq.artemis.tests.unit.ra; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.HashMap; import java.util.Map; + +import javax.transaction.xa.XAResource; + +import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientSession; +import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter; import org.apache.activemq.artemis.service.extensions.xa.recovery.ActiveMQXAResourceWrapper; import org.apache.activemq.artemis.service.extensions.xa.recovery.XARecoveryConfig; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Test; - -import javax.transaction.xa.XAResource; -import org.apache.activemq.artemis.api.core.TransportConfiguration; -import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; +import org.junit.jupiter.api.Test; public class ActiveMQXAResourceWrapperTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java index c0127c3796..0ca9817da0 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ConnectionFactoryPropertiesTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.ra; +import static java.beans.Introspector.getBeanInfo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.HashMap; @@ -29,10 +35,7 @@ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter; import org.apache.activemq.artemis.ra.ConnectionFactoryProperties; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; - -import static java.beans.Introspector.getBeanInfo; +import org.junit.jupiter.api.Test; public class ConnectionFactoryPropertiesTest extends ActiveMQTestBase { @@ -83,7 +86,7 @@ public class ConnectionFactoryPropertiesTest extends ActiveMQTestBase { @Test public void testCompareConnectionFactoryAndResourceAdapterProperties() throws Exception { SortedSet connectionFactoryProperties = findAllPropertyNames(ActiveMQConnectionFactory.class); - Assert.assertTrue(connectionFactoryProperties.contains("useTopologyForLoadBalancing")); + assertTrue(connectionFactoryProperties.contains("useTopologyForLoadBalancing")); connectionFactoryProperties.removeAll(UNSUPPORTED_CF_PROPERTIES); SortedSet raProperties = findAllPropertyNames(ActiveMQResourceAdapter.class); raProperties.removeAll(UNSUPPORTED_RA_PROPERTIES); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java index eb9131feb0..16a0aaa754 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.ra; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import javax.jms.Connection; import java.util.ArrayList; import java.util.HashMap; @@ -41,42 +47,39 @@ import org.apache.activemq.artemis.ra.ConnectionFactoryProperties; import org.apache.activemq.artemis.ra.inflow.ActiveMQActivation; import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ResourceAdapterTest extends ActiveMQTestBase { - - @Test public void testDefaultConnectionFactory() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory(); - Assert.assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); - Assert.assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); - Assert.assertEquals(factory.getClientID(), null); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); - Assert.assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); - Assert.assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); - Assert.assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); - Assert.assertEquals(factory.getDupsOKBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); - Assert.assertEquals(factory.getMinLargeMessageSize(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); - Assert.assertEquals(factory.getProducerMaxRate(), ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE); - Assert.assertEquals(factory.getConfirmationWindowSize(), ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE); + assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); + assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); + assertEquals(factory.getClientID(), null); + assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); + assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); + assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); + assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); + assertEquals(factory.getDupsOKBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); + assertEquals(factory.getMinLargeMessageSize(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); + assertEquals(factory.getProducerMaxRate(), ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE); + assertEquals(factory.getConfirmationWindowSize(), ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE); // by default, reconnect attempts is set to -1 - Assert.assertEquals(-1, factory.getReconnectAttempts()); - Assert.assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.00001); - Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); - Assert.assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); - Assert.assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); - Assert.assertEquals(factory.isAutoGroup(), ActiveMQClient.DEFAULT_AUTO_GROUP); - Assert.assertEquals(factory.isBlockOnAcknowledge(), ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); - Assert.assertEquals(factory.isBlockOnNonDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); - Assert.assertEquals(factory.isBlockOnDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); - Assert.assertEquals(factory.isPreAcknowledge(), ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); - Assert.assertEquals(factory.isUseGlobalPools(), ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); + assertEquals(-1, factory.getReconnectAttempts()); + assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); + assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.00001); + assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); + assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); + assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); + assertEquals(factory.isAutoGroup(), ActiveMQClient.DEFAULT_AUTO_GROUP); + assertEquals(factory.isBlockOnAcknowledge(), ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); + assertEquals(factory.isBlockOnNonDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); + assertEquals(factory.isBlockOnDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); + assertEquals(factory.isPreAcknowledge(), ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); + assertEquals(factory.isUseGlobalPools(), ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); } @Test @@ -85,7 +88,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory(); ActiveMQConnectionFactory factory2 = ra.getDefaultActiveMQConnectionFactory(); - Assert.assertEquals(factory, factory2); + assertEquals(factory, factory2); } @Test @@ -93,30 +96,30 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setConnectorClassName(InVMConnectorFactory.class.getName()); ActiveMQConnectionFactory factory = ra.getConnectionFactory(new ConnectionFactoryProperties()); - Assert.assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); - Assert.assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); - Assert.assertEquals(factory.getClientID(), null); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); - Assert.assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); - Assert.assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); - Assert.assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); - Assert.assertEquals(factory.getDupsOKBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); - Assert.assertEquals(factory.getMinLargeMessageSize(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); - Assert.assertEquals(factory.getProducerMaxRate(), ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE); - Assert.assertEquals(factory.getConfirmationWindowSize(), ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE); + assertEquals(factory.getCallTimeout(), ActiveMQClient.DEFAULT_CALL_TIMEOUT); + assertEquals(factory.getClientFailureCheckPeriod(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD); + assertEquals(factory.getClientID(), null); + assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME); + assertEquals(factory.getConnectionTTL(), ActiveMQClient.DEFAULT_CONNECTION_TTL); + assertEquals(factory.getConsumerMaxRate(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE); + assertEquals(factory.getConsumerWindowSize(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE); + assertEquals(factory.getDupsOKBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); + assertEquals(factory.getMinLargeMessageSize(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE); + assertEquals(factory.getProducerMaxRate(), ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE); + assertEquals(factory.getConfirmationWindowSize(), ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE); // by default, reconnect attempts is set to -1 - Assert.assertEquals(-1, factory.getReconnectAttempts()); - Assert.assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.000001); - Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); - Assert.assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); - Assert.assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); - Assert.assertEquals(factory.isAutoGroup(), ActiveMQClient.DEFAULT_AUTO_GROUP); - Assert.assertEquals(factory.isBlockOnAcknowledge(), ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); - Assert.assertEquals(factory.isBlockOnNonDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); - Assert.assertEquals(factory.isBlockOnDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); - Assert.assertEquals(factory.isPreAcknowledge(), ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); - Assert.assertEquals(factory.isUseGlobalPools(), ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); + assertEquals(-1, factory.getReconnectAttempts()); + assertEquals(factory.getRetryInterval(), ActiveMQClient.DEFAULT_RETRY_INTERVAL); + assertEquals(factory.getRetryIntervalMultiplier(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0.000001); + assertEquals(factory.getScheduledThreadPoolMaxSize(), ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE); + assertEquals(factory.getThreadPoolMaxSize(), ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE); + assertEquals(factory.getTransactionBatchSize(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE); + assertEquals(factory.isAutoGroup(), ActiveMQClient.DEFAULT_AUTO_GROUP); + assertEquals(factory.isBlockOnAcknowledge(), ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); + assertEquals(factory.isBlockOnNonDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); + assertEquals(factory.isBlockOnDurableSend(), ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); + assertEquals(factory.isPreAcknowledge(), ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); + assertEquals(factory.isUseGlobalPools(), ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); } @Test @@ -149,29 +152,29 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ra.setTransactionBatchSize(18); ra.setUseGlobalPools(!ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory(); - Assert.assertEquals(factory.getCallTimeout(), 1); - Assert.assertEquals(factory.getClientFailureCheckPeriod(), 2); - Assert.assertEquals(factory.getClientID(), "myid"); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), "mlbcn"); - Assert.assertEquals(factory.getConnectionTTL(), 3); - Assert.assertEquals(factory.getConsumerMaxRate(), 4); - Assert.assertEquals(factory.getConsumerWindowSize(), 5); - Assert.assertEquals(factory.getDupsOKBatchSize(), 8); - Assert.assertEquals(factory.getMinLargeMessageSize(), 10); - Assert.assertEquals(factory.getProducerMaxRate(), 11); - Assert.assertEquals(factory.getConfirmationWindowSize(), 12); - Assert.assertEquals(factory.getReconnectAttempts(), 13); - Assert.assertEquals(factory.getRetryInterval(), 14); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), 15d, 0.00001); - Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), 16); - Assert.assertEquals(factory.getThreadPoolMaxSize(), 17); - Assert.assertEquals(factory.getTransactionBatchSize(), 18); - Assert.assertEquals(factory.isAutoGroup(), !ActiveMQClient.DEFAULT_AUTO_GROUP); - Assert.assertEquals(factory.isBlockOnAcknowledge(), !ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); - Assert.assertEquals(factory.isBlockOnNonDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); - Assert.assertEquals(factory.isBlockOnDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); - Assert.assertEquals(factory.isPreAcknowledge(), !ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); - Assert.assertEquals(factory.isUseGlobalPools(), !ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); + assertEquals(factory.getCallTimeout(), 1); + assertEquals(factory.getClientFailureCheckPeriod(), 2); + assertEquals(factory.getClientID(), "myid"); + assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), "mlbcn"); + assertEquals(factory.getConnectionTTL(), 3); + assertEquals(factory.getConsumerMaxRate(), 4); + assertEquals(factory.getConsumerWindowSize(), 5); + assertEquals(factory.getDupsOKBatchSize(), 8); + assertEquals(factory.getMinLargeMessageSize(), 10); + assertEquals(factory.getProducerMaxRate(), 11); + assertEquals(factory.getConfirmationWindowSize(), 12); + assertEquals(factory.getReconnectAttempts(), 13); + assertEquals(factory.getRetryInterval(), 14); + assertEquals(factory.getRetryIntervalMultiplier(), 15d, 0.00001); + assertEquals(factory.getScheduledThreadPoolMaxSize(), 16); + assertEquals(factory.getThreadPoolMaxSize(), 17); + assertEquals(factory.getTransactionBatchSize(), 18); + assertEquals(factory.isAutoGroup(), !ActiveMQClient.DEFAULT_AUTO_GROUP); + assertEquals(factory.isBlockOnAcknowledge(), !ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); + assertEquals(factory.isBlockOnNonDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); + assertEquals(factory.isBlockOnDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); + assertEquals(factory.isPreAcknowledge(), !ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); + assertEquals(factory.isUseGlobalPools(), !ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); } @Test @@ -205,29 +208,29 @@ public class ResourceAdapterTest extends ActiveMQTestBase { connectionFactoryProperties.setTransactionBatchSize(18); connectionFactoryProperties.setUseGlobalPools(!ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); ActiveMQConnectionFactory factory = ra.getConnectionFactory(connectionFactoryProperties); - Assert.assertEquals(factory.getCallTimeout(), 1); - Assert.assertEquals(factory.getClientFailureCheckPeriod(), 2); - Assert.assertEquals(factory.getClientID(), "myid"); - Assert.assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), "mlbcn"); - Assert.assertEquals(factory.getConnectionTTL(), 3); - Assert.assertEquals(factory.getConsumerMaxRate(), 4); - Assert.assertEquals(factory.getConsumerWindowSize(), 5); - Assert.assertEquals(factory.getDupsOKBatchSize(), 8); - Assert.assertEquals(factory.getMinLargeMessageSize(), 10); - Assert.assertEquals(factory.getProducerMaxRate(), 11); - Assert.assertEquals(factory.getConfirmationWindowSize(), 12); - Assert.assertEquals(factory.getReconnectAttempts(), 13); - Assert.assertEquals(factory.getRetryInterval(), 14); - Assert.assertEquals(factory.getRetryIntervalMultiplier(), 15d, 0.000001); - Assert.assertEquals(factory.getScheduledThreadPoolMaxSize(), 16); - Assert.assertEquals(factory.getThreadPoolMaxSize(), 17); - Assert.assertEquals(factory.getTransactionBatchSize(), 18); - Assert.assertEquals(factory.isAutoGroup(), !ActiveMQClient.DEFAULT_AUTO_GROUP); - Assert.assertEquals(factory.isBlockOnAcknowledge(), !ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); - Assert.assertEquals(factory.isBlockOnNonDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); - Assert.assertEquals(factory.isBlockOnDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); - Assert.assertEquals(factory.isPreAcknowledge(), !ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); - Assert.assertEquals(factory.isUseGlobalPools(), !ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); + assertEquals(factory.getCallTimeout(), 1); + assertEquals(factory.getClientFailureCheckPeriod(), 2); + assertEquals(factory.getClientID(), "myid"); + assertEquals(factory.getConnectionLoadBalancingPolicyClassName(), "mlbcn"); + assertEquals(factory.getConnectionTTL(), 3); + assertEquals(factory.getConsumerMaxRate(), 4); + assertEquals(factory.getConsumerWindowSize(), 5); + assertEquals(factory.getDupsOKBatchSize(), 8); + assertEquals(factory.getMinLargeMessageSize(), 10); + assertEquals(factory.getProducerMaxRate(), 11); + assertEquals(factory.getConfirmationWindowSize(), 12); + assertEquals(factory.getReconnectAttempts(), 13); + assertEquals(factory.getRetryInterval(), 14); + assertEquals(factory.getRetryIntervalMultiplier(), 15d, 0.000001); + assertEquals(factory.getScheduledThreadPoolMaxSize(), 16); + assertEquals(factory.getThreadPoolMaxSize(), 17); + assertEquals(factory.getTransactionBatchSize(), 18); + assertEquals(factory.isAutoGroup(), !ActiveMQClient.DEFAULT_AUTO_GROUP); + assertEquals(factory.isBlockOnAcknowledge(), !ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE); + assertEquals(factory.isBlockOnNonDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND); + assertEquals(factory.isBlockOnDurableSend(), !ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND); + assertEquals(factory.isPreAcknowledge(), !ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE); + assertEquals(factory.isUseGlobalPools(), !ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS); } @Test @@ -240,7 +243,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase { connectionFactoryProperties.setParsedConnectorClassNames(value); ActiveMQConnectionFactory factory = ra.getConnectionFactory(connectionFactoryProperties); ActiveMQConnectionFactory defaultFactory = ra.getDefaultActiveMQConnectionFactory(); - Assert.assertNotSame(factory, defaultFactory); + assertNotSame(factory, defaultFactory); } @Test @@ -253,12 +256,12 @@ public class ResourceAdapterTest extends ActiveMQTestBase { connectionFactoryProperties.setDiscoveryLocalBindAddress("newAddress"); ActiveMQConnectionFactory factory = ra.getConnectionFactory(connectionFactoryProperties); ActiveMQConnectionFactory defaultFactory = ra.getDefaultActiveMQConnectionFactory(); - Assert.assertNotSame(factory, defaultFactory); + assertNotSame(factory, defaultFactory); DiscoveryGroupConfiguration dc = factory.getServerLocator().getDiscoveryGroupConfiguration(); UDPBroadcastEndpointFactory udpDg = (UDPBroadcastEndpointFactory) dc.getBroadcastEndpointFactory(); - Assert.assertEquals(udpDg.getLocalBindAddress(), "newAddress"); - Assert.assertEquals(udpDg.getGroupAddress(), "myhost"); - Assert.assertEquals(udpDg.getGroupPort(), 5678); + assertEquals(udpDg.getLocalBindAddress(), "newAddress"); + assertEquals(udpDg.getGroupAddress(), "myhost"); + assertEquals(udpDg.getGroupPort(), 5678); } @Test @@ -366,7 +369,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ConnectionFactoryProperties connectionFactoryProperties = new ConnectionFactoryProperties(); try { ra.getConnectionFactory(connectionFactoryProperties); - Assert.fail("should throw exception"); + fail("should throw exception"); } catch (IllegalArgumentException e) { // pass } @@ -381,20 +384,20 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ActiveMQActivationSpec spec = new ActiveMQActivationSpec(); spec.setAcknowledgeMode("DUPS_OK_ACKNOWLEDGE"); - Assert.assertEquals("Dups-ok-acknowledge", spec.getAcknowledgeMode()); + assertEquals("Dups-ok-acknowledge", spec.getAcknowledgeMode()); spec.setSubscriptionDurability("Durable"); - Assert.assertEquals("Durable", spec.getSubscriptionDurability()); + assertEquals("Durable", spec.getSubscriptionDurability()); spec.setSubscriptionDurability("NonDurable"); - Assert.assertEquals("NonDurable", spec.getSubscriptionDurability()); + assertEquals("NonDurable", spec.getSubscriptionDurability()); final int validMaxSessionValue = 110; spec.setMaxSession(validMaxSessionValue); - Assert.assertTrue(validMaxSessionValue == spec.getMaxSession()); + assertTrue(validMaxSessionValue == spec.getMaxSession()); spec.setMaxSession(-3); - Assert.assertTrue(spec.getMaxSession() == 1); + assertTrue(spec.getMaxSession() == 1); spec = new ActiveMQActivationSpec(); ActiveMQResourceAdapter adapter = new ActiveMQResourceAdapter(); @@ -405,16 +408,16 @@ public class ResourceAdapterTest extends ActiveMQTestBase { spec.setResourceAdapter(adapter); - Assert.assertEquals("us1", spec.getUser()); - Assert.assertEquals("ps1", spec.getPassword()); + assertEquals("us1", spec.getUser()); + assertEquals("ps1", spec.getPassword()); spec.setUser("us2"); spec.setPassword("ps2"); spec.setClientID("cl2"); - Assert.assertEquals("us2", spec.getUser()); - Assert.assertEquals("ps2", spec.getPassword()); - Assert.assertEquals("cl2", spec.getClientID()); + assertEquals("us2", spec.getUser()); + assertEquals("ps2", spec.getPassword()); + assertEquals("cl2", spec.getClientID()); } @@ -461,7 +464,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ActiveMQActivation activation = new ActiveMQActivation(ra, new MessageEndpointFactory(), spec); activation.start(); - Assert.assertEquals("wrong connection count ", server.getConnectionCount(), 11); + assertEquals(server.getConnectionCount(), 11, "wrong connection count "); activation.stop(); ra.stop(); @@ -517,7 +520,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase { ActiveMQActivation activation = new ActiveMQActivation(ra, new MessageEndpointFactory(), spec); activation.start(); - Assert.assertEquals("wrong connection count ", server.getConnectionCount(), 2); + assertEquals(server.getConnectionCount(), 2, "wrong connection count "); activation.stop(); ra.stop(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/referenceable/DestinationObjectFactoryTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/referenceable/DestinationObjectFactoryTest.java index 5e21ffb7f7..8918bf2c0d 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/referenceable/DestinationObjectFactoryTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/referenceable/DestinationObjectFactoryTest.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.ra.referenceable; +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 javax.naming.Reference; import javax.naming.spi.ObjectFactory; @@ -23,8 +27,7 @@ import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.jms.client.ActiveMQDestination; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class DestinationObjectFactoryTest extends ActiveMQTestBase { @@ -38,9 +41,9 @@ public class DestinationObjectFactoryTest extends ActiveMQTestBase { Class factoryClass = Class.forName(factoryName); ObjectFactory factory = (ObjectFactory) factoryClass.newInstance(); Object object = factory.getObjectInstance(reference, null, null, null); - Assert.assertNotNull(object); - Assert.assertTrue(object instanceof ActiveMQDestination); - Assert.assertEquals(queue, object); + assertNotNull(object); + assertTrue(object instanceof ActiveMQDestination); + assertEquals(queue, object); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java index c35fa01f22..0af0d51df5 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ActiveMQBufferInputStreamTest.java @@ -16,11 +16,13 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQBufferInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ActiveMQBufferInputStreamTest extends ActiveMQTestBase { diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/AutomaticLatchTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/AutomaticLatchTest.java index 7943e5b3b9..ad06ae9794 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/AutomaticLatchTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/AutomaticLatchTest.java @@ -16,12 +16,13 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.utils.AutomaticLatch; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AutomaticLatchTest { @@ -30,11 +31,11 @@ public class AutomaticLatchTest { AtomicInteger value = new AtomicInteger(0); AutomaticLatch latch = new AutomaticLatch(1); latch.afterCompletion(() -> value.incrementAndGet()); - Assert.assertEquals(0, value.get()); + assertEquals(0, value.get()); latch.countDown(); - Assert.assertEquals(1, value.get()); + assertEquals(1, value.get()); } @Test @@ -42,20 +43,20 @@ public class AutomaticLatchTest { AtomicInteger value = new AtomicInteger(0); AutomaticLatch latch = new AutomaticLatch(0); latch.afterCompletion(() -> value.incrementAndGet()); - Assert.assertEquals(1, value.get()); + assertEquals(1, value.get()); latch.countUp(); latch.countDown(); // the previous latch completion should been cleared by now - Assert.assertEquals(1, value.get()); + assertEquals(1, value.get()); latch.afterCompletion(() -> value.addAndGet(10)); - Assert.assertEquals(11, value.get()); + assertEquals(11, value.get()); latch.countUp(); latch.countDown(); - Assert.assertEquals(11, value.get()); + assertEquals(11, value.get()); } @Test @@ -68,11 +69,11 @@ public class AutomaticLatchTest { latch.countDown(); - Assert.assertEquals((Integer)0, outcome.get(0)); - Assert.assertEquals((Integer)1, outcome.get(1)); - Assert.assertEquals((Integer)2, outcome.get(2)); + assertEquals((Integer)0, outcome.get(0)); + assertEquals((Integer)1, outcome.get(1)); + assertEquals((Integer)2, outcome.get(2)); - Assert.assertEquals(3, outcome.size()); + assertEquals(3, outcome.size()); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/EmptyListTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/EmptyListTest.java index 6052334fe5..192c33db5b 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/EmptyListTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/EmptyListTest.java @@ -16,32 +16,35 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.activemq.artemis.utils.collections.EmptyList; import org.apache.activemq.artemis.utils.collections.LinkedList; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class EmptyListTest { @Test public void testEmpty() { LinkedList stringEmpty = EmptyList.getEmptyList(); - Assert.assertEquals(0, stringEmpty.size()); + assertEquals(0, stringEmpty.size()); Iterator stringIterator = stringEmpty.iterator(); - Assert.assertFalse(stringIterator.hasNext()); + assertFalse(stringIterator.hasNext()); try { stringIterator.next(); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (NoSuchElementException e) { } try { stringEmpty.get(0); - Assert.fail("Exception expected"); + fail("Exception expected"); } catch (IndexOutOfBoundsException e) { } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java index eacd29e469..82afccdb21 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/LinkedListTest.java @@ -16,6 +16,13 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.lang.invoke.MethodHandles; import java.util.Comparator; import java.util.HashMap; @@ -36,9 +43,8 @@ import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.collections.LinkedListImpl; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; import org.apache.activemq.artemis.utils.collections.NodeStore; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,7 +56,7 @@ public class LinkedListTest extends ActiveMQTestBase { private LinkedListImpl list; @Override - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); list = new LinkedListImpl<>(integerComparator) { @@ -82,23 +88,23 @@ public class LinkedListTest extends ActiveMQTestBase { @Test public void addSorted() { - Assert.assertEquals(0, scans); // sanity check + assertEquals(0, scans); // sanity check list.addSorted(1); list.addSorted(3); list.addSorted(2); list.addSorted(0); - Assert.assertEquals(0, scans); // all adds were somewhat ordered, it shouldn't be doing any scans + assertEquals(0, scans); // all adds were somewhat ordered, it shouldn't be doing any scans validateOrder(null); - Assert.assertEquals(4, list.size()); + assertEquals(4, list.size()); } @Test public void addSortedCachedLast() { - Assert.assertEquals(0, scans); // just a sanity check + assertEquals(0, scans); // just a sanity check list.addSorted(5); list.addSorted(1); list.addSorted(3); @@ -109,10 +115,10 @@ public class LinkedListTest extends ActiveMQTestBase { list.addSorted(19); list.addSorted(7); list.addSorted(8); - Assert.assertEquals(0, scans); // no full scans should be done - Assert.assertEquals(1, (int)list.poll()); + assertEquals(0, scans); // no full scans should be done + assertEquals(1, (int)list.poll()); list.addSorted(9); - Assert.assertEquals(1, scans); // remove (poll) should clear the last added cache, a scan will be needed + assertEquals(1, scans); // remove (poll) should clear the last added cache, a scan will be needed printDebug(); validateOrder(null); @@ -121,25 +127,25 @@ public class LinkedListTest extends ActiveMQTestBase { @Test public void scanDirectionalTest() { list.addSorted(9); - Assert.assertEquals(1, list.size()); + assertEquals(1, list.size()); list.addSorted(5); - Assert.assertEquals(2, list.size()); + assertEquals(2, list.size()); list.addSorted(6); - Assert.assertEquals(3, list.size()); + assertEquals(3, list.size()); list.addSorted(2); - Assert.assertEquals(4, list.size()); + assertEquals(4, list.size()); list.addSorted(7); - Assert.assertEquals(5, list.size()); + assertEquals(5, list.size()); list.addSorted(4); - Assert.assertEquals(6, list.size()); + assertEquals(6, list.size()); list.addSorted(8); - Assert.assertEquals(7, list.size()); + assertEquals(7, list.size()); list.addSorted(1); - Assert.assertEquals(8, list.size()); + assertEquals(8, list.size()); list.addSorted(10); - Assert.assertEquals(9, list.size()); + assertEquals(9, list.size()); list.addSorted(3); - Assert.assertEquals(10, list.size()); + assertEquals(10, list.size()); printDebug(); validateOrder(null); } @@ -175,11 +181,11 @@ public class LinkedListTest extends ActiveMQTestBase { } } - Assert.assertEquals(values.size(), list.size()); + assertEquals(values.size(), list.size()); validateOrder(values); - Assert.assertEquals(0, values.size()); + assertEquals(0, values.size()); } @@ -190,8 +196,8 @@ public class LinkedListTest extends ActiveMQTestBase { Integer value = integerIterator.next(); logger.debug("Reading {}", value); if (previous != null) { - Assert.assertTrue(value + " should be > " + previous, integerComparator.compare(previous, value) > 0); - Assert.assertTrue(value + " should be > " + previous, value.intValue() > previous.intValue()); + assertTrue(integerComparator.compare(previous, value) > 0, value + " should be > " + previous); + assertTrue(value.intValue() > previous.intValue(), value + " should be > " + previous); } if (values != null) { @@ -298,19 +304,19 @@ public class LinkedListTest extends ActiveMQTestBase { for (int add = 0; add < 1000; add++) { final ObservableNode o = new ObservableNode(null, add); objs.addTail(o); - assertNotNull("prev", o.publicPrev()); - assertNull("next", o.publicNext()); + assertNotNull(o.publicPrev(), "prev"); + assertNull(o.publicNext(), "next"); } for (int remove = 0; remove < 1000; remove++) { final ObservableNode next = iter.next(); assertNotNull(next); - assertNotNull("prev", next.publicPrev()); + assertNotNull(next.publicPrev(), "prev"); //it's ok to check this, because we've *at least* 100 elements left! - assertNotNull("next", next.publicNext()); + assertNotNull(next.publicNext(), "next"); iter.remove(); - assertNull("prev", next.publicPrev()); - assertNull("next", next.publicNext()); + assertNull(next.publicPrev(), "prev"); + assertNull(next.publicNext(), "next"); } assertEquals(100, objs.size()); } @@ -319,8 +325,8 @@ public class LinkedListTest extends ActiveMQTestBase { final ObservableNode next = iter.next(); assertNotNull(next); iter.remove(); - assertNull("prev", next.publicPrev()); - assertNull("next", next.publicNext()); + assertNull(next.publicPrev(), "prev"); + assertNull(next.publicNext(), "next"); } } assertEquals(0, objs.size()); @@ -358,30 +364,30 @@ public class LinkedListTest extends ActiveMQTestBase { objs.addTail(o); } - Assert.assertEquals(1000, objs.size()); + assertEquals(1000, objs.size()); if (deferSupplier) { - Assert.assertEquals(0, nodeStore.size()); + assertEquals(0, nodeStore.size()); objs.setNodeStore(nodeStore); } else { // clear the ID supplier objs.clearID(); // and redo it - Assert.assertEquals(0, nodeStore.size()); + assertEquals(0, nodeStore.size()); nodeStore = new ListNodeStore(); objs.setNodeStore(nodeStore); - Assert.assertEquals(1000, objs.size()); + assertEquals(1000, objs.size()); } - Assert.assertEquals(1000, nodeStore.size()); + assertEquals(1000, nodeStore.size()); /** remove all even items */ for (int i = 1; i <= 1000; i += 2) { objs.removeWithID(serverID, i); } - Assert.assertEquals(500, objs.size()); - Assert.assertEquals(500, nodeStore.size()); + assertEquals(500, objs.size()); + assertEquals(500, nodeStore.size()); Iterator iterator = objs.iterator(); @@ -389,17 +395,17 @@ public class LinkedListTest extends ActiveMQTestBase { int i = 2; while (iterator.hasNext()) { ObservableNode value = iterator.next(); - Assert.assertEquals(i, value.id); + assertEquals(i, value.id); i += 2; } } for (int i = 2; i <= 1000; i += 2) { - Assert.assertNotNull(objs.removeWithID(serverID, i)); + assertNotNull(objs.removeWithID(serverID, i)); } - Assert.assertEquals(0, nodeStore.size()); - Assert.assertEquals(0, objs.size()); + assertEquals(0, nodeStore.size()); + assertEquals(0, objs.size()); } } @@ -419,7 +425,7 @@ public class LinkedListTest extends ActiveMQTestBase { for (int i = 0; i < elements; i++) { objs.addHead(new ObservableNode(serverID, i)); } - Assert.assertEquals(elements, objs.size()); + assertEquals(elements, objs.size()); CyclicBarrier barrier = new CyclicBarrier(2); @@ -471,11 +477,11 @@ public class LinkedListTest extends ActiveMQTestBase { } }); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); - Assert.assertEquals(0, objs.size()); + assertEquals(0, objs.size()); - Assert.assertEquals(0, errors.get()); + assertEquals(0, errors.get()); } finally { executor.shutdownNow(); } @@ -498,12 +504,12 @@ public class LinkedListTest extends ActiveMQTestBase { int removed = 0; for (countLoop = 0; countLoop <= 1000; countLoop++) { final ObservableNode obj = iter.next(); - Assert.assertNotNull(obj); + assertNotNull(obj); if (countLoop == 500 || countLoop == 1000) { - assertNotNull("prev", obj.publicPrev()); + assertNotNull(obj.publicPrev(), "prev"); iter.remove(); - assertNull("prev", obj.publicPrev()); - assertNull("next", obj.publicNext()); + assertNull(obj.publicPrev(), "prev"); + assertNull(obj.publicNext(), "next"); removed++; } } @@ -518,7 +524,7 @@ public class LinkedListTest extends ActiveMQTestBase { assertNotNull(obj); countLoop++; } - Assert.assertEquals(expectedSize, countLoop); + assertEquals(expectedSize, countLoop); } // it's needed to add this line here because IBM JDK calls finalize on all objects in list // before previous assert is called and fails the test, this will prevent it @@ -1533,7 +1539,7 @@ public class LinkedListTest extends ActiveMQTestBase { } for (int i = 0; i < 100; i++) { - Assert.assertEquals(i, list.get(i).intValue()); + assertEquals(i, list.get(i).intValue()); } boolean expectedException = false; @@ -1544,7 +1550,7 @@ public class LinkedListTest extends ActiveMQTestBase { expectedException = true; } - Assert.assertTrue(expectedException); + assertTrue(expectedException); } @Test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java index 4d8559fc41..36c571448e 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/MemorySizeTest.java @@ -19,13 +19,12 @@ package org.apache.activemq.artemis.tests.unit.util; import org.apache.activemq.artemis.core.message.impl.CoreMessage; import org.apache.activemq.artemis.core.server.impl.MessageReferenceImpl; import org.apache.activemq.artemis.utils.MemorySize; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; -public class MemorySizeTest extends Assert { +public class MemorySizeTest { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Test diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java index f604a2b3c0..34d1815a25 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ObjectInputStreamWithClassLoaderTest.java @@ -16,6 +16,12 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -45,13 +51,10 @@ import org.apache.activemq.artemis.tests.unit.util.deserialization.pkg1.TestClas import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.tests.util.ArtemisTestCase; import org.apache.activemq.artemis.utils.ObjectInputStreamWithClassLoader; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { - - public static ClassLoader newClassLoader(final Class... userClasses) throws Exception { Set userClassUrls = new HashSet<>(); @@ -94,7 +97,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { //Class.isAnonymousClass() call used in ObjectInputStreamWithClassLoader //need to access the enclosing class and its parent class of the obj //i.e. ActiveMQTestBase, ArtemisTestCase, and Assert. - ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest.newClassLoader(obj.getClass(), ActiveMQTestBase.class, ArtemisTestCase.class, Assert.class); + ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest.newClassLoader(obj.getClass(), ActiveMQTestBase.class, ArtemisTestCase.class); Thread.currentThread().setContextClassLoader(testClassLoader); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); @@ -102,10 +105,10 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { Object deserializedObj = ois.readObject(); - Assert.assertNotSame(obj, deserializedObj); - Assert.assertNotSame(obj.getClass(), deserializedObj.getClass()); - Assert.assertNotSame(obj.getClass().getClassLoader(), deserializedObj.getClass().getClassLoader()); - Assert.assertSame(testClassLoader, deserializedObj.getClass().getClassLoader()); + assertNotSame(obj, deserializedObj); + assertNotSame(obj.getClass(), deserializedObj.getClass()); + assertNotSame(obj.getClass().getClassLoader(), deserializedObj.getClass().getClassLoader()); + assertSame(testClassLoader, deserializedObj.getClass().getClassLoader()); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } @@ -121,7 +124,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { originalProxy.setMyInt(100); byte[] bytes = ObjectInputStreamWithClassLoaderTest.toBytes(originalProxy); - ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest.newClassLoader(this.getClass(), ActiveMQTestBase.class, ArtemisTestCase.class, Assert.class); + ClassLoader testClassLoader = ObjectInputStreamWithClassLoaderTest.newClassLoader(this.getClass(), ActiveMQTestBase.class, ArtemisTestCase.class); Thread.currentThread().setContextClassLoader(testClassLoader); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStreamWithClassLoader ois = new ObjectInputStreamWithClassLoader(bais); @@ -141,7 +144,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyList() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); try { outputStream.writeObject(new TestClass1()); @@ -173,7 +176,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { assertTrue(result instanceof ClassNotFoundException); denyList = "org.apache.activemq.artemis.tests.unit.util.deserialization.pkg2"; - result = readSerializedObject(null, denyList, serailizeFile); + result = readSerializedObject(null, denyList,serailizeFile); assertNull(result); denyList = "some.other.package"; @@ -218,7 +221,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListAgainstArrayObject() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); TestClass1[] sourceObject = new TestClass1[]{new TestClass1()}; ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); @@ -253,7 +256,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListAgainstListObject() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); List sourceObject = new ArrayList<>(); sourceObject.add(new TestClass1()); @@ -296,7 +299,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListAgainstListMapObject() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); Map sourceObject = new HashMap<>(); sourceObject.put(new TestClass1(), new TestClass2()); @@ -362,7 +365,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListAnonymousObject() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); try { Serializable object = EnclosingClass.anonymousObject; @@ -392,7 +395,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListLocalObject() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); try { Object object = EnclosingClass.getLocalObject(); @@ -423,7 +426,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testDeprecatedWhiteBlackListSystemProperty() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); try { outputStream.writeObject(new TestClass1()); @@ -438,8 +441,8 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { ObjectInputStreamWithClassLoader ois = new ObjectInputStreamWithClassLoader(new FileInputStream(serailizeFile)); String bList = ois.getDenyList(); String wList = ois.getAllowList(); - assertEquals("wrong black list: " + bList, "system.defined.black.list", bList); - assertEquals("wrong white list: " + wList, "system.defined.white.list", wList); + assertEquals("system.defined.black.list", bList, "wrong black list: " + bList); + assertEquals("system.defined.white.list", wList, "wrong white list: " + wList); ois.close(); } finally { System.clearProperty(ObjectInputStreamWithClassLoader.BLACKLIST_PROPERTY); @@ -450,7 +453,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { @Test public void testAllowDenyListSystemProperty() throws Exception { - File serailizeFile = new File(temporaryFolder.getRoot(), "testclass.bin"); + File serailizeFile = new File(temporaryFolder, "testclass.bin"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(serailizeFile)); try { outputStream.writeObject(new TestClass1()); @@ -465,8 +468,8 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { ObjectInputStreamWithClassLoader ois = new ObjectInputStreamWithClassLoader(new FileInputStream(serailizeFile)); String bList = ois.getDenyList(); String wList = ois.getAllowList(); - assertEquals("wrong deny list: " + bList, "system.defined.deny.list", bList); - assertEquals("wrong allow list: " + wList, "system.defined.allow.list", wList); + assertEquals("system.defined.deny.list", bList, "wrong deny list: " + bList); + assertEquals("system.defined.allow.list", wList, "wrong allow list: " + wList); ois.close(); } finally { System.clearProperty(ObjectInputStreamWithClassLoader.DENYLIST_PROPERTY); @@ -548,7 +551,7 @@ public class ObjectInputStreamWithClassLoaderTest extends ActiveMQTestBase { } private static byte[] toBytes(final Object obj) throws IOException { - Assert.assertTrue(obj instanceof Serializable); + assertTrue(obj instanceof Serializable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java index 1ce7c67d5f..a902797f08 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/ReusableLatchTest.java @@ -16,15 +16,19 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.invoke.MethodHandles; import java.util.concurrent.CountDownLatch; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ReusableLatch; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.invoke.MethodHandles; public class ReusableLatchTest extends ActiveMQTestBase { @@ -47,13 +51,13 @@ public class ReusableLatchTest extends ActiveMQTestBase { for (int i = 1; i <= 100; i++) { latch.countUp(); - Assert.assertEquals(i, latch.getCount()); + assertEquals(i, latch.getCount()); } for (int i = 100; i > 0; i--) { - Assert.assertEquals(i, latch.getCount()); + assertEquals(i, latch.getCount()); latch.countDown(); - Assert.assertEquals(i - 1, latch.getCount()); + assertEquals(i - 1, latch.getCount()); } latch.await(); @@ -143,10 +147,10 @@ public class ReusableLatchTest extends ActiveMQTestBase { } for (int i = 0; i < numberOfThreads; i++) { - Assert.assertTrue(waits[i].waiting); + assertTrue(waits[i].waiting); } - Assert.assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount()); + assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount()); class ThreadDown extends Thread { @@ -192,10 +196,10 @@ public class ReusableLatchTest extends ActiveMQTestBase { down[i].join(); } - Assert.assertEquals(1, latch.getCount()); + assertEquals(1, latch.getCount()); for (int i = 0; i < numberOfThreads; i++) { - Assert.assertTrue(waits[i].waiting); + assertTrue(waits[i].waiting); } latch.countDown(); @@ -204,10 +208,10 @@ public class ReusableLatchTest extends ActiveMQTestBase { waits[i].join(); } - Assert.assertEquals(0, latch.getCount()); + assertEquals(0, latch.getCount()); for (int i = 0; i < numberOfThreads; i++) { - Assert.assertFalse(waits[i].waiting); + assertFalse(waits[i].waiting); } } @@ -249,15 +253,15 @@ public class ReusableLatchTest extends ActiveMQTestBase { t.readyLatch.await(); - Assert.assertEquals(true, t.waiting); + assertTrue(t.waiting); latch.countDown(); t.join(); - Assert.assertEquals(false, t.waiting); + assertFalse(t.waiting); - Assert.assertNull(t.e); + assertNull(t.e); latch.countUp(); @@ -266,23 +270,23 @@ public class ReusableLatchTest extends ActiveMQTestBase { t.readyLatch.await(); - Assert.assertEquals(true, t.waiting); + assertTrue(t.waiting); latch.countDown(); t.join(); - Assert.assertEquals(false, t.waiting); + assertFalse(t.waiting); - Assert.assertNull(t.e); + assertNull(t.e); - Assert.assertTrue(latch.await(1000)); + assertTrue(latch.await(1000)); - Assert.assertEquals(0, latch.getCount()); + assertEquals(0, latch.getCount()); latch.countDown(); - Assert.assertEquals(0, latch.getCount()); + assertEquals(0, latch.getCount()); } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java index 8c56b0a88c..18818c16d8 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UTF8Test.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -30,9 +34,8 @@ import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.DataConstants; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.UTF8Util; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class UTF8Test extends ActiveMQTestBase { @@ -56,7 +59,7 @@ public class UTF8Test extends ActiveMQTestBase { final int encodedSize = buffer.readUnsignedShort(); final byte[] realEncodedBytes = new byte[encodedSize]; buffer.getBytes(buffer.readerIndex(), realEncodedBytes); - Assert.assertArrayEquals(expectedBytes, realEncodedBytes); + assertArrayEquals(expectedBytes, realEncodedBytes); } @Test @@ -73,7 +76,7 @@ public class UTF8Test extends ActiveMQTestBase { String newStr = UTF8Util.readUTF(buffer); - Assert.assertEquals(str, newStr); + assertEquals(str, newStr); } @Test @@ -103,7 +106,7 @@ public class UTF8Test extends ActiveMQTestBase { String newStr = data.readUTF(); - Assert.assertEquals(str, newStr); + assertEquals(str, newStr); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(byteOut); @@ -114,7 +117,7 @@ public class UTF8Test extends ActiveMQTestBase { newStr = UTF8Util.readUTF(buffer); - Assert.assertEquals(str, newStr); + assertEquals(str, newStr); } @Test @@ -132,11 +135,11 @@ public class UTF8Test extends ActiveMQTestBase { try { UTF8Util.saveUTF(buffer.byteBuf(), str); - Assert.fail("String is too big, supposed to throw an exception"); + fail("String is too big, supposed to throw an exception"); } catch (Exception ignored) { } - Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex()); + assertEquals(0, buffer.writerIndex(), "A buffer was supposed to be untouched since the string was too big"); chars = new char[25000]; @@ -148,11 +151,11 @@ public class UTF8Test extends ActiveMQTestBase { try { UTF8Util.saveUTF(buffer.byteBuf(), str); - Assert.fail("Encoded String is too big, supposed to throw an exception"); + fail("Encoded String is too big, supposed to throw an exception"); } catch (Exception ignored) { } - Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex()); + assertEquals(0, buffer.writerIndex(), "A buffer was supposed to be untouched since the string was too big"); // Testing a string right on the limit chars = new char[0xffff]; @@ -165,16 +168,16 @@ public class UTF8Test extends ActiveMQTestBase { UTF8Util.saveUTF(buffer.byteBuf(), str); - Assert.assertEquals(0xffff + DataConstants.SIZE_SHORT, buffer.writerIndex()); + assertEquals(0xffff + DataConstants.SIZE_SHORT, buffer.writerIndex()); String newStr = UTF8Util.readUTF(buffer); - Assert.assertEquals(str, newStr); + assertEquals(str, newStr); } @Override - @After + @AfterEach public void tearDown() throws Exception { UTF8Util.clearBuffer(); super.tearDown(); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java index cb93c0cad5..4ddd5b7401 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDGeneratorTest.java @@ -16,10 +16,14 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; @@ -48,21 +52,21 @@ public class UUIDGeneratorTest extends ActiveMQTestBase { org.apache.activemq.artemis.utils.UUID nativeId = gen.generateUUID(); uuidSet.add(nativeId); } - assertEquals("All there", numIterations, uuidSet.size()); + assertEquals(numIterations, uuidSet.size(), "All there"); } @Test public void testGetHardwareAddress() throws Exception { byte[] bytes = UUIDGenerator.getHardwareAddress(); - Assert.assertNotNull(bytes); - Assert.assertTrue(bytes.length == 6); + assertNotNull(bytes); + assertTrue(bytes.length == 6); } @Test public void testZeroPaddedBytes() throws Exception { - Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(null)); - Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[0])); - Assert.assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[7])); + assertNull(UUIDGenerator.getZeroPaddedSixBytes(null)); + assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[0])); + assertNull(UUIDGenerator.getZeroPaddedSixBytes(new byte[7])); byte[] fiveBytes = new byte[]{1, 2, 3, 4, 5}; byte[] zeroPaddedFiveBytes = UUIDGenerator.getZeroPaddedSixBytes(fiveBytes); diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java index 6aff0c3963..359ecda455 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/UUIDTest.java @@ -16,14 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.HashSet; import java.util.Set; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class UUIDTest extends ActiveMQTestBase { @@ -39,7 +40,7 @@ public class UUIDTest extends ActiveMQTestBase { } // we put them in a set to check duplicates - Assert.assertEquals(getTimes(), uuidsSet.size()); + assertEquals(getTimes(), uuidsSet.size()); } protected int getTimes() { @@ -55,8 +56,8 @@ public class UUIDTest extends ActiveMQTestBase { byte[] data2 = UUID.stringToBytes(uuidString); final UUID uuid2 = new UUID(UUID.TYPE_TIME_BASED, data2); assertEqualsByteArrays(uuid.asBytes(), data2); - assertEquals(uuidString, uuid, uuid2); - assertEquals(uuidString, uuidString, uuid2.toString()); + assertEquals(uuid, uuid2, uuidString); + assertEquals(uuidString, uuid2.toString(), uuidString); } } } diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java index 758d505084..08a3e4de4c 100644 --- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java +++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/util/VersionLoaderTest.java @@ -16,14 +16,15 @@ */ package org.apache.activemq.artemis.tests.unit.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; import java.util.StringTokenizer; import org.apache.activemq.artemis.core.version.Version; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.VersionLoader; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class VersionLoaderTest extends ActiveMQTestBase { @@ -35,12 +36,12 @@ public class VersionLoaderTest extends ActiveMQTestBase { Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream(VersionLoader.DEFAULT_PROP_FILE_NAME)); - Assert.assertEquals(props.get("activemq.version.versionName"), version.getVersionName()); + assertEquals(props.get("activemq.version.versionName"), version.getVersionName()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.majorVersion")), version.getMajorVersion()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.minorVersion")), version.getMinorVersion()); - Assert.assertEquals(Integer.parseInt(props.getProperty("activemq.version.microVersion")), version.getMicroVersion()); - Assert.assertEquals(Integer.parseInt(new StringTokenizer(props.getProperty("activemq.version.incrementingVersion"), ",").nextToken()), version.getIncrementingVersion()); + assertEquals(Integer.parseInt(props.getProperty("activemq.version.majorVersion")), version.getMajorVersion()); + assertEquals(Integer.parseInt(props.getProperty("activemq.version.minorVersion")), version.getMinorVersion()); + assertEquals(Integer.parseInt(props.getProperty("activemq.version.microVersion")), version.getMicroVersion()); + assertEquals(Integer.parseInt(new StringTokenizer(props.getProperty("activemq.version.incrementingVersion"), ",").nextToken()), version.getIncrementingVersion()); } }