ARTEMIS-4790: use JUnit 5 for the tests

This commit is contained in:
Robbie Gemmell 2024-06-03 13:14:01 +01:00 committed by Justin Bertram
parent b9bb494b58
commit 362dbd11ac
1570 changed files with 32173 additions and 26021 deletions

View File

@ -80,8 +80,9 @@
<artifactId>arquillian-junit-core</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.jms</groupId>

View File

@ -150,8 +150,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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 {

View File

@ -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<Object[]> 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)));
}
/**

View File

@ -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");
}

View File

@ -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);

View File

@ -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");
}

View File

@ -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<ManagementContext, ActiveMQServer>)startServer()).getB();
}
@After
@AfterEach
@Override
public void tearDown() throws Exception {
stopServer();

View File

@ -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);
}

View File

@ -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<String, String> 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<String, String> 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(" "));
}
}

View File

@ -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) {
}
}

View File

@ -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);

View File

@ -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/<TestClassName>/<generated>
@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) {

View File

@ -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()));
}

View File

@ -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);

View File

@ -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());

View File

@ -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<Message> generateTextMessages(Session session, Destination destination) throws Exception {

View File

@ -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();

View File

@ -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();
}
}

View File

@ -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);

View File

@ -67,7 +67,6 @@
<artifactId>log4j-slf4j2-impl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
@ -81,8 +80,13 @@
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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());
}
}

View File

@ -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

View File

@ -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();
}

View File

@ -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<byte[], Integer> 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<byte[], Integer> 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<byte[]> 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,8 +265,9 @@ public class ByteUtilTest {
shouldZeroesByteBuffer(buffer, offset, bytes);
}
@Test(expected = ReadOnlyBufferException.class)
@Test
public void shouldFailWithReadOnlyHeapByteBuffer() {
assertThrows(ReadOnlyBufferException.class, () -> {
final byte one = (byte) 1;
final int capacity = 64;
final int bytes = 32;
@ -273,10 +276,12 @@ public class ByteUtilTest {
fill(buffer, 0, capacity, one);
buffer = buffer.asReadOnlyBuffer();
shouldZeroesByteBuffer(buffer, offset, bytes);
});
}
@Test(expected = IndexOutOfBoundsException.class)
@Test
public void shouldFailIfOffsetIsGreaterOrEqualHeapByteBufferCapacity() {
assertThrows(IndexOutOfBoundsException.class, () -> {
final byte one = (byte) 1;
final int capacity = 64;
final int bytes = 0;
@ -290,13 +295,15 @@ public class ByteUtilTest {
final byte[] originalContent = duplicateRemaining(buffer, 0, 0);
final byte[] expectedContent = new byte[capacity];
Arrays.fill(expectedContent, one);
Assert.assertArrayEquals(expectedContent, originalContent);
assertArrayEquals(expectedContent, originalContent);
throw expectedEx;
}
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldFailIfOffsetIsNegative() {
assertThrows(IllegalArgumentException.class, () -> {
final byte one = (byte) 1;
final int capacity = 64;
final int bytes = 1;
@ -310,13 +317,15 @@ public class ByteUtilTest {
final byte[] originalContent = duplicateRemaining(buffer, 0, 0);
final byte[] expectedContent = new byte[capacity];
Arrays.fill(expectedContent, one);
Assert.assertArrayEquals(expectedContent, originalContent);
assertArrayEquals(expectedContent, originalContent);
throw expectedEx;
}
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldFailIfBytesIsNegative() {
assertThrows(IllegalArgumentException.class, () -> {
final byte one = (byte) 1;
final int capacity = 64;
final int bytes = -1;
@ -330,13 +339,15 @@ public class ByteUtilTest {
final byte[] originalContent = duplicateRemaining(buffer, 0, 0);
final byte[] expectedContent = new byte[capacity];
Arrays.fill(expectedContent, one);
Assert.assertArrayEquals(expectedContent, originalContent);
assertArrayEquals(expectedContent, originalContent);
throw expectedEx;
}
});
}
@Test(expected = IndexOutOfBoundsException.class)
@Test
public void shouldFailIfExceedingHeapByteBufferCapacity() {
assertThrows(IndexOutOfBoundsException.class, () -> {
final byte one = (byte) 1;
final int capacity = 64;
final int bytes = 65;
@ -350,9 +361,10 @@ public class ByteUtilTest {
final byte[] originalContent = duplicateRemaining(buffer, 0, 0);
final byte[] expectedContent = new byte[capacity];
Arrays.fill(expectedContent, one);
Assert.assertArrayEquals(expectedContent, originalContent);
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() {
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());
}
}

View File

@ -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<String> 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<String> 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();

View File

@ -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));

View File

@ -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<Object[]> 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);

View File

@ -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 {

View File

@ -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 {

View File

@ -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<Object[]> 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);

View File

@ -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);
}
}

View File

@ -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() {

View File

@ -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 {
assertThrows(IllegalArgumentException.class, () -> {
PasswordMaskingUtil.getCodec("codec doesn't exist");
});
}
}

View File

@ -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));
}
}

View File

@ -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 {

View File

@ -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);
}

View File

@ -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 {

View File

@ -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());
}
}

View File

@ -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<String> 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<String> 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

View File

@ -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/<TestClassName>/<generated>
@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);

View File

@ -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

View File

@ -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));
}
}

View File

@ -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<SimpleString> 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,27 +291,30 @@ 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() {
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() {
assertThrows(IndexOutOfBoundsException.class, () -> {
final int expectedLength = Integer.BYTES + Byte.BYTES + Integer.BYTES;
ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength);
buf.writeByte(DataConstants.NOT_NULL);
@ -311,10 +323,12 @@ public class TypedPropertiesTest {
buf.writeInt(2);
buf.resetReaderIndex();
searchProperty(SimpleString.toSimpleString("a"), buf, 0);
});
}
@Test(expected = IllegalStateException.class)
@Test
public void testSearchWithInvalidTypeBeforeEnd() {
assertThrows(IllegalStateException.class, () -> {
ByteBuf buf = Unpooled.buffer();
buf.writeByte(DataConstants.NOT_NULL);
// fake 2 properties
@ -326,6 +340,7 @@ public class TypedPropertiesTest {
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());
}
}

View File

@ -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<String, String> 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);
}

View File

@ -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));
}
}

View File

@ -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<String, Boolean> 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<String, Boolean> 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<String, Boolean> 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);
}
}
}

View File

@ -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();
}

View File

@ -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();
}

View File

@ -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 {

View File

@ -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() {
assertThrows(IllegalArgumentException.class, () -> {
new ConcurrentAppendOnlyChunkedList<>(3);
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldFailToCreateNegativeChunkSizeCollection() {
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,12 +155,13 @@ 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() {
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
final int messages = ELEMENTS;
final Integer[] elements = new Integer[messages];
for (int i = 0;i < messages;i++) {
@ -162,16 +171,21 @@ public class ConcurrentAppendOnlyChunkedListTest {
}
final int offset = 10;
chunkedList.toArray(size -> new Integer[offset + size - 1], offset);
});
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
@Test
public void shouldFailToArrayWithNegativeStartIndex() {
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
chunkedList.toArray(Integer[]::new, -1);
});
}
@Test(expected = NullPointerException.class)
@Test
public void shouldFailToArrayWithNullArray() {
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);
}
}

View File

@ -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 {

View File

@ -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 {

View File

@ -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 <a href="https://github.com/real-logic/agrona/blob/master/agrona/src/test/java/org/agrona/collections/IntHashSetTest.java">Agrona IntHashSetTest</a>
@ -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,15 +142,18 @@ public class LongHashSetTest {
assertIteratorHasElementsWithoutHasNext();
}
@Test(expected = NoSuchElementException.class)
@Test
public void iteratorsThrowNoSuchElementException() {
assertThrows(NoSuchElementException.class, () -> {
addTwoElements(testSet);
exhaustIterator();
});
}
@Test(expected = NoSuchElementException.class)
@Test
public void iteratorsThrowNoSuchElementExceptionFromTheBeginningEveryTime() {
assertThrows(NoSuchElementException.class, () -> {
addTwoElements(testSet);
try {
@ -153,16 +162,19 @@ public class LongHashSetTest {
}
exhaustIterator();
});
}
@Test
public void iteratorHasNoElements() {
Assert.assertFalse(testSet.iterator().hasNext());
assertFalse(testSet.iterator().hasNext());
}
@Test(expected = NoSuchElementException.class)
@Test
public void iteratorThrowExceptionForEmptySet() {
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() {
assertThrows(ArrayStoreException.class, () -> {
testSet.toArray(new String[1]);
});
}
@Test(expected = NullPointerException.class)
@Test
public void toArrayThrowsNullPointerExceptionForNullArgument() {
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<Long> 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<Long> 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<Long>()));
assertFalse(testSet.removeAll(new LongHashSet(100)));
assertFalse(testSet.removeAll(new HashSet<Long>()));
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<Long>()));
assertFalse(testSet.removeAll(disjoint));
assertFalse(testSet.removeAll(new HashSet<Long>()));
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<Long> 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<Long> other) {
Assert.assertTrue(other.contains(1L));
Assert.assertTrue(other.contains(1001L));
assertTrue(other.contains(1L));
assertTrue(other.contains(1001L));
}
private void exhaustIterator() {

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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() {
assertThrows(IllegalArgumentException.class, () -> {
new SparseArrayLinkedList<>(0);
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldFailToCreateNegativeArrayCapacityCollection() {
assertThrows(IllegalArgumentException.class, () -> {
new SparseArrayLinkedList<>(-1);
});
}
@Test(expected = NullPointerException.class)
@Test
public void shouldFailToAddNull() {
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<Integer> 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<Integer> 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<Integer> 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));
}
}

View File

@ -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 {

View File

@ -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();
}

View File

@ -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());
}
}

View File

@ -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);

View File

@ -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<AtomicRunnable> 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

View File

@ -62,8 +62,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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);

View File

@ -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"));
}
}

View File

@ -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<String, Object>(), null);
TransportConfiguration configuration2 = new TransportConfiguration("SomeClass", new HashMap<String, Object>(), null);
Assert.assertEquals(configuration, configuration2);
Assert.assertEquals(configuration.hashCode(), configuration2.hashCode());
assertEquals(configuration, configuration2);
assertEquals(configuration.hashCode(), configuration2.hashCode());
HashMap<String, Object> 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<String, Object> params = Collections.emptyMap();
final Map<String, Object> 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);
}
}

View File

@ -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());
}
}

View File

@ -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<Object[]> 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");
}
}
}

View File

@ -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<Object[]> 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)));

View File

@ -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);
}
}

View File

@ -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) {

View File

@ -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)));

View File

@ -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

View File

@ -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");
}
}

View File

@ -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());
}

View File

@ -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) {

View File

@ -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 {

View File

@ -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"));
}
}

View File

@ -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);
}
}
}

View File

@ -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 {

View File

@ -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<String, Object> 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<String, Object> values = new HashMap<>();
values.put("test", "zzz");
Assert.assertEquals(3L, ConfigurationHelper.getLongProperty("test", 3L, values));
assertEquals(3L, ConfigurationHelper.getLongProperty("test", 3L, values));
}
}

View File

@ -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 {

View File

@ -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) {

View File

@ -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 <b>
@ -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 = "<![CDATA[somedata]]>";
String stripped = XMLUtil.stripCDATA(xml);
Assert.assertEquals("somedata", stripped);
assertEquals("somedata", stripped);
}
}

View File

@ -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() {
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);
});
}
}

View File

@ -61,8 +61,13 @@
<version>${jakarta.activation-api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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());
}
}

View File

@ -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);
}
}

View File

@ -47,9 +47,13 @@
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<!-- The johnzon-core and json-api contents are repackaged in -commons,

View File

@ -25,7 +25,7 @@ import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
import org.apache.activemq.artemis.core.server.embedded.Main;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -73,8 +73,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -97,8 +97,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -90,8 +90,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -72,8 +72,13 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -80,8 +80,13 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -16,6 +16,11 @@
*/
package org.apache.activemq.artemis.jdbc.store.file;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.sql.DriverManager;
import java.sql.SQLException;
@ -44,27 +49,19 @@ import org.apache.activemq.artemis.jdbc.store.drivers.JDBCConnectionProvider;
import org.apache.activemq.artemis.jdbc.store.drivers.JDBCDataSourceUtils;
import org.apache.activemq.artemis.jdbc.store.drivers.JDBCUtils;
import org.apache.activemq.artemis.jdbc.store.sql.SQLProvider;
import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension;
import org.apache.activemq.artemis.tests.extensions.parameterized.Parameter;
import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters;
import org.apache.activemq.artemis.tests.util.ArtemisTestCase;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ThreadLeakCheckRule;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
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.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class JDBCSequentialFileFactoryTest {
@Rule
public ThreadLeakCheckRule leakCheckRule = new ThreadLeakCheckRule();
@ExtendWith(ParameterizedTestExtension.class)
public class JDBCSequentialFileFactoryTest extends ArtemisTestCase {
private static String className = EmbeddedDriver.class.getCanonicalName();
@ -74,17 +71,18 @@ public class JDBCSequentialFileFactoryTest {
private ScheduledExecutorService scheduledExecutorService;
@Parameterized.Parameter
@Parameter(index = 0)
public boolean useAuthentication;
private String user = null;
private String password = null;
@Parameterized.Parameters(name = "authentication = {0}")
@Parameters(name = "authentication = {0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{false}, {true}});
}
@Before
@BeforeEach
public void setup() throws Exception {
executor = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()));
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()));
@ -109,15 +107,18 @@ public class JDBCSequentialFileFactoryTest {
factory.start();
}
@After
@AfterEach
public void tearDown() throws Exception {
try {
executor.shutdown();
scheduledExecutorService.shutdown();
factory.destroy();
} finally {
shutdownDerby();
}
}
@After
public void shutdownDerby() {
private void shutdownDerby() {
try {
if (useAuthentication) {
DriverManager.getConnection("jdbc:derby:;shutdown=true", user, password);
@ -132,12 +133,12 @@ public class JDBCSequentialFileFactoryTest {
}
}
@Test
@TestTemplate
public void testJDBCFileFactoryStarted() throws Exception {
assertTrue(factory.isStarted());
}
@Test
@TestTemplate
public void testReadZeroBytesOnEmptyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
@ -150,7 +151,7 @@ public class JDBCSequentialFileFactoryTest {
}
}
@Test
@TestTemplate
public void testReadZeroBytesOnNotEmptyFile() throws Exception {
final int fileLength = 8;
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
@ -166,7 +167,7 @@ public class JDBCSequentialFileFactoryTest {
}
}
@Test
@TestTemplate
public void testReadOutOfBoundsOnEmptyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
@ -174,13 +175,13 @@ public class JDBCSequentialFileFactoryTest {
final ByteBuffer readBuffer = ByteBuffer.allocate(1);
file.position(1);
final int bytes = file.read(readBuffer);
assertTrue("bytes read should be < 0", bytes < 0);
assertTrue(bytes < 0, "bytes read should be < 0");
} finally {
file.close();
}
}
@Test
@TestTemplate
public void testReadOutOfBoundsOnNotEmptyFile() throws Exception {
final int fileLength = 8;
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
@ -191,13 +192,13 @@ public class JDBCSequentialFileFactoryTest {
file.position(fileLength + 1);
final ByteBuffer readBuffer = ByteBuffer.allocate(fileLength);
final int bytes = file.read(readBuffer);
assertTrue("bytes read should be < 0", bytes < 0);
assertTrue(bytes < 0, "bytes read should be < 0");
} finally {
file.close();
}
}
@Test
@TestTemplate
public void testCreateFiles() throws Exception {
int noFiles = 100;
List<SequentialFile> files = new LinkedList<>();
@ -219,10 +220,10 @@ public class JDBCSequentialFileFactoryTest {
file.close();
}
Assert.assertEquals(0, factory.getNumberOfOpenFiles());
assertEquals(0, factory.getNumberOfOpenFiles());
}
@Test
@TestTemplate
public void testAsyncAppendToFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
@ -242,7 +243,7 @@ public class JDBCSequentialFileFactoryTest {
checkData(file, src);
}
@Test
@TestTemplate
public void testWriteToFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
@ -268,7 +269,7 @@ public class JDBCSequentialFileFactoryTest {
assertEquals(bufferSize, file.size());
}
@Test
@TestTemplate
public void testCopyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
@ -293,7 +294,7 @@ public class JDBCSequentialFileFactoryTest {
assertEquals(bufferSize, file.size());
}
@Test
@TestTemplate
public void testCloneFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
@ -324,7 +325,7 @@ public class JDBCSequentialFileFactoryTest {
*
* @throws Exception
*/
@Test
@TestTemplate
public void testGetFileSizeWorksWhenNotOpen() throws Exception {
// Create test file with some data.
int testFileSize = 1024;

View File

@ -16,6 +16,9 @@
*/
package org.apache.activemq.artemis.jdbc.store.file;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
@ -37,9 +40,8 @@ import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class PostgresLargeObjectManagerTest {

Some files were not shown because too many files have changed in this diff Show More