diff --git a/hadoop-common-project/hadoop-common/pom.xml b/hadoop-common-project/hadoop-common/pom.xml
index 1d9fc166c745a..91fe4b91f3414 100644
--- a/hadoop-common-project/hadoop-common/pom.xml
+++ b/hadoop-common-project/hadoop-common/pom.xml
@@ -219,6 +219,11 @@
mockito-inline
test
+
+ org.mockito
+ mockito-junit-jupiter
+ test
+
org.apache.avro
avro
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/DummySharedResource.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/DummySharedResource.java
index a7cf41dd997ec..a2fbd15f5c36d 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/DummySharedResource.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/DummySharedResource.java
@@ -17,7 +17,7 @@
*/
package org.apache.hadoop.ha;
-import org.junit.Assert;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A fake shared resource, for use in automatic failover testing.
@@ -47,6 +47,6 @@ public synchronized void release(DummyHAService oldHolder) {
}
public synchronized void assertNoViolations() {
- Assert.assertEquals(0, violations);
+ assertEquals(0, violations);
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/MiniZKFCCluster.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/MiniZKFCCluster.java
index 8d3075f45263b..1f5bf0779fdeb 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/MiniZKFCCluster.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/MiniZKFCCluster.java
@@ -17,8 +17,8 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.InetSocketAddress;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElector.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElector.java
index e8c57f1efd717..b63eb3089d05a 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElector.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElector.java
@@ -36,9 +36,8 @@
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.Assert;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -49,7 +48,13 @@
import org.apache.hadoop.util.ZKUtil.ZKAuthInfo;
import org.apache.hadoop.test.GenericTestUtils;
-import static org.mockito.ArgumentMatchers.any;
+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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.any;
public class TestActiveStandbyElector {
@@ -92,7 +97,7 @@ protected void sleepFor(int ms) {
private static final String ZK_BREADCRUMB_NAME = ZK_PARENT_NAME + "/" +
ActiveStandbyElector.BREADCRUMB_FILENAME;
- @Before
+ @BeforeEach
public void init() throws IOException, KeeperException {
count = 0;
mockZK = Mockito.mock(ZooKeeper.class);
@@ -123,9 +128,10 @@ private void mockPriorActive(byte[] data) throws Exception {
/**
* verify that joinElection checks for null data
*/
- @Test(expected = HadoopIllegalArgumentException.class)
+ @Test
public void testJoinElectionException() {
- elector.joinElection(null);
+ assertThrows(HadoopIllegalArgumentException.class,
+ () -> elector.joinElection(null));
}
/**
@@ -177,7 +183,7 @@ public void testCreateNodeResultBecomeActive() throws Exception {
public void testFailToBecomeActive() throws Exception {
mockNoPriorActive();
elector.joinElection(data);
- Assert.assertEquals(0, elector.sleptFor);
+ assertEquals(0, elector.sleptFor);
Mockito.doThrow(new ServiceFailedException("failed to become active"))
.when(mockApp).becomeActive();
@@ -189,8 +195,8 @@ public void testFailToBecomeActive() throws Exception {
// should re-join
Mockito.verify(mockZK, Mockito.times(2)).create(ZK_LOCK_NAME, data,
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);
- Assert.assertEquals(2, count);
- Assert.assertTrue(elector.sleptFor > 0);
+ assertEquals(2, count);
+ assertTrue(elector.sleptFor > 0);
}
/**
@@ -202,7 +208,7 @@ public void testFailToBecomeActive() throws Exception {
public void testFailToBecomeActiveAfterZKDisconnect() throws Exception {
mockNoPriorActive();
elector.joinElection(data);
- Assert.assertEquals(0, elector.sleptFor);
+ assertEquals(0, elector.sleptFor);
elector.processResult(Code.CONNECTIONLOSS.intValue(), ZK_LOCK_NAME, mockZK,
ZK_LOCK_NAME);
@@ -226,8 +232,8 @@ public void testFailToBecomeActiveAfterZKDisconnect() throws Exception {
// should re-join
Mockito.verify(mockZK, Mockito.times(3)).create(ZK_LOCK_NAME, data,
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);
- Assert.assertEquals(2, count);
- Assert.assertTrue(elector.sleptFor > 0);
+ assertEquals(2, count);
+ assertTrue(elector.sleptFor > 0);
}
@@ -331,7 +337,7 @@ public void testCreateNodeResultRetryBecomeActive() throws Exception {
elector.joinElection(data);
// recreate connection via getNewZooKeeper
- Assert.assertEquals(2, count);
+ assertEquals(2, count);
elector.processResult(Code.CONNECTIONLOSS.intValue(), ZK_LOCK_NAME, mockZK,
ZK_LOCK_NAME);
elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK,
@@ -457,10 +463,10 @@ public void testProcessCallbackEventNone() throws Exception {
Event.KeeperState.SyncConnected);
elector.processWatchEvent(mockZK, mockEvent);
verifyExistCall(1);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
elector.processResult(Code.SESSIONEXPIRED.intValue(), ZK_LOCK_NAME,
mockZK, new Stat());
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
// session expired should enter safe mode and initiate re-election
// re-election checked via checking re-creation of new zookeeper and
@@ -471,7 +477,7 @@ public void testProcessCallbackEventNone() throws Exception {
Mockito.verify(mockApp, Mockito.times(1)).enterNeutralMode();
// called getNewZooKeeper to create new session. first call was in
// constructor
- Assert.assertEquals(2, count);
+ assertEquals(2, count);
// once in initial joinElection and one now
Mockito.verify(mockZK, Mockito.times(2)).create(ZK_LOCK_NAME, data,
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);
@@ -504,13 +510,13 @@ public void testProcessCallbackEventNode() throws Exception {
ZK_LOCK_NAME);
Mockito.verify(mockApp, Mockito.times(1)).becomeStandby();
verifyExistCall(1);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
Stat stat = new Stat();
stat.setEphemeralOwner(0L);
Mockito.when(mockZK.getSessionId()).thenReturn(1L);
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class);
Mockito.when(mockEvent.getPath()).thenReturn(ZK_LOCK_NAME);
@@ -520,18 +526,18 @@ public void testProcessCallbackEventNode() throws Exception {
Event.EventType.NodeDataChanged);
elector.processWatchEvent(mockZK, mockEvent);
verifyExistCall(2);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
// monitoring should be setup again after event is received
Mockito.when(mockEvent.getType()).thenReturn(
Event.EventType.NodeChildrenChanged);
elector.processWatchEvent(mockZK, mockEvent);
verifyExistCall(3);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
// lock node deletion when in standby mode should create znode again
// successful znode creation enters active state and sets monitor
@@ -546,10 +552,10 @@ public void testProcessCallbackEventNode() throws Exception {
ZK_LOCK_NAME);
Mockito.verify(mockApp, Mockito.times(1)).becomeActive();
verifyExistCall(4);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
stat.setEphemeralOwner(1L);
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
// lock node deletion in active mode should enter neutral mode and create
// znode again successful znode creation enters active state and sets
@@ -564,9 +570,9 @@ public void testProcessCallbackEventNode() throws Exception {
ZK_LOCK_NAME);
Mockito.verify(mockApp, Mockito.times(2)).becomeActive();
verifyExistCall(5);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
// bad path name results in fatal error
Mockito.when(mockEvent.getPath()).thenReturn(null);
@@ -574,7 +580,7 @@ public void testProcessCallbackEventNode() throws Exception {
Mockito.verify(mockApp, Mockito.times(1)).notifyFatalError(
"Unexpected watch error from Zookeeper");
// fatal error means no new connection other than one from constructor
- Assert.assertEquals(1, count);
+ assertEquals(1, count);
// no new watches after fatal error
verifyExistCall(5);
@@ -599,13 +605,13 @@ public void testSuccessiveStandbyCalls() {
ZK_LOCK_NAME);
Mockito.verify(mockApp, Mockito.times(1)).becomeStandby();
verifyExistCall(1);
- Assert.assertTrue(elector.isMonitorLockNodePending());
+ assertTrue(elector.isMonitorLockNodePending());
Stat stat = new Stat();
stat.setEphemeralOwner(0L);
Mockito.when(mockZK.getSessionId()).thenReturn(1L);
elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
- Assert.assertFalse(elector.isMonitorLockNodePending());
+ assertFalse(elector.isMonitorLockNodePending());
WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class);
Mockito.when(mockEvent.getPath()).thenReturn(ZK_LOCK_NAME);
@@ -644,7 +650,7 @@ public void testQuitElection() throws Exception {
byte[] data = new byte[8];
elector.joinElection(data);
// getNewZooKeeper called 2 times. once in constructor and once now
- Assert.assertEquals(2, count);
+ assertEquals(2, count);
elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK,
ZK_LOCK_NAME);
Mockito.verify(mockApp, Mockito.times(1)).becomeStandby();
@@ -669,7 +675,7 @@ public void testGetActiveData() throws ActiveNotFoundException,
Mockito.when(
mockZK.getData(Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false),
any())).thenReturn(data);
- Assert.assertEquals(data, elector.getActiveData());
+ assertEquals(data, elector.getActiveData());
Mockito.verify(mockZK, Mockito.times(1)).getData(
Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), any());
@@ -680,7 +686,7 @@ public void testGetActiveData() throws ActiveNotFoundException,
new KeeperException.NoNodeException());
try {
elector.getActiveData();
- Assert.fail("ActiveNotFoundException expected");
+ fail("ActiveNotFoundException expected");
} catch(ActiveNotFoundException e) {
Mockito.verify(mockZK, Mockito.times(2)).getData(
Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), any());
@@ -693,7 +699,7 @@ public void testGetActiveData() throws ActiveNotFoundException,
any())).thenThrow(
new KeeperException.AuthFailedException());
elector.getActiveData();
- Assert.fail("KeeperException.AuthFailedException expected");
+ fail("KeeperException.AuthFailedException expected");
} catch(KeeperException.AuthFailedException ke) {
Mockito.verify(mockZK, Mockito.times(3)).getData(
Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), any());
@@ -762,7 +768,7 @@ public void testEnsureBaseNodeFails() throws Exception {
Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT));
try {
elector.ensureParentZNode();
- Assert.fail("Did not throw!");
+ fail("Did not throw!");
} catch (IOException ioe) {
if (!(ioe.getCause() instanceof KeeperException.ConnectionLossException)) {
throw ioe;
@@ -791,7 +797,7 @@ protected ZooKeeper createZooKeeper() throws IOException {
};
- Assert.fail("Did not throw zookeeper connection loss exceptions!");
+ fail("Did not throw zookeeper connection loss exceptions!");
} catch (KeeperException ke) {
GenericTestUtils.assertExceptionContains( "ConnectionLoss", ke);
}
@@ -842,14 +848,14 @@ protected synchronized ZooKeeper connectToZooKeeper() {
= ArgumentCaptor.forClass(ZKClientConfig.class);
Mockito.verify(e).initiateZookeeper(configArgumentCaptor.capture());
ZKClientConfig clientConfig = configArgumentCaptor.getValue();
- Assert.assertEquals(defaultConfig.getProperty(ZKClientConfig.SECURE_CLIENT),
- clientConfig.getProperty(ZKClientConfig.SECURE_CLIENT));
- Assert.assertEquals(defaultConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET),
- clientConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET));
- Assert.assertNull(clientConfig.getProperty(clientX509Util.getSslKeystoreLocationProperty()));
- Assert.assertNull(clientConfig.getProperty(clientX509Util.getSslKeystorePasswdProperty()));
- Assert.assertNull(clientConfig.getProperty(clientX509Util.getSslTruststoreLocationProperty()));
- Assert.assertNull(clientConfig.getProperty(clientX509Util.getSslTruststorePasswdProperty()));
+ assertEquals(defaultConfig.getProperty(ZKClientConfig.SECURE_CLIENT),
+ clientConfig.getProperty(ZKClientConfig.SECURE_CLIENT));
+ assertEquals(defaultConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET),
+ clientConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET));
+ assertNull(clientConfig.getProperty(clientX509Util.getSslKeystoreLocationProperty()));
+ assertNull(clientConfig.getProperty(clientX509Util.getSslKeystorePasswdProperty()));
+ assertNull(clientConfig.getProperty(clientX509Util.getSslTruststoreLocationProperty()));
+ assertNull(clientConfig.getProperty(clientX509Util.getSslTruststorePasswdProperty()));
}
/**
@@ -882,17 +888,17 @@ protected synchronized ZooKeeper connectToZooKeeper() {
= ArgumentCaptor.forClass(ZKClientConfig.class);
Mockito.verify(e).initiateZookeeper(configArgumentCaptor.capture());
ZKClientConfig clientConfig = configArgumentCaptor.getValue();
- Assert.assertEquals("true", clientConfig.getProperty(ZKClientConfig.SECURE_CLIENT));
- Assert.assertEquals("org.apache.zookeeper.ClientCnxnSocketNetty",
- clientConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET));
- Assert.assertEquals("keystore_location",
- clientConfig.getProperty(clientX509Util.getSslKeystoreLocationProperty()));
- Assert.assertEquals("keystore_password",
- clientConfig.getProperty(clientX509Util.getSslKeystorePasswdProperty()));
- Assert.assertEquals("truststore_location",
- clientConfig.getProperty(clientX509Util.getSslTruststoreLocationProperty()));
- Assert.assertEquals("truststore_password",
- clientConfig.getProperty(clientX509Util.getSslTruststorePasswdProperty()));
+ assertEquals("true", clientConfig.getProperty(ZKClientConfig.SECURE_CLIENT));
+ assertEquals("org.apache.zookeeper.ClientCnxnSocketNetty",
+ clientConfig.getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET));
+ assertEquals("keystore_location",
+ clientConfig.getProperty(clientX509Util.getSslKeystoreLocationProperty()));
+ assertEquals("keystore_password",
+ clientConfig.getProperty(clientX509Util.getSslKeystorePasswdProperty()));
+ assertEquals("truststore_location",
+ clientConfig.getProperty(clientX509Util.getSslTruststoreLocationProperty()));
+ assertEquals("truststore_password",
+ clientConfig.getProperty(clientX509Util.getSslTruststorePasswdProperty()));
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestFailoverController.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestFailoverController.java
index 3f027fa1c598a..01b9ef9c16787 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestFailoverController.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestFailoverController.java
@@ -34,11 +34,14 @@
import static org.apache.hadoop.ha.TestNodeFencer.setupFencer;
import org.apache.hadoop.security.AccessControlException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.internal.stubbing.answers.ThrowsException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class TestFailoverController {
private InetSocketAddress svc1Addr = new InetSocketAddress("svc1", 1234);
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHAAdmin.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHAAdmin.java
index a027b4d682b9f..cd2a4c7c1c824 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHAAdmin.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHAAdmin.java
@@ -17,7 +17,8 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -28,8 +29,8 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.hadoop.thirdparty.com.google.common.base.Joiner;
import org.slf4j.Logger;
@@ -44,7 +45,7 @@ public class TestHAAdmin {
private String errOutput;
private String output;
- @Before
+ @BeforeEach
public void setup() throws IOException {
tool = new HAAdmin() {
@Override
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHealthMonitor.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHealthMonitor.java
index 8738372fc4b38..b24d8eadb1fee 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHealthMonitor.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestHealthMonitor.java
@@ -17,7 +17,8 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -30,8 +31,9 @@
import org.apache.hadoop.ha.HealthMonitor.State;
import org.apache.hadoop.util.Time;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,7 +49,7 @@ public class TestHealthMonitor {
private DummyHAService svc;
- @Before
+ @BeforeEach
public void setupHM() throws InterruptedException, IOException {
Configuration conf = new Configuration();
conf.setInt(CommonConfigurationKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, 1);
@@ -78,7 +80,8 @@ protected DummyHAService createDummyHAService() {
new InetSocketAddress("0.0.0.0", 0), true);
}
- @Test(timeout=15000)
+ @Test
+ @Timeout(value = 15)
public void testMonitor() throws Exception {
LOG.info("Mocking bad health check, waiting for UNHEALTHY");
svc.isHealthy = false;
@@ -112,7 +115,8 @@ public void testMonitor() throws Exception {
* Test that the proper state is propagated when the health monitor
* sees an uncaught exception in its thread.
*/
- @Test(timeout=15000)
+ @Test
+ @Timeout(value = 15)
public void testHealthMonitorDies() throws Exception {
LOG.info("Mocking RTE in health monitor, waiting for FAILED");
throwOOMEOnCreate = true;
@@ -128,7 +132,8 @@ public void testHealthMonitorDies() throws Exception {
* health monitor and thus change its state to FAILED
* @throws Exception
*/
- @Test(timeout=15000)
+ @Test
+ @Timeout(value = 15)
public void testCallbackThrowsRTE() throws Exception {
hm.addCallback(new Callback() {
@Override
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestNodeFencer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestNodeFencer.java
index be67848e2120a..205f36a30180f 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestNodeFencer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestNodeFencer.java
@@ -17,7 +17,12 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import java.net.InetSocketAddress;
import java.util.List;
@@ -26,9 +31,8 @@
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.Lists;
import org.apache.hadoop.util.Shell;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class TestNodeFencer {
@@ -40,16 +44,16 @@ public class TestNodeFencer {
private static String FENCER_TRUE_COMMAND_UNIX = "shell(true)";
private static String FENCER_TRUE_COMMAND_WINDOWS = "shell(rem)";
- @Before
+ @BeforeEach
public void clearMockState() {
AlwaysSucceedFencer.fenceCalled = 0;
AlwaysSucceedFencer.callArgs.clear();
AlwaysFailFencer.fenceCalled = 0;
AlwaysFailFencer.callArgs.clear();
- MOCK_TARGET = Mockito.mock(HAServiceTarget.class);
- Mockito.doReturn("my mock").when(MOCK_TARGET).toString();
- Mockito.doReturn(new InetSocketAddress("host", 1234))
+ MOCK_TARGET = mock(HAServiceTarget.class);
+ doReturn("my mock").when(MOCK_TARGET).toString();
+ doReturn(new InetSocketAddress("host", 1234))
.when(MOCK_TARGET).getAddress();
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestShellCommandFencer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestShellCommandFencer.java
index 3eb6f42e467ed..61537e1249f25 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestShellCommandFencer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestShellCommandFencer.java
@@ -17,7 +17,15 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.contains;
+import static org.mockito.Mockito.endsWith;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.reset;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
@@ -28,17 +36,15 @@
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
-import static org.mockito.Mockito.mock;
-
public class TestShellCommandFencer {
private ShellCommandFencer fencer = createFencer();
private static final HAServiceTarget TEST_TARGET =
@@ -46,19 +52,19 @@ public class TestShellCommandFencer {
new InetSocketAddress("dummyhost", 1234));
private static final Logger LOG = ShellCommandFencer.LOG;
- @BeforeClass
+ @BeforeAll
public static void setupLogMock() {
ShellCommandFencer.LOG = mock(Logger.class, new LogAnswer());
}
- @AfterClass
+ @AfterAll
public static void tearDownLogMock() throws Exception {
ShellCommandFencer.LOG = LOG;
}
- @Before
+ @BeforeEach
public void resetLogSpy() {
- Mockito.reset(ShellCommandFencer.LOG);
+ reset(ShellCommandFencer.LOG);
}
private static ShellCommandFencer createFencer() {
@@ -88,9 +94,8 @@ public void testCheckNoArgs() {
new NodeFencer(conf, "shell");
fail("Didn't throw when passing no args to shell");
} catch (BadFencingConfigurationException confe) {
- assertTrue(
- "Unexpected exception:" + StringUtils.stringifyException(confe),
- confe.getMessage().contains("No argument passed"));
+ assertTrue(confe.getMessage().contains("No argument passed"),
+ "Unexpected exception:" + StringUtils.stringifyException(confe));
}
}
@@ -101,9 +106,8 @@ public void testCheckParensNoArgs() {
new NodeFencer(conf, "shell()");
fail("Didn't throw when passing no args to shell");
} catch (BadFencingConfigurationException confe) {
- assertTrue(
- "Unexpected exception:" + StringUtils.stringifyException(confe),
- confe.getMessage().contains("Unable to parse line: 'shell()'"));
+ assertTrue(confe.getMessage().contains("Unable to parse line: 'shell()'"),
+ "Unexpected exception:" + StringUtils.stringifyException(confe));
}
}
@@ -114,8 +118,8 @@ public void testCheckParensNoArgs() {
@Test
public void testStdoutLogging() {
assertTrue(fencer.tryFence(TEST_TARGET, "echo hello"));
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.endsWith("echo hello: hello"));
+ verify(ShellCommandFencer.LOG).info(
+ endsWith("echo hello: hello"));
}
/**
@@ -125,8 +129,8 @@ public void testStdoutLogging() {
@Test
public void testStderrLogging() {
assertTrue(fencer.tryFence(TEST_TARGET, "echo hello>&2"));
- Mockito.verify(ShellCommandFencer.LOG).warn(
- Mockito.endsWith("echo hello>&2: hello"));
+ verify(ShellCommandFencer.LOG).warn(
+ endsWith("echo hello>&2: hello"));
}
/**
@@ -137,12 +141,12 @@ public void testStderrLogging() {
public void testConfAsEnvironment() {
if (!Shell.WINDOWS) {
fencer.tryFence(TEST_TARGET, "echo $in_fencing_tests");
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.endsWith("echo $in...ing_tests: yessir"));
+ verify(ShellCommandFencer.LOG).info(
+ endsWith("echo $in...ing_tests: yessir"));
} else {
fencer.tryFence(TEST_TARGET, "echo %in_fencing_tests%");
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.endsWith("echo %in...ng_tests%: yessir"));
+ verify(ShellCommandFencer.LOG).info(
+ endsWith("echo %in...ng_tests%: yessir"));
}
}
@@ -154,12 +158,12 @@ public void testConfAsEnvironment() {
public void testTargetAsEnvironment() {
if (!Shell.WINDOWS) {
fencer.tryFence(TEST_TARGET, "echo $target_host $target_port");
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.endsWith("echo $ta...rget_port: dummyhost 1234"));
+ verify(ShellCommandFencer.LOG).info(
+ endsWith("echo $ta...rget_port: dummyhost 1234"));
} else {
fencer.tryFence(TEST_TARGET, "echo %target_host% %target_port%");
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.endsWith("echo %ta...get_port%: dummyhost 1234"));
+ verify(ShellCommandFencer.LOG).info(
+ endsWith("echo %ta...get_port%: dummyhost 1234"));
}
}
@@ -179,18 +183,18 @@ public void testEnvironmentWithPeer() {
+ "echo $source_host $source_port";
if (!Shell.WINDOWS) {
fencer.tryFence(target, cmd);
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.contains("echo $ta...rget_port: dummytarget 1111"));
+ verify(ShellCommandFencer.LOG).info(
+ contains("echo $ta...rget_port: dummytarget 1111"));
fencer.tryFence(source, cmd);
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.contains("echo $so...urce_port: dummysource 2222"));
+ verify(ShellCommandFencer.LOG).info(
+ contains("echo $so...urce_port: dummysource 2222"));
} else {
fencer.tryFence(target, cmd);
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.contains("echo %ta...get_port%: dummytarget 1111"));
+ verify(ShellCommandFencer.LOG).info(
+ contains("echo %ta...get_port%: dummytarget 1111"));
fencer.tryFence(source, cmd);
- Mockito.verify(ShellCommandFencer.LOG).info(
- Mockito.contains("echo %so...urce_port%: dummysource 2222"));
+ verify(ShellCommandFencer.LOG).info(
+ contains("echo %so...urce_port%: dummysource 2222"));
}
}
@@ -201,7 +205,8 @@ public void testEnvironmentWithPeer() {
* so that, if we use 'ssh', it won't try to prompt for a password
* and block forever, for example.
*/
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testSubprocessInputIsClosed() {
assertFalse(fencer.tryFence(TEST_TARGET, "read"));
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestSshFenceByTcpPort.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestSshFenceByTcpPort.java
index b07da8da5a89e..052ed9416fea5 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestSshFenceByTcpPort.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestSshFenceByTcpPort.java
@@ -17,7 +17,11 @@
*/
package org.apache.hadoop.ha;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.net.InetSocketAddress;
@@ -25,8 +29,8 @@
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.ha.SshFenceByTcpPort.Args;
import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Assume;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.slf4j.event.Level;
public class TestSshFenceByTcpPort {
@@ -55,9 +59,10 @@ public class TestSshFenceByTcpPort {
new DummyHAService(HAServiceState.ACTIVE,
new InetSocketAddress("8.8.8.8", 1234));
- @Test(timeout=20000)
+ @Test
+ @Timeout(value = 20)
public void testFence() throws BadFencingConfigurationException {
- Assume.assumeTrue(isConfigured());
+ assumeTrue(isConfigured());
Configuration conf = new Configuration();
conf.set(SshFenceByTcpPort.CONF_IDENTITIES_KEY, TEST_KEYFILE);
SshFenceByTcpPort fence = new SshFenceByTcpPort();
@@ -72,7 +77,8 @@ public void testFence() throws BadFencingConfigurationException {
* Make sure that it times out and returns false, but doesn't throw
* any exception
*/
- @Test(timeout=20000)
+ @Test
+ @Timeout(value = 20)
public void testConnectTimeout() throws BadFencingConfigurationException {
Configuration conf = new Configuration();
conf.setInt(SshFenceByTcpPort.CONF_CONNECT_TIMEOUT_KEY, 3000);
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/HttpServerFunctionalTest.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/HttpServerFunctionalTest.java
index f2d5541632285..ac649311f02bc 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/HttpServerFunctionalTest.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/HttpServerFunctionalTest.java
@@ -21,7 +21,7 @@
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.authorize.AccessControlList;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.http.HttpServer2.Builder;
@@ -42,14 +42,14 @@
* This is a base class for functional tests of the {@link HttpServer2}.
* The methods are static for other classes to import statically.
*/
-public class HttpServerFunctionalTest extends Assert {
+public class HttpServerFunctionalTest extends Assertions {
@SuppressWarnings("serial")
public static class LongHeaderServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
- Assert.assertEquals(63 * 1024, request.getHeader("longheader").length());
+ assertEquals(63 * 1024, request.getHeader("longheader").length());
response.setStatus(HttpServletResponse.SC_OK);
}
}
@@ -244,7 +244,7 @@ public static void stop(HttpServer2 server) throws Exception {
*/
public static URL getServerURL(HttpServer2 server)
throws MalformedURLException {
- assertNotNull("No server", server);
+ assertNotNull(server, "No server");
return new URL("http://"
+ NetUtils.getHostPortString(server.getConnectorAddress(0)));
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestAuthenticationSessionCookie.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestAuthenticationSessionCookie.java
index 44338dae9c937..545b273701fcf 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestAuthenticationSessionCookie.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestAuthenticationSessionCookie.java
@@ -13,15 +13,14 @@
*/
package org.apache.hadoop.http;
-import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.ssl.KeyStoreTestUtil;
import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.eclipse.jetty.util.log.Log;
import javax.servlet.*;
@@ -36,6 +35,9 @@
import java.util.HashMap;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
public class TestAuthenticationSessionCookie {
private static final String BASEDIR =
GenericTestUtils.getTempPath(TestHttpCookieFlag.class.getSimpleName());
@@ -149,10 +151,10 @@ public void testSessionCookie() throws IOException {
String header = conn.getHeaderField("Set-Cookie");
List cookies = HttpCookie.parse(header);
- Assert.assertTrue(!cookies.isEmpty());
+ assertTrue(!cookies.isEmpty());
Log.getLog().info(header);
- Assert.assertFalse(header.contains("; Expires="));
- Assert.assertTrue("token".equals(cookies.get(0).getValue()));
+ assertFalse(header.contains("; Expires="));
+ assertTrue("token".equals(cookies.get(0).getValue()));
}
@Test
@@ -171,13 +173,13 @@ public void testPersistentCookie() throws IOException {
String header = conn.getHeaderField("Set-Cookie");
List cookies = HttpCookie.parse(header);
- Assert.assertTrue(!cookies.isEmpty());
+ assertTrue(!cookies.isEmpty());
Log.getLog().info(header);
- Assert.assertTrue(header.contains("; Expires="));
- Assert.assertTrue("token".equals(cookies.get(0).getValue()));
+ assertTrue(header.contains("; Expires="));
+ assertTrue("token".equals(cookies.get(0).getValue()));
}
- @After
+ @AfterEach
public void cleanup() throws Exception {
server.stop();
FileUtil.fullyDelete(new File(BASEDIR));
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestDisabledProfileServlet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestDisabledProfileServlet.java
index ce068bb6f1cf6..dc5372fc2589b 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestDisabledProfileServlet.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestDisabledProfileServlet.java
@@ -23,9 +23,9 @@
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
-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;
/**
* Small test to cover default disabled prof endpoint.
@@ -35,14 +35,14 @@ public class TestDisabledProfileServlet extends HttpServerFunctionalTest {
private static HttpServer2 server;
private static URL baseUrl;
- @BeforeClass
+ @BeforeAll
public static void setup() throws Exception {
server = createTestServer();
server.start();
baseUrl = getServerURL(server);
}
- @AfterClass
+ @AfterAll
public static void cleanup() throws Exception {
server.stop();
}
@@ -68,20 +68,20 @@ public void testQuery() throws Exception {
@Test
public void testRequestMethods() throws IOException {
HttpURLConnection connection = getConnection("PUT");
- assertEquals("Unexpected response code", HttpServletResponse.SC_METHOD_NOT_ALLOWED,
- connection.getResponseCode());
+ assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ connection.getResponseCode(), "Unexpected response code");
connection.disconnect();
connection = getConnection("POST");
- assertEquals("Unexpected response code", HttpServletResponse.SC_METHOD_NOT_ALLOWED,
- connection.getResponseCode());
+ assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ connection.getResponseCode(), "Unexpected response code");
connection.disconnect();
connection = getConnection("DELETE");
- assertEquals("Unexpected response code", HttpServletResponse.SC_METHOD_NOT_ALLOWED,
- connection.getResponseCode());
+ assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ connection.getResponseCode(), "Unexpected response code");
connection.disconnect();
connection = getConnection("GET");
- assertEquals("Unexpected response code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- connection.getResponseCode());
+ assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ connection.getResponseCode(), "Unexpected response code");
connection.disconnect();
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestGlobalFilter.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestGlobalFilter.java
index ade383883f10e..1a8581f7479c0 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestGlobalFilter.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestGlobalFilter.java
@@ -35,7 +35,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.net.NetUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHtmlQuoting.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHtmlQuoting.java
index 775754d9f879f..0342f5edc96e9 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHtmlQuoting.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHtmlQuoting.java
@@ -17,11 +17,14 @@
*/
package org.apache.hadoop.http;
-import static org.junit.Assert.*;
+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 javax.servlet.http.HttpServletRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestHtmlQuoting {
@@ -72,19 +75,18 @@ public void testRequestQuoting() throws Exception {
new HttpServer2.QuotingInputFilter.RequestQuoter(mockReq);
Mockito.doReturn("a cookies = HttpCookie.parse(header);
- Assert.assertTrue(!cookies.isEmpty());
- Assert.assertTrue(header.contains("; HttpOnly"));
- Assert.assertTrue("token".equals(cookies.get(0).getValue()));
+ assertTrue(!cookies.isEmpty());
+ assertTrue(header.contains("; HttpOnly"));
+ assertTrue("token".equals(cookies.get(0).getValue()));
}
@Test
@@ -135,13 +136,13 @@ public void testHttpsCookie() throws IOException, GeneralSecurityException {
String header = conn.getHeaderField("Set-Cookie");
List cookies = HttpCookie.parse(header);
- Assert.assertTrue(!cookies.isEmpty());
- Assert.assertTrue(header.contains("; HttpOnly"));
- Assert.assertTrue(cookies.get(0).getSecure());
- Assert.assertTrue("token".equals(cookies.get(0).getValue()));
+ assertTrue(!cookies.isEmpty());
+ assertTrue(header.contains("; HttpOnly"));
+ assertTrue(cookies.get(0).getSecure());
+ assertTrue("token".equals(cookies.get(0).getValue()));
}
- @AfterClass
+ @AfterAll
public static void cleanup() throws Exception {
server.stop();
FileUtil.fullyDelete(new File(BASEDIR));
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpRequestLog.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpRequestLog.java
index 58721c4baa8f9..e150ab0427ff8 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpRequestLog.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpRequestLog.java
@@ -17,25 +17,24 @@
*/
package org.apache.hadoop.http;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Slf4jRequestLogWriter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestHttpRequestLog {
@Test
public void testAppenderDefined() {
RequestLog requestLog = HttpRequestLog.getRequestLog("test");
- assertNotNull("RequestLog should not be null", requestLog);
- assertThat(requestLog, instanceOf(CustomRequestLog.class));
+ assertNotNull(requestLog, "RequestLog should not be null");
+ assertInstanceOf(CustomRequestLog.class, requestLog);
CustomRequestLog crl = (CustomRequestLog) requestLog;
- assertThat(crl.getWriter(), instanceOf(Slf4jRequestLogWriter.class));
+ assertInstanceOf(Slf4jRequestLogWriter.class, crl.getWriter());
assertEquals(CustomRequestLog.EXTENDED_NCSA_FORMAT, crl.getFormatString());
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServer.java
index bf2e8a4f2de40..d59aa34a65688 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServer.java
@@ -30,14 +30,12 @@
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
-import org.assertj.core.api.Assertions;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.util.ajax.JSON;
-import org.junit.AfterClass;
-import org.junit.Assert;
-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;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,6 +71,8 @@
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
+import static org.assertj.core.api.Assertions.assertThat;
+
public class TestHttpServer extends HttpServerFunctionalTest {
static final Logger LOG = LoggerFactory.getLogger(TestHttpServer.class);
private static HttpServer2 server;
@@ -143,7 +143,8 @@ public void doGet(HttpServletRequest request,
}
}
- @BeforeClass public static void setup() throws Exception {
+ @BeforeAll
+ public static void setup() throws Exception {
Configuration conf = new Configuration();
conf.setInt(HttpServer2.HTTP_MAX_THREADS_KEY, MAX_THREADS);
conf.setBoolean(
@@ -160,7 +161,8 @@ public void doGet(HttpServletRequest request,
LOG.info("HTTP server started: "+ baseUrl);
}
- @AfterClass public static void cleanup() throws Exception {
+ @AfterAll
+ public static void cleanup() throws Exception {
server.stop();
}
@@ -181,8 +183,8 @@ public void run() {
assertEquals("a:b\nc:d\n",
readOutput(new URL(baseUrl, "/echo?a=b&c=d")));
int serverThreads = server.webServer.getThreadPool().getThreads();
- assertTrue("More threads are started than expected, Server Threads count: "
- + serverThreads, serverThreads <= MAX_THREADS);
+ assertTrue(serverThreads <= MAX_THREADS,
+ "More threads are started than expected, Server Threads count: " + serverThreads);
System.out.println("Number of threads = " + serverThreads +
" which is less or equal than the max = " + MAX_THREADS);
} catch (Exception e) {
@@ -280,9 +282,9 @@ public void testHttpServer2Metrics() throws Exception {
final HttpURLConnection conn =
(HttpURLConnection)servletUrl.openConnection();
conn.connect();
- Assertions.assertThat(conn.getResponseCode()).isEqualTo(200);
+ assertThat(conn.getResponseCode()).isEqualTo(200);
final int after = metrics.responses2xx();
- Assertions.assertThat(after).isGreaterThan(before);
+ assertThat(after).isGreaterThan(before);
}
/**
@@ -329,7 +331,7 @@ private void validateXFrameOption(HttpServer2.XFrameOption option) throws
try {
HttpURLConnection conn = getHttpURLConnection(httpServer);
String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS");
- assertTrue("X-FRAME-OPTIONS is absent in the header", xfoHeader != null);
+ assertTrue(xfoHeader != null, "X-FRAME-OPTIONS is absent in the header");
assertTrue(xfoHeader.endsWith(option.toString()));
} finally {
httpServer.stop();
@@ -345,7 +347,7 @@ public void testHttpResonseDoesNotContainXFrameOptions() throws Exception {
try {
HttpURLConnection conn = getHttpURLConnection(httpServer);
String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS");
- assertTrue("Unexpected X-FRAME-OPTIONS in header", xfoHeader == null);
+ assertTrue(xfoHeader == null, "Unexpected X-FRAME-OPTIONS in header");
} finally {
httpServer.stop();
}
@@ -542,9 +544,8 @@ public void testRequestQuoterWithNull() throws Exception {
Mockito.doReturn(null).when(request).getParameterValues("dummy");
RequestQuoter requestQuoter = new RequestQuoter(request);
String[] parameterValues = requestQuoter.getParameterValues("dummy");
- Assert.assertNull(
- "It should return null " + "when there are no values for the parameter",
- parameterValues);
+ assertNull(parameterValues,
+ "It should return null when there are no values for the parameter");
}
@Test
@@ -554,8 +555,8 @@ public void testRequestQuoterWithNotNull() throws Exception {
Mockito.doReturn(values).when(request).getParameterValues("dummy");
RequestQuoter requestQuoter = new RequestQuoter(request);
String[] parameterValues = requestQuoter.getParameterValues("dummy");
- Assert.assertTrue("It should return Parameter Values", Arrays.equals(
- values, parameterValues));
+ assertTrue(Arrays.equals(values, parameterValues),
+ "It should return Parameter Values");
}
@SuppressWarnings("unchecked")
@@ -585,32 +586,32 @@ public void testHasAdministratorAccess() throws Exception {
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
//authorization OFF
- Assert.assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
+ assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
//authorization ON & user NULL
response = Mockito.mock(HttpServletResponse.class);
conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true);
- Assert.assertFalse(HttpServer2.hasAdministratorAccess(context, request, response));
+ assertFalse(HttpServer2.hasAdministratorAccess(context, request, response));
Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_FORBIDDEN), Mockito.anyString());
//authorization ON & user NOT NULL & ACLs NULL
response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getRemoteUser()).thenReturn("foo");
- Assert.assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
+ assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
//authorization ON & user NOT NULL & ACLs NOT NULL & user not in ACLs
response = Mockito.mock(HttpServletResponse.class);
AccessControlList acls = Mockito.mock(AccessControlList.class);
Mockito.when(acls.isUserAllowed(Mockito.any())).thenReturn(false);
Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
- Assert.assertFalse(HttpServer2.hasAdministratorAccess(context, request, response));
+ assertFalse(HttpServer2.hasAdministratorAccess(context, request, response));
Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_FORBIDDEN), Mockito.anyString());
//authorization ON & user NOT NULL & ACLs NOT NULL & user in in ACLs
response = Mockito.mock(HttpServletResponse.class);
Mockito.when(acls.isUserAllowed(Mockito.any())).thenReturn(true);
Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
- Assert.assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
+ assertTrue(HttpServer2.hasAdministratorAccess(context, request, response));
}
@@ -623,7 +624,7 @@ public void testRequiresAuthorizationAccess() throws Exception {
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
//requires admin access to instrumentation, FALSE by default
- Assert.assertTrue(HttpServer2.isInstrumentationAccessAllowed(context, request, response));
+ assertTrue(HttpServer2.isInstrumentationAccessAllowed(context, request, response));
//requires admin access to instrumentation, TRUE
conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN, true);
@@ -631,7 +632,7 @@ public void testRequiresAuthorizationAccess() throws Exception {
AccessControlList acls = Mockito.mock(AccessControlList.class);
Mockito.when(acls.isUserAllowed(Mockito.any())).thenReturn(false);
Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
- Assert.assertFalse(HttpServer2.isInstrumentationAccessAllowed(context, request, response));
+ assertFalse(HttpServer2.isInstrumentationAccessAllowed(context, request, response));
}
@Test public void testBindAddress() throws Exception {
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLifecycle.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLifecycle.java
index 4ae1190abd5af..4b6ad61a94d26 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLifecycle.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLifecycle.java
@@ -17,7 +17,7 @@
*/
package org.apache.hadoop.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class TestHttpServerLifecycle extends HttpServerFunctionalTest {
@@ -27,12 +27,12 @@ public class TestHttpServerLifecycle extends HttpServerFunctionalTest {
* @param server server
*/
private void assertAlive(HttpServer2 server) {
- assertTrue("Server is not alive", server.isAlive());
+ assertTrue(server.isAlive(), "Server is not alive");
assertToStringContains(server, HttpServer2.STATE_DESCRIPTION_ALIVE);
}
private void assertNotLive(HttpServer2 server) {
- assertTrue("Server should not be live", !server.isAlive());
+ assertTrue(!server.isAlive(), "Server should not be live");
assertToStringContains(server, HttpServer2.STATE_DESCRIPTION_NOT_LIVE);
}
@@ -73,8 +73,8 @@ public void testStartedServerIsAlive() throws Throwable {
*/
private void assertToStringContains(HttpServer2 server, String text) {
String description = server.toString();
- assertTrue("Did not find \"" + text + "\" in \"" + description + "\"",
- description.contains(text));
+ assertTrue(description.contains(text),
+ "Did not find \"" + text + "\" in \"" + description + "\"");
}
/**
@@ -121,6 +121,6 @@ public void testWepAppContextAfterServerStop() throws Throwable {
assertAlive(server);
assertEquals(value, server.getAttribute(key));
stop(server);
- assertNull("Server context should have cleared", server.getAttribute(key));
+ assertNull(server.getAttribute(key), "Server context should have cleared");
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLogs.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLogs.java
index a4abbd92405ce..c4f8bf22f8422 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLogs.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLogs.java
@@ -21,9 +21,9 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.net.NetUtils;
-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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,7 +36,7 @@ public class TestHttpServerLogs extends HttpServerFunctionalTest {
static final Logger LOG = LoggerFactory.getLogger(TestHttpServerLogs.class);
private static HttpServer2 server;
- @BeforeClass
+ @BeforeAll
public static void setup() throws Exception {
}
@@ -47,7 +47,7 @@ private void startServer(Configuration conf) throws Exception {
LOG.info("HTTP server started: "+ baseUrl);
}
- @AfterClass
+ @AfterAll
public static void cleanup() throws Exception {
if (server != null && server.isAlive()) {
server.stop();
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWebapps.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWebapps.java
index 07dbc2a7c6e23..bf36a60a9433e 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWebapps.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWebapps.java
@@ -18,7 +18,7 @@
package org.apache.hadoop.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWithSpnego.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWithSpnego.java
index cddbc2a1959ae..d6a92f0df1de9 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWithSpnego.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWithSpnego.java
@@ -34,10 +34,9 @@
import org.apache.hadoop.security.authentication.util.StringSignerSecretProviderCreator;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.security.authorize.ProxyUsers;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.Assert;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileWriter;
@@ -46,7 +45,9 @@
import java.net.URI;
import java.net.URL;
import java.util.Properties;
-import static org.junit.Assert.assertTrue;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* This class is tested for http server with SPNEGO authentication.
@@ -69,7 +70,7 @@ public class TestHttpServerWithSpnego {
private static MiniKdc testMiniKDC;
private static File secretFile = new File(testRootDir, SECRET_STR);
- @BeforeClass
+ @BeforeAll
public static void setUp() throws Exception {
try {
testMiniKDC = new MiniKdc(MiniKdc.createConf(), testRootDir);
@@ -77,14 +78,14 @@ public static void setUp() throws Exception {
testMiniKDC.createPrincipal(
httpSpnegoKeytabFile, HTTP_USER + "/localhost");
} catch (Exception e) {
- assertTrue("Couldn't setup MiniKDC", false);
+ assertTrue(false, "Couldn't setup MiniKDC");
}
Writer w = new FileWriter(secretFile);
w.write("secret");
w.close();
}
- @AfterClass
+ @AfterAll
public static void tearDown() {
if (testMiniKDC != null) {
testMiniKDC.stop();
@@ -153,7 +154,7 @@ public void testAuthenticationWithProxyUser() throws Exception {
HttpURLConnection conn = authUrl
.openConnection(new URL(serverURL + servlet + "?doAs=userB"),
token);
- Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
}
// userA cannot impersonate userC, it fails.
@@ -162,7 +163,7 @@ public void testAuthenticationWithProxyUser() throws Exception {
HttpURLConnection conn = authUrl
.openConnection(new URL(serverURL + servlet + "?doAs=userC"),
token);
- Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
+ assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
conn.getResponseCode());
}
@@ -173,7 +174,7 @@ public void testAuthenticationWithProxyUser() throws Exception {
new String[]{"logLevel", "logs"}) {
HttpURLConnection conn = authUrl
.openConnection(new URL(serverURL + servlet), token);
- Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
}
// Setup token for userB
@@ -184,7 +185,7 @@ public void testAuthenticationWithProxyUser() throws Exception {
new String[]{"logLevel", "logs"}) {
HttpURLConnection conn = authUrl
.openConnection(new URL(serverURL + servlet), token);
- Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
+ assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
conn.getResponseCode());
}
@@ -221,13 +222,13 @@ public void testAuthenticationToAllowList() throws Exception {
// endpoints in whitelist should not require Kerberos authentication
for (String endpoint : allowList) {
HttpURLConnection conn = (HttpURLConnection) new URL(serverURL + endpoint).openConnection();
- Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
}
// endpoints not in whitelist should require Kerberos authentication
for (String endpoint : denyList) {
HttpURLConnection conn = (HttpURLConnection) new URL(serverURL + endpoint).openConnection();
- Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
+ assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
}
} finally {
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestIsActiveServlet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestIsActiveServlet.java
index 22bea17a7c063..8b367a12a6ce8 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestIsActiveServlet.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestIsActiveServlet.java
@@ -18,8 +18,8 @@
package org.apache.hadoop.http;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -29,7 +29,7 @@
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -51,7 +51,7 @@ public class TestIsActiveServlet {
private HttpServletResponse resp;
private ByteArrayOutputStream respOut;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
req = mock(HttpServletRequest.class);
resp = mock(HttpServletResponse.class);
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestProfileServlet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestProfileServlet.java
index 5c87451a49e6c..b895e1818942a 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestProfileServlet.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestProfileServlet.java
@@ -22,9 +22,9 @@
import java.net.URL;
import java.util.UUID;
-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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,7 +38,7 @@ public class TestProfileServlet extends HttpServerFunctionalTest {
private static final Logger LOG = LoggerFactory.getLogger(TestProfileServlet.class);
- @BeforeClass
+ @BeforeAll
public static void setup() throws Exception {
ProfileServlet.setIsTestRun(true);
System.setProperty("async.profiler.home", UUID.randomUUID().toString());
@@ -47,7 +47,7 @@ public static void setup() throws Exception {
baseUrl = getServerURL(server);
}
- @AfterClass
+ @AfterAll
public static void cleanup() throws Exception {
ProfileServlet.setIsTestRun(false);
System.clearProperty("async.profiler.home");
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
index cc76b4ad6d975..30065cc31c10d 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
@@ -43,9 +43,9 @@
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
-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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -106,7 +106,7 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
static final String INCLUDED_PROTOCOLS = "TLSv1.2";
static final String INCLUDED_PROTOCOLS_JDK11 = "TLSv1.3,TLSv1.2";
- @BeforeClass
+ @BeforeAll
public static void setup() throws Exception {
turnOnSSLDebugLogging();
storeHttpsCipherSuites();
@@ -156,7 +156,7 @@ private static void setupServer(Configuration conf, Configuration sslConf)
server.start();
}
- @AfterClass
+ @AfterAll
public static void cleanup() throws Exception {
server.stop();
FileUtil.fullyDelete(new File(BASEDIR));
@@ -286,7 +286,7 @@ public void testExcludedCiphers() throws Exception {
URL url = new URL(baseUrl, SERVLET_PATH_ECHO + "?a=b&c=d");
HttpsURLConnection conn = getConnectionWithSSLSocketFactory(url,
EXCLUDED_CIPHERS);
- assertFalse("excludedCipher list is empty", EXCLUDED_CIPHERS.isEmpty());
+ assertFalse(EXCLUDED_CIPHERS.isEmpty(), "excludedCipher list is empty");
try {
readFromConnection(conn);
fail("No Ciphers in common, SSLHandshake must fail.");
@@ -306,8 +306,7 @@ public void testIncludedProtocols() throws Exception {
HttpsURLConnection conn =
getConnectionWithPreferredProtocolSSLSocketFactory(url,
includedProtocols);
- assertFalse("included protocol list is empty",
- includedProtocols.isEmpty());
+ assertFalse(includedProtocols.isEmpty(), "included protocol list is empty");
readFromConnection(conn);
@@ -351,7 +350,7 @@ private void testEnabledCiphers(String ciphers) throws
IOException, GeneralSecurityException {
URL url = new URL(baseUrl, SERVLET_PATH_ECHO + "?a=b&c=d");
HttpsURLConnection conn = getConnectionWithSSLSocketFactory(url, ciphers);
- assertFalse("excludedCipher list is empty", ciphers.isEmpty());
+ assertFalse(ciphers.isEmpty(), "excludedCipher list is empty");
String out = readFromConnection(conn);
assertEquals(out, "a:b\nc:d\n");
LOG.info("At least one additional enabled cipher than excluded ciphers,"
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServerConfigs.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServerConfigs.java
index 039fae0195730..5b61509f4b0a5 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServerConfigs.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServerConfigs.java
@@ -27,10 +27,10 @@
import org.apache.hadoop.security.ssl.KeyStoreTestUtil;
import org.apache.hadoop.security.ssl.SSLFactory;
import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import static org.apache.hadoop.http.TestSSLHttpServer.EXCLUDED_CIPHERS;
import static org.apache.hadoop.http.TestSSLHttpServer.INCLUDED_PROTOCOLS;
@@ -39,6 +39,7 @@
import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.CLIENT_KEY_STORE_PASSWORD_DEFAULT;
import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.SERVER_KEY_STORE_PASSWORD_DEFAULT;
import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.TRUST_STORE_PASSWORD_DEFAULT;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test suit for testing KeyStore and TrustStore password settings.
@@ -56,7 +57,7 @@ public class TestSSLHttpServerConfigs {
private static final String CLIENT_PWD = CLIENT_KEY_STORE_PASSWORD_DEFAULT;
private static final String TRUST_STORE_PWD = TRUST_STORE_PASSWORD_DEFAULT;
- @Before
+ @BeforeEach
public void start() throws Exception {
TestSSLHttpServer.turnOnSSLDebugLogging();
TestSSLHttpServer.storeHttpsCipherSuites();
@@ -71,7 +72,7 @@ public void start() throws Exception {
sslConfDir = KeyStoreTestUtil.getClasspathDir(TestSSLHttpServer.class);
}
- @After
+ @AfterEach
public void shutdown() throws Exception {
FileUtil.fullyDelete(new File(BASEDIR));
KeyStoreTestUtil.cleanupSSLConfig(keystoreDir, sslConfDir);
@@ -136,38 +137,43 @@ public Boolean get() {
}
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetup() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
testServerStart(SERVER_PWD, SERVER_PWD, TRUST_STORE_PWD);
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetupWithoutTrustPassword() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
testServerStart(SERVER_PWD, SERVER_PWD, null);
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetupWithoutKeyStorePassword() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
testServerStart(SERVER_PWD, null, null);
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetupWithoutKeyStoreKeyPassword() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
testServerStart(null, SERVER_PWD, null);
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetupWithNoKeyStorePassword() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
// Accessing KeyStore without either of KeyStore.KeyPassword or KeyStore
// .password should fail.
try {
testServerStart(null, null, null);
- Assert.fail("Server should have failed to start without any " +
+ fail("Server should have failed to start without any " +
"KeyStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Problem starting http server",
@@ -175,14 +181,15 @@ public void testServerSetupWithNoKeyStorePassword() throws Exception {
}
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testServerSetupWithWrongKeyStorePassword() throws Exception {
setupKeyStores(SERVER_PWD, CLIENT_PWD, TRUST_STORE_PWD);
// Accessing KeyStore with wrong keyStore password/ keyPassword should fail.
try {
testServerStart(SERVER_PWD, "wrongPassword", null);
- Assert.fail("Server should have failed to start with wrong " +
+ fail("Server should have failed to start with wrong " +
"KeyStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Keystore was tampered with, " +
@@ -191,7 +198,7 @@ public void testServerSetupWithWrongKeyStorePassword() throws Exception {
try {
testServerStart("wrongPassword", SERVER_PWD, null);
- Assert.fail("Server should have failed to start with wrong " +
+ fail("Server should have failed to start with wrong " +
"KeyStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Problem starting http server",
@@ -201,7 +208,8 @@ public void testServerSetupWithWrongKeyStorePassword() throws Exception {
}
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testKeyStoreSetupWithoutTrustStorePassword() throws Exception {
// Setup TrustStore without TrustStore password
setupKeyStores(SERVER_PWD, CLIENT_PWD, "");
@@ -213,7 +221,7 @@ public void testKeyStoreSetupWithoutTrustStorePassword() throws Exception {
// set) should fail.
try {
testServerStart(SERVER_PWD, SERVER_PWD, "wrongPassword");
- Assert.fail("Server should have failed to start with wrong " +
+ fail("Server should have failed to start with wrong " +
"TrustStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Keystore was tampered with, " +
@@ -221,7 +229,8 @@ public void testKeyStoreSetupWithoutTrustStorePassword() throws Exception {
}
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testKeyStoreSetupWithoutKeyStorePassword() throws Exception {
// Setup KeyStore without KeyStore password
setupKeyStores(SERVER_PWD, "", TRUST_STORE_PWD);
@@ -233,7 +242,7 @@ public void testKeyStoreSetupWithoutKeyStorePassword() throws Exception {
// set) should fail.
try {
testServerStart(SERVER_PWD, "wrongPassword", TRUST_STORE_PWD);
- Assert.fail("Server should have failed to start with wrong " +
+ fail("Server should have failed to start with wrong " +
"KeyStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Keystore was tampered with, " +
@@ -241,7 +250,8 @@ public void testKeyStoreSetupWithoutKeyStorePassword() throws Exception {
}
}
- @Test(timeout=120000)
+ @Test
+ @Timeout(value = 120)
public void testKeyStoreSetupWithoutPassword() throws Exception {
// Setup KeyStore without any password
setupKeyStores("", "", "");
@@ -254,7 +264,7 @@ public void testKeyStoreSetupWithoutPassword() throws Exception {
try {
testServerStart(null, null, null);
- Assert.fail("Server should have failed to start without " +
+ fail("Server should have failed to start without " +
"KeyStore password.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("Problem starting http server",
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java
index a8ecbd4fe28ef..3c225d0d25058 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java
@@ -35,7 +35,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/lib/TestStaticUserWebFilter.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/lib/TestStaticUserWebFilter.java
index 03b37e304619d..646a09955a2c6 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/lib/TestStaticUserWebFilter.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/lib/TestStaticUserWebFilter.java
@@ -17,7 +17,7 @@
*/
package org.apache.hadoop.http.lib;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -30,7 +30,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.http.lib.StaticUserWebFilter.StaticUserFilter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/MiniRPCBenchmark.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/MiniRPCBenchmark.java
index 4234f24006999..76db3b332225e 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/MiniRPCBenchmark.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/MiniRPCBenchmark.java
@@ -27,7 +27,6 @@
import java.util.Enumeration;
import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
@@ -44,6 +43,8 @@
import org.apache.hadoop.util.Time;
import org.slf4j.event.Level;
+import static org.junit.jupiter.api.Assertions.fail;
+
/**
* MiniRPCBenchmark measures time to establish an RPC connection
* to a secure RPC server.
@@ -222,7 +223,7 @@ public MiniProtocol run() throws IOException {
}
});
} catch (InterruptedException e) {
- Assert.fail(Arrays.toString(e.getStackTrace()));
+ fail(Arrays.toString(e.getStackTrace()));
}
} finally {
RPC.stopProxy(client);
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestAsyncIPC.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestAsyncIPC.java
index 64c486c4b14f8..11ec4e83d01d9 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestAsyncIPC.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestAsyncIPC.java
@@ -29,9 +29,9 @@
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.concurrent.AsyncGetFuture;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,8 +43,8 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
public class TestAsyncIPC {
@@ -56,7 +56,7 @@ public class TestAsyncIPC {
return new AsyncGetFuture<>(Client.getAsyncRpcResponse());
}
- @Before
+ @BeforeEach
public void setupConf() {
conf = new Configuration();
conf.setInt(CommonConfigurationKeys.IPC_CLIENT_ASYNC_CALLS_MAX_KEY, 10000);
@@ -102,10 +102,10 @@ public void run() {
void assertReturnValues() throws InterruptedException, ExecutionException {
for (int i = 0; i < count; i++) {
LongWritable value = returnFutures.get(i).get();
- Assert.assertEquals("call" + i + " failed.",
- expectedValues.get(i).longValue(), value.get());
+ assertEquals(expectedValues.get(i).longValue(), value.get(),
+ "call" + i + " failed.");
}
- Assert.assertFalse(failed);
+ assertFalse(failed);
}
void assertReturnValues(long timeout, TimeUnit unit)
@@ -128,12 +128,12 @@ void assertReturnValues(long timeout, TimeUnit unit)
continue;
}
- Assert.assertEquals("call" + i + " failed.",
- expectedValues.get(i).longValue(), value.get());
+ assertEquals(expectedValues.get(i).longValue(), value.get(),
+ "call" + i + " failed.");
checked[i] = true;
}
}
- Assert.assertFalse(failed);
+ assertFalse(failed);
}
}
@@ -227,14 +227,16 @@ private void waitForReturnValues(final int start, final int end)
}
}
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testAsyncCall() throws IOException, InterruptedException,
ExecutionException {
internalTestAsyncCall(3, false, 2, 5, 100);
internalTestAsyncCall(3, true, 2, 5, 10);
}
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testAsyncCallLimit() throws IOException,
InterruptedException, ExecutionException {
internalTestAsyncCallLimit(100, false, 5, 10, 500);
@@ -267,7 +269,8 @@ public void internalTestAsyncCall(int handlerCount, boolean handlerSleep,
server.stop();
}
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testCallGetReturnRpcResponseMultipleTimes() throws IOException,
InterruptedException, ExecutionException {
int handlerCount = 10, callCount = 100;
@@ -284,14 +287,15 @@ public void testCallGetReturnRpcResponseMultipleTimes() throws IOException,
caller.assertReturnValues();
caller.assertReturnValues();
caller.assertReturnValues();
- Assert.assertEquals(asyncCallCount, client.getAsyncCallCount());
+ assertEquals(asyncCallCount, client.getAsyncCallCount());
} finally {
client.stop();
server.stop();
}
}
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testFutureGetWithTimeout() throws IOException,
InterruptedException, ExecutionException {
// GenericTestUtils.setLogLevel(AsyncGetFuture.LOG, Level.ALL);
@@ -340,7 +344,7 @@ public void internalTestAsyncCallLimit(int handlerCount, boolean handlerSleep,
callers[i].getCount());
String msg = String.format("Expected not failed for caller-%d: %s.", i,
callers[i]);
- assertFalse(msg, callers[i].failed);
+ assertFalse(callers[i].failed, msg);
}
for (int i = 0; i < clientCount; i++) {
clients[i].stop();
@@ -356,7 +360,8 @@ public void internalTestAsyncCallLimit(int handlerCount, boolean handlerSleep,
* @throws ExecutionException
* @throws InterruptedException
*/
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testCallIdAndRetry() throws IOException, InterruptedException,
ExecutionException {
final Map infoMap = new HashMap();
@@ -382,7 +387,7 @@ Call createCall(RpcKind rpcKind, Writable rpcRequest) {
@Override
void checkResponse(RpcResponseHeaderProto header) throws IOException {
super.checkResponse(header);
- Assert.assertEquals(infoMap.get(header.getCallId()).retry,
+ assertEquals(infoMap.get(header.getCallId()).retry,
header.getRetryCount());
}
};
@@ -392,7 +397,7 @@ void checkResponse(RpcResponseHeaderProto header) throws IOException {
server.callListener = new Runnable() {
@Override
public void run() {
- Assert.assertEquals(infoMap.get(Server.getCallId()).retry,
+ assertEquals(infoMap.get(Server.getCallId()).retry,
Server.getCallRetryCount());
}
};
@@ -415,7 +420,8 @@ public void run() {
* @throws ExecutionException
* @throws InterruptedException
*/
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testCallRetryCount() throws IOException, InterruptedException,
ExecutionException {
final int retryCount = 255;
@@ -430,7 +436,7 @@ public void testCallRetryCount() throws IOException, InterruptedException,
public void run() {
// we have not set the retry count for the client, thus on the server
// side we should see retry count as 0
- Assert.assertEquals(retryCount, Server.getCallRetryCount());
+ assertEquals(retryCount, Server.getCallRetryCount());
}
};
@@ -452,11 +458,13 @@ public void run() {
* @throws ExecutionException
* @throws InterruptedException
*/
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testInitialCallRetryCount() throws IOException,
InterruptedException, ExecutionException {
// Override client to store the call id
final Client client = new Client(LongWritable.class, conf);
+ Client.setCallIdAndRetryCount(Client.nextCallId(), 0, null);
// Attach a listener that tracks every call ID received by the server.
final TestServer server = new TestIPC.TestServer(1, false, conf);
@@ -465,7 +473,7 @@ public void testInitialCallRetryCount() throws IOException,
public void run() {
// we have not set the retry count for the client, thus on the server
// side we should see retry count as 0
- Assert.assertEquals(0, Server.getCallRetryCount());
+ assertEquals(0, Server.getCallRetryCount());
}
};
@@ -488,7 +496,8 @@ public void run() {
* @throws InterruptedException
* @throws ExecutionException
*/
- @Test(timeout = 60000)
+ @Test
+ @Timeout(value = 60)
public void testUniqueSequentialCallIds() throws IOException,
InterruptedException, ExecutionException {
int serverThreads = 10, callerCount = 100, perCallerCallCount = 100;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallQueueManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallQueueManager.java
index 545ddb40ff5fe..bc607d762a3cd 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallQueueManager.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallQueueManager.java
@@ -18,16 +18,18 @@
package org.apache.hadoop.ipc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.reset;
import java.util.ArrayList;
import java.util.HashMap;
@@ -38,8 +40,8 @@
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.ipc.CallQueueManager.CallQueueOverflowException;
import org.apache.hadoop.security.UserGroupInformation;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
public class TestCallQueueManager {
private CallQueueManager manager;
@@ -261,7 +263,8 @@ public void testSchedulerWithoutFCQ() throws InterruptedException {
assertCanPut(manager, 0, 1);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testSwapUnderContention() throws InterruptedException {
manager = new CallQueueManager(queueClass, schedulerClass, false,
5000, "", conf);
@@ -438,12 +441,12 @@ public void testSchedulerConstructorException() throws InterruptedException {
@SuppressWarnings("unchecked")
@Test
public void testCallQueueOverflowExceptions() throws Exception {
- RpcScheduler scheduler = Mockito.mock(RpcScheduler.class);
- BlockingQueue queue = Mockito.mock(BlockingQueue.class);
+ RpcScheduler scheduler = mock(RpcScheduler.class);
+ BlockingQueue queue = mock(BlockingQueue.class);
CallQueueManager cqm =
- Mockito.spy(new CallQueueManager<>(queue, scheduler, false, false));
+ spy(new CallQueueManager<>(queue, scheduler, false, false));
CallQueueManager cqmTriggerFailover =
- Mockito.spy(new CallQueueManager<>(queue, scheduler, false, true));
+ spy(new CallQueueManager<>(queue, scheduler, false, true));
Schedulable call = new FakeCall(0);
// call queue exceptions that trigger failover
@@ -473,7 +476,7 @@ public void testCallQueueOverflowExceptions() throws Exception {
cqm.add(call);
fail("didn't throw");
} catch (Exception ex) {
- assertTrue(ex.toString(), ex instanceof CallQueueOverflowException);
+ assertTrue(ex instanceof CallQueueOverflowException, ex.toString());
}
// backoff disabled, put is put to queue.
@@ -500,7 +503,7 @@ public void testCallQueueOverflowExceptions() throws Exception {
cqm.put(call);
fail("didn't fail");
} catch (Exception ex) {
- assertTrue(ex.toString(), ex instanceof CallQueueOverflowException);
+ assertTrue(ex instanceof CallQueueOverflowException, ex.toString());
}
verify(queue, times(0)).put(call);
verify(queue, times(0)).add(call);
@@ -513,7 +516,7 @@ public void testCallQueueOverflowExceptions() throws Exception {
cqm.add(call);
fail("didn't fail");
} catch (Exception ex) {
- assertTrue(ex.toString(), ex instanceof CallQueueOverflowException);
+ assertTrue(ex instanceof CallQueueOverflowException, ex.toString());
}
verify(queue, times(0)).put(call);
verify(queue, times(0)).add(call);
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallerContext.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallerContext.java
index bb4a119e7db29..a995b2232ecba 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallerContext.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallerContext.java
@@ -18,10 +18,11 @@
package org.apache.hadoop.ipc;
import org.apache.hadoop.conf.Configuration;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_CALLER_CONTEXT_SEPARATOR_KEY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class TestCallerContext {
@Test
@@ -31,14 +32,14 @@ public void testBuilderAppend() {
CallerContext.Builder builder = new CallerContext.Builder(null, conf);
CallerContext context = builder.append("context1")
.append("context2").append("key3", "value3").build();
- Assert.assertEquals(true,
+ assertEquals(true,
context.getContext().contains("$"));
String[] items = context.getContext().split("\\$");
- Assert.assertEquals(3, items.length);
- Assert.assertEquals("key3:value3", items[2]);
+ assertEquals(3, items.length);
+ assertEquals("key3:value3", items[2]);
builder.append("$$");
- Assert.assertEquals("context1$context2$key3:value3$$$",
+ assertEquals("context1$context2$key3:value3$$$",
builder.build().getContext());
}
@@ -48,37 +49,39 @@ public void testBuilderAppendIfAbsent() {
conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "$");
CallerContext.Builder builder = new CallerContext.Builder(null, conf);
builder.append("key1", "value1");
- Assert.assertEquals("key1:value1",
+ assertEquals("key1:value1",
builder.build().getContext());
// Append an existed key with different value.
builder.appendIfAbsent("key1", "value2");
String[] items = builder.build().getContext().split("\\$");
- Assert.assertEquals(1, items.length);
- Assert.assertEquals("key1:value1",
+ assertEquals(1, items.length);
+ assertEquals("key1:value1",
builder.build().getContext());
// Append an absent key.
builder.appendIfAbsent("key2", "value2");
String[] items2 = builder.build().getContext().split("\\$");
- Assert.assertEquals(2, items2.length);
- Assert.assertEquals("key1:value1$key2:value2",
+ assertEquals(2, items2.length);
+ assertEquals("key1:value1$key2:value2",
builder.build().getContext());
// Append a key that is a substring of an existing key.
builder.appendIfAbsent("key", "value");
String[] items3 = builder.build().getContext().split("\\$");
- Assert.assertEquals(3, items3.length);
- Assert.assertEquals("key1:value1$key2:value2$key:value",
+ assertEquals(3, items3.length);
+ assertEquals("key1:value1$key2:value2$key:value",
builder.build().getContext());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testNewBuilder() {
- Configuration conf = new Configuration();
- // Set illegal separator.
- conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "\t");
- CallerContext.Builder builder = new CallerContext.Builder(null, conf);
- builder.build();
+ assertThrows(IllegalArgumentException.class, () -> {
+ Configuration conf = new Configuration();
+ // Set illegal separator.
+ conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "\t");
+ CallerContext.Builder builder = new CallerContext.Builder(null, conf);
+ builder.build();
+ });
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestDecayRpcScheduler.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestDecayRpcScheduler.java
index 4ae3de1b15873..0afae0be4378f 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestDecayRpcScheduler.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestDecayRpcScheduler.java
@@ -22,13 +22,15 @@
import java.util.Map;
import org.eclipse.jetty.util.ajax.JSON;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import static org.apache.hadoop.ipc.DecayRpcScheduler.IPC_DECAYSCHEDULER_THRESHOLDS_KEY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -80,14 +82,18 @@ public long getCost(ProcessingDetails details) {
private DecayRpcScheduler scheduler;
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testNegativeScheduler() {
- scheduler = new DecayRpcScheduler(-1, "", new Configuration());
+ assertThrows(IllegalArgumentException.class, () -> {
+ scheduler = new DecayRpcScheduler(-1, "", new Configuration());
+ });
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testZeroScheduler() {
- scheduler = new DecayRpcScheduler(0, "", new Configuration());
+ assertThrows(IllegalArgumentException.class, () -> {
+ scheduler = new DecayRpcScheduler(0, "", new Configuration());
+ });
}
@Test
@@ -292,17 +298,18 @@ public void testPriority() throws Exception {
"Hadoop:service="+ namespace + ",name=DecayRpcScheduler");
String cvs1 = (String) mbs.getAttribute(mxbeanName, "CallVolumeSummary");
- assertTrue("Get expected JMX of CallVolumeSummary before decay",
- cvs1.equals("{\"A\":6,\"B\":2,\"C\":2}"));
+ assertTrue(cvs1.equals("{\"A\":6,\"B\":2,\"C\":2}"),
+ "Get expected JMX of CallVolumeSummary before decay");
scheduler.forceDecay();
String cvs2 = (String) mbs.getAttribute(mxbeanName, "CallVolumeSummary");
- assertTrue("Get expected JMX for CallVolumeSummary after decay",
- cvs2.equals("{\"A\":3,\"B\":1,\"C\":1}"));
+ assertTrue(cvs2.equals("{\"A\":3,\"B\":1,\"C\":1}"),
+ "Get expected JMX for CallVolumeSummary after decay");
}
- @Test(timeout=2000)
+ @Test
+ @Timeout(value = 2)
@SuppressWarnings("deprecation")
public void testPeriodic() throws InterruptedException {
Configuration conf = new Configuration();
@@ -325,7 +332,8 @@ public void testPeriodic() throws InterruptedException {
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testNPEatInitialization() throws InterruptedException {
// redirect the LOG to and check if there is NPE message while initializing
// the DecayRpcScheduler
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestFairCallQueue.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestFairCallQueue.java
index 06b65dc4df3c5..1afc88c562c8e 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestFairCallQueue.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestFairCallQueue.java
@@ -28,15 +28,15 @@
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
-import org.junit.Before;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
import javax.management.MBeanServer;
import javax.management.ObjectName;
@@ -77,7 +77,7 @@ private Schedulable mockCall(String id) {
}
@SuppressWarnings("deprecation")
- @Before
+ @BeforeEach
public void setUp() {
Configuration conf = new Configuration();
conf.setInt("ns." + FairCallQueue.IPC_CALLQUEUE_PRIORITY_LEVELS_KEY, 2);
@@ -407,21 +407,21 @@ public void testInsertion() throws Exception {
private void checkOverflowException(Exception ex, RpcStatusProto status,
boolean failOverTriggered) {
// should be an overflow exception
- assertTrue(ex.getClass().getName() + " != CallQueueOverflowException",
- ex instanceof CallQueueOverflowException);
+ assertTrue(ex instanceof CallQueueOverflowException,
+ ex.getClass().getName() + " != CallQueueOverflowException");
IOException ioe = ((CallQueueOverflowException)ex).getCause();
assertNotNull(ioe);
- assertTrue(ioe.getClass().getName() + " != RpcServerException",
- ioe instanceof RpcServerException);
+ assertTrue(ioe instanceof RpcServerException,
+ ioe.getClass().getName() + " != RpcServerException");
RpcServerException rse = (RpcServerException)ioe;
// check error/fatal status and if it embeds a retriable ex or standby ex.
assertEquals(status, rse.getRpcStatusProto());
if (failOverTriggered) {
- assertTrue(rse.getClass().getName() + " != RetriableException",
- rse.getCause() instanceof StandbyException);
+ assertTrue(rse.getCause() instanceof StandbyException,
+ rse.getClass().getName() + " != RetriableException");
} else {
- assertTrue(rse.getClass().getName() + " != RetriableException",
- rse.getCause() instanceof RetriableException);
+ assertTrue(rse.getCause() instanceof RetriableException,
+ rse.getClass().getName() + " != RetriableException");
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPC.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPC.java
index 9165c71eb41bf..a191095b44516 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPC.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPC.java
@@ -18,19 +18,28 @@
package org.apache.hadoop.ipc;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.reset;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
@@ -94,12 +103,9 @@
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.test.LambdaTestUtils;
import org.apache.hadoop.util.StringUtils;
-import org.assertj.core.api.Condition;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -110,8 +116,6 @@
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
-import static org.assertj.core.api.Assertions.assertThat;
-
/** Unit tests for IPC. */
public class TestIPC {
public static final Logger LOG = LoggerFactory.getLogger(TestIPC.class);
@@ -126,7 +130,7 @@ public class TestIPC {
static boolean WRITABLE_FAULTS_ENABLED = true;
static int WRITABLE_FAULTS_SLEEP = 0;
- @Before
+ @BeforeEach
public void setupConf() {
conf = new Configuration();
Client.setPingInterval(conf, PING_INTERVAL);
@@ -339,7 +343,8 @@ public Object invoke(Object proxy, Method method, Object[] args)
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testSerial() throws IOException, InterruptedException {
internalTestSerial(3, false, 2, 5, 100);
internalTestSerial(3, true, 2, 5, 10);
@@ -403,7 +408,8 @@ public void testAuxiliaryPorts() throws IOException, InterruptedException {
server.stop();
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testStandAloneClient() throws IOException {
Client client = new Client(LongWritable.class, conf);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 10);
@@ -413,13 +419,13 @@ public void testStandAloneClient() throws IOException {
} catch (IOException e) {
String message = e.getMessage();
String addressText = address.getHostName() + ":" + address.getPort();
- assertTrue("Did not find "+addressText+" in "+message,
- message.contains(addressText));
+ assertTrue(message.contains(addressText),
+ "Did not find "+addressText+" in "+message);
Throwable cause=e.getCause();
- assertNotNull("No nested exception in "+e,cause);
+ assertNotNull(cause, "No nested exception in "+e);
String causeText=cause.getMessage();
- assertTrue("Did not find " + causeText + " in " + message,
- message.contains(causeText));
+ assertTrue(message.contains(causeText),
+ "Did not find " + causeText + " in " + message);
} finally {
client.stop();
}
@@ -539,7 +545,8 @@ private void doErrorTest(
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIOEOnClientWriteParam() throws Exception {
doErrorTest(IOEOnWriteWritable.class,
LongWritable.class,
@@ -547,7 +554,8 @@ public void testIOEOnClientWriteParam() throws Exception {
LongWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testRTEOnClientWriteParam() throws Exception {
doErrorTest(RTEOnWriteWritable.class,
LongWritable.class,
@@ -555,7 +563,8 @@ public void testRTEOnClientWriteParam() throws Exception {
LongWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIOEOnServerReadParam() throws Exception {
doErrorTest(LongWritable.class,
IOEOnReadWritable.class,
@@ -563,7 +572,8 @@ public void testIOEOnServerReadParam() throws Exception {
LongWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testRTEOnServerReadParam() throws Exception {
doErrorTest(LongWritable.class,
RTEOnReadWritable.class,
@@ -572,7 +582,8 @@ public void testRTEOnServerReadParam() throws Exception {
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIOEOnServerWriteResponse() throws Exception {
doErrorTest(LongWritable.class,
LongWritable.class,
@@ -580,7 +591,8 @@ public void testIOEOnServerWriteResponse() throws Exception {
LongWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testRTEOnServerWriteResponse() throws Exception {
doErrorTest(LongWritable.class,
LongWritable.class,
@@ -588,7 +600,8 @@ public void testRTEOnServerWriteResponse() throws Exception {
LongWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIOEOnClientReadResponse() throws Exception {
doErrorTest(LongWritable.class,
LongWritable.class,
@@ -596,7 +609,8 @@ public void testIOEOnClientReadResponse() throws Exception {
IOEOnReadWritable.class);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testRTEOnClientReadResponse() throws Exception {
doErrorTest(LongWritable.class,
LongWritable.class,
@@ -609,7 +623,8 @@ public void testRTEOnClientReadResponse() throws Exception {
* that a ping should have been sent. This is a reproducer for a
* deadlock seen in one iteration of HADOOP-6762.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIOEOnWriteAfterPingClient() throws Exception {
// start server
Client.setPingInterval(conf, 100);
@@ -628,8 +643,8 @@ public void testIOEOnWriteAfterPingClient() throws Exception {
private static void assertExceptionContains(
Throwable t, String substring) {
String msg = StringUtils.stringifyException(t);
- assertTrue("Exception should contain substring '" + substring + "':\n" +
- msg, msg.contains(substring));
+ assertTrue(msg.contains(substring),
+ "Exception should contain substring '" + substring + "':\n" + msg);
LOG.info("Got expected exception", t);
}
@@ -637,7 +652,8 @@ private static void assertExceptionContains(
* Test that, if the socket factory throws an IOE, it properly propagates
* to the client.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testSocketFactoryException() throws IOException {
SocketFactory mockFactory = mock(SocketFactory.class);
doThrow(new IOException("Injected fault")).when(mockFactory).createSocket();
@@ -670,12 +686,13 @@ public synchronized void setSoTimeout(int timeout) {
* failure is handled properly. This is a regression test for
* HADOOP-7428.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testRTEDuringConnectionSetup() throws IOException {
// Set up a socket factory which returns sockets which
// throw an RTE when setSoTimeout is called.
SocketFactory spyFactory = spy(NetUtils.getDefaultSocketFactory(conf));
- Mockito.doAnswer(new Answer() {
+ doAnswer(new Answer() {
@Override
public Socket answer(InvocationOnMock invocation) {
return new MockSocket();
@@ -699,7 +716,7 @@ public Socket answer(InvocationOnMock invocation) {
// Resetting to the normal socket behavior should succeed
// (i.e. it should not have cached a half-constructed connection)
- Mockito.reset(spyFactory);
+ reset(spyFactory);
call(client, RANDOM.nextLong(), address, conf);
} finally {
client.stop();
@@ -707,7 +724,8 @@ public Socket answer(InvocationOnMock invocation) {
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcTimeout() throws IOException {
// start server
Server server = new TestServer(1, true);
@@ -730,7 +748,8 @@ public void testIpcTimeout() throws IOException {
client.stop();
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcConnectTimeout() throws IOException {
// start server
Server server = new TestServer(1, true);
@@ -754,7 +773,8 @@ public void testIpcConnectTimeout() throws IOException {
/**
* Check service class byte in IPC header is correct on wire.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcWithServiceClass() throws IOException {
// start server
Server server = new TestServer(5, false);
@@ -800,7 +820,8 @@ public Writable call(RPC.RpcKind rpcKind, String protocol, Writable param,
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcHostResolutionTimeout() throws Exception {
final InetSocketAddress addr = new InetSocketAddress("host.invalid", 80);
@@ -898,7 +919,8 @@ public void testStableHashCode() throws IOException {
}
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcFlakyHostResolution() throws IOException {
// start server
Server server = new TestServer(5, false);
@@ -929,7 +951,8 @@ public void testIpcFlakyHostResolution() throws IOException {
* @throws BrokenBarrierException
* @throws InterruptedException
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcWithReaderQueuing() throws Exception {
// 1 reader, 1 connectionQ slot, 1 callq
for (int i=0; i < 10; i++) {
@@ -1058,7 +1081,8 @@ public void run() {
server.stop();
}
- @Test(timeout=30000)
+ @Test
+ @Timeout(value = 30)
public void testConnectionIdleTimeouts() throws Exception {
GenericTestUtils.setLogLevel(Server.LOG, Level.DEBUG);
final int maxIdle = 1000;
@@ -1176,37 +1200,40 @@ private static void callAndVerify(Server server, InetSocketAddress addr,
call(client, addr, serviceClass, conf);
Connection connection = server.getConnections()[0];
LOG.info("Connection is from: {}", connection);
- assertEquals(
- "Connection string representation should include only IP address for healthy connection", 1,
- connection.toString().split(" / ").length);
+ assertEquals(1, connection.toString().split(" / ").length,
+ "Connection string representation should include only IP address for healthy connection");
int serviceClass2 = connection.getServiceClass();
assertFalse(noChanged ^ serviceClass == serviceClass2);
client.stop();
}
-
- @Test(timeout=30000, expected=IOException.class)
+
+ @Test
+ @Timeout(value = 30)
public void testIpcAfterStopping() throws IOException {
- // start server
- Server server = new TestServer(5, false);
- InetSocketAddress addr = NetUtils.getConnectAddress(server);
- server.start();
+ assertThrows(IOException.class, () -> {
+ // start server
+ Server server = new TestServer(5, false);
+ InetSocketAddress addr = NetUtils.getConnectAddress(server);
+ server.start();
- // start client
- Client client = new Client(LongWritable.class, conf);
- call(client, addr, 0, conf);
- client.stop();
-
- // This call should throw IOException.
- call(client, addr, 0, conf);
+ // start client
+ Client client = new Client(LongWritable.class, conf);
+ call(client, addr, 0, conf);
+ client.stop();
+
+ // This call should throw IOException.
+ call(client, addr, 0, conf);
+ });
}
/**
* Check that file descriptors aren't leaked by starting
* and stopping IPC servers.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testSocketLeak() throws IOException {
- Assume.assumeTrue(FD_DIR.exists()); // only run on Linux
+ assumeTrue(FD_DIR.exists()); // only run on Linux
long startFds = countOpenFileDescriptors();
for (int i = 0; i < 50; i++) {
@@ -1216,15 +1243,16 @@ public void testSocketLeak() throws IOException {
}
long endFds = countOpenFileDescriptors();
- assertTrue("Leaked " + (endFds - startFds) + " file descriptors",
- endFds - startFds < 20);
+ assertTrue(endFds - startFds < 20,
+ "Leaked " + (endFds - startFds) + " file descriptors");
}
/**
* Check if Client is interrupted after handling
* InterruptedException during cleanup
*/
- @Test(timeout=30000)
+ @Test
+ @Timeout(value = 30)
public void testInterrupted() {
Client client = new Client(LongWritable.class, conf);
Thread.currentThread().interrupt();
@@ -1234,7 +1262,7 @@ public void testInterrupted() {
LOG.info("Expected thread interrupt during client cleanup");
} catch (AssertionError e) {
LOG.error("The Client did not interrupt after handling an Interrupted Exception");
- Assert.fail("The Client did not interrupt after handling an Interrupted Exception");
+ fail("The Client did not interrupt after handling an Interrupted Exception");
}
// Clear Thread interrupt
Thread.interrupted();
@@ -1244,31 +1272,36 @@ private long countOpenFileDescriptors() {
return FD_DIR.list().length;
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcFromHadoop_0_18_13() throws IOException {
doIpcVersionTest(NetworkTraces.HADOOP_0_18_3_RPC_DUMP,
NetworkTraces.RESPONSE_TO_HADOOP_0_18_3_RPC);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcFromHadoop0_20_3() throws IOException {
doIpcVersionTest(NetworkTraces.HADOOP_0_20_3_RPC_DUMP,
NetworkTraces.RESPONSE_TO_HADOOP_0_20_3_RPC);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testIpcFromHadoop0_21_0() throws IOException {
doIpcVersionTest(NetworkTraces.HADOOP_0_21_0_RPC_DUMP,
NetworkTraces.RESPONSE_TO_HADOOP_0_21_0_RPC);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testHttpGetResponse() throws IOException {
doIpcVersionTest("GET / HTTP/1.0\r\n\r\n".getBytes(),
Server.RECEIVED_HTTP_REQ_RESPONSE.getBytes());
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testConnectionRetriesOnSocketTimeoutExceptions() throws IOException {
Configuration conf = new Configuration();
// set max retries to 0
@@ -1294,7 +1327,8 @@ static class CallInfo {
* (1) the rpc server uses the call id/retry provided by the rpc client, and
* (2) the rpc client receives the same call id/retry from the rpc server.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testCallIdAndRetry() throws IOException {
final CallInfo info = new CallInfo();
@@ -1311,8 +1345,8 @@ Call createCall(RpcKind rpcKind, Writable rpcRequest) {
@Override
void checkResponse(RpcResponseHeaderProto header) throws IOException {
super.checkResponse(header);
- Assert.assertEquals(info.id, header.getCallId());
- Assert.assertEquals(info.retry, header.getRetryCount());
+ assertEquals(info.id, header.getCallId());
+ assertEquals(info.retry, header.getRetryCount());
}
};
@@ -1321,8 +1355,8 @@ void checkResponse(RpcResponseHeaderProto header) throws IOException {
server.callListener = new Runnable() {
@Override
public void run() {
- Assert.assertEquals(info.id, Server.getCallId());
- Assert.assertEquals(info.retry, Server.getCallRetryCount());
+ assertEquals(info.id, Server.getCallId());
+ assertEquals(info.retry, Server.getCallRetryCount());
}
};
@@ -1343,11 +1377,12 @@ public void run() {
* caller is notified.
* @throws IOException
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testReceiveStateBeforeCallerNotification() throws IOException {
AtomicBoolean stateReceived = new AtomicBoolean(false);
- AlignmentContext alignmentContext = Mockito.mock(AlignmentContext.class);
- Mockito.doAnswer((Answer) invocation -> {
+ AlignmentContext alignmentContext = mock(AlignmentContext.class);
+ doAnswer((Answer) invocation -> {
Thread.sleep(1000);
stateReceived.set(true);
return null;
@@ -1362,7 +1397,7 @@ public void testReceiveStateBeforeCallerNotification() throws IOException {
server.start();
call(client, new LongWritable(RANDOM.nextLong()), addr,
0, conf, alignmentContext);
- Assert.assertTrue(stateReceived.get());
+ assertTrue(stateReceived.get());
} finally {
client.stop();
server.stop();
@@ -1378,7 +1413,8 @@ interface DummyProtocol {
/**
* Test the retry count while used in a retry proxy.
*/
- @Test(timeout=100000)
+ @Test
+ @Timeout(value = 100)
public void testRetryProxy() throws IOException {
final Client client = new Client(LongWritable.class, conf);
@@ -1387,7 +1423,7 @@ public void testRetryProxy() throws IOException {
private int retryCount = 0;
@Override
public void run() {
- Assert.assertEquals(retryCount++, Server.getCallRetryCount());
+ assertEquals(retryCount++, Server.getCallRetryCount());
}
};
@@ -1404,7 +1440,7 @@ public void run() {
try {
server.start();
retryProxy.dummyRun();
- Assert.assertEquals(TestInvocationHandler.retry, totalRetry + 1);
+ assertEquals(TestInvocationHandler.retry, totalRetry + 1);
} finally {
Client.setCallIdAndRetryCount(0, 0, null);
client.stop();
@@ -1416,39 +1452,41 @@ public void run() {
* Test that there is no retry when invalid token exception is thrown.
* Verfies fix for HADOOP-12054
*/
- @Test(expected = InvalidToken.class)
+ @Test
public void testNoRetryOnInvalidToken() throws IOException {
- final Client client = new Client(LongWritable.class, conf);
- final TestServer server = new TestServer(1, false);
- TestInvalidTokenHandler handler =
- new TestInvalidTokenHandler(client, server);
- DummyProtocol proxy = (DummyProtocol) Proxy.newProxyInstance(
- DummyProtocol.class.getClassLoader(),
- new Class[] { DummyProtocol.class }, handler);
- FailoverProxyProvider provider =
- new DefaultFailoverProxyProvider(
- DummyProtocol.class, proxy);
- DummyProtocol retryProxy =
- (DummyProtocol) RetryProxy.create(DummyProtocol.class, provider,
- RetryPolicies.failoverOnNetworkException(
- RetryPolicies.TRY_ONCE_THEN_FAIL, 100, 100, 10000, 0));
+ assertThrows(InvalidToken.class, () -> {
+ final Client client = new Client(LongWritable.class, conf);
+ final TestServer server = new TestServer(1, false);
+ TestInvalidTokenHandler handler =
+ new TestInvalidTokenHandler(client, server);
+ DummyProtocol proxy = (DummyProtocol) Proxy.newProxyInstance(
+ DummyProtocol.class.getClassLoader(),
+ new Class[]{DummyProtocol.class}, handler);
+ FailoverProxyProvider provider =
+ new DefaultFailoverProxyProvider<>(DummyProtocol.class, proxy);
+ DummyProtocol retryProxy =
+ (DummyProtocol) RetryProxy.create(DummyProtocol.class, provider,
+ RetryPolicies.failoverOnNetworkException(
+ RetryPolicies.TRY_ONCE_THEN_FAIL, 100, 100, 10000, 0));
- try {
- server.start();
- retryProxy.dummyRun();
- } finally {
- // Check if dummyRun called only once
- assertThat(handler.invocations).isOne();
- Client.setCallIdAndRetryCount(0, 0, null);
- client.stop();
- server.stop();
- }
+ try {
+ server.start();
+ retryProxy.dummyRun();
+ } finally {
+ // Check if dummyRun called only once
+ assertThat(handler.invocations).isOne();
+ Client.setCallIdAndRetryCount(0, 0, null);
+ client.stop();
+ server.stop();
+ }
+ });
}
/**
* Test if the rpc server gets the default retry count (0) from client.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testInitialCallRetryCount() throws IOException {
// Override client to store the call id
final Client client = new Client(LongWritable.class, conf);
@@ -1460,7 +1498,7 @@ public void testInitialCallRetryCount() throws IOException {
public void run() {
// we have not set the retry count for the client, thus on the server
// side we should see retry count as 0
- Assert.assertEquals(0, Server.getCallRetryCount());
+ assertEquals(0, Server.getCallRetryCount());
}
};
@@ -1479,7 +1517,8 @@ public void run() {
/**
* Test if the rpc server gets the retry count from client.
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testCallRetryCount() throws IOException {
final int retryCount = 255;
// Override client to store the call id
@@ -1493,7 +1532,7 @@ public void testCallRetryCount() throws IOException {
public void run() {
// we have not set the retry count for the client, thus on the server
// side we should see retry count as 0
- Assert.assertEquals(retryCount, Server.getCallRetryCount());
+ assertEquals(retryCount, Server.getCallRetryCount());
}
};
@@ -1514,7 +1553,8 @@ public void run() {
* even if multiple threads are using the same client.
* @throws InterruptedException
*/
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testUniqueSequentialCallIds()
throws IOException, InterruptedException {
int serverThreads = 10, callerCount = 100, perCallerCallCount = 100;
@@ -1623,10 +1663,11 @@ public void testClientGetTimeout() throws IOException {
assertThat(Client.getTimeout(config)).isEqualTo(-1);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testSetupConnectionShouldNotBlockShutdown() throws Exception {
// Start server
- SocketFactory mockFactory = Mockito.mock(SocketFactory.class);
+ SocketFactory mockFactory = mock(SocketFactory.class);
Server server = new TestServer(1, true);
final InetSocketAddress addr = NetUtils.getConnectAddress(server);
@@ -1669,7 +1710,7 @@ public Boolean get() {
private void assertRetriesOnSocketTimeouts(Configuration conf,
int maxTimeoutRetries) throws IOException {
- SocketFactory mockFactory = Mockito.mock(SocketFactory.class);
+ SocketFactory mockFactory = mock(SocketFactory.class);
doThrow(new ConnectTimeoutException("fake")).when(mockFactory).createSocket();
Client client = new Client(LongWritable.class, conf, mockFactory);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9090);
@@ -1677,18 +1718,20 @@ private void assertRetriesOnSocketTimeouts(Configuration conf,
call(client, RANDOM.nextLong(), address, conf);
fail("Not throwing the SocketTimeoutException");
} catch (SocketTimeoutException e) {
- Mockito.verify(mockFactory, Mockito.times(maxTimeoutRetries))
+ verify(mockFactory, times(maxTimeoutRetries))
.createSocket();
}
client.stop();
}
- @Test(timeout=4000)
+ @Test
+ @Timeout(value = 4)
public void testInsecureVersionMismatch() throws IOException {
checkVersionMismatch();
}
- @Test(timeout=4000)
+ @Test
+ @Timeout(value = 4)
public void testSecureVersionMismatch() throws IOException {
SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, conf);
UserGroupInformation.setConfiguration(conf);
@@ -1722,13 +1765,13 @@ public void run() {
Client client = new Client(LongWritable.class, conf);
call(client, 0, addr, conf);
} catch (RemoteException re) {
- Assert.assertEquals(RPC.VersionMismatch.class.getName(),
+ assertEquals(RPC.VersionMismatch.class.getName(),
re.getClassName());
- Assert.assertEquals(NetworkTraces.HADOOP0_20_ERROR_MSG,
+ assertEquals(NetworkTraces.HADOOP0_20_ERROR_MSG,
re.getMessage());
return;
}
- Assert.fail("didn't get version mismatch");
+ fail("didn't get version mismatch");
}
}
@@ -1747,13 +1790,13 @@ public void testRpcResponseLimit() throws Throwable {
try {
call(client, 0, addr, conf);
} catch (IOException ioe) {
- Assert.assertNotNull(ioe);
- Assert.assertEquals(RpcException.class, ioe.getClass());
- Assert.assertTrue(ioe.getMessage().contains(
+ assertNotNull(ioe);
+ assertEquals(RpcException.class, ioe.getClass());
+ assertTrue(ioe.getMessage().contains(
"exceeds maximum data length"));
return;
}
- Assert.fail("didn't get limit exceeded");
+ fail("didn't get limit exceeded");
}
@Test
@@ -1766,13 +1809,14 @@ public void testProxyUserBinding() throws Exception {
checkUserBinding(true);
}
- @Test(timeout=60000)
+ @Test
+ @Timeout(value = 60)
public void testUpdateAddressEnsureResolved() throws Exception {
// start server
Server server = new TestServer(1, false);
server.start();
- SocketFactory mockFactory = Mockito.mock(SocketFactory.class);
+ SocketFactory mockFactory = mock(SocketFactory.class);
doThrow(new ConnectTimeoutException("fake")).when(mockFactory)
.createSocket();
Client client = new Client(LongWritable.class, conf, mockFactory);
@@ -1811,16 +1855,16 @@ private void checkUserBinding(boolean asProxy) throws Exception {
Socket s;
// don't attempt bind with no service host.
s = checkConnect(null, asProxy);
- Mockito.verify(s, Mockito.never()).bind(any(SocketAddress.class));
+ verify(s, never()).bind(any(SocketAddress.class));
// don't attempt bind with service host not belonging to this host.
s = checkConnect("1.2.3.4", asProxy);
- Mockito.verify(s, Mockito.never()).bind(any(SocketAddress.class));
+ verify(s, never()).bind(any(SocketAddress.class));
// do attempt bind when service host is this host.
InetAddress addr = InetAddress.getLocalHost();
s = checkConnect(addr.getHostAddress(), asProxy);
- Mockito.verify(s).bind(new InetSocketAddress(addr, 0));
+ verify(s).bind(new InetSocketAddress(addr, 0));
}
// dummy protocol that claims to support kerberos.
@@ -1838,7 +1882,7 @@ private Socket checkConnect(String addr, boolean asProxy) throws Exception {
principal.append("@REALM");
UserGroupInformation ugi =
spy(UserGroupInformation.createRemoteUser(principal.toString()));
- Mockito.doReturn(true).when(ugi).hasKerberosCredentials();
+ doReturn(true).when(ugi).hasKerberosCredentials();
if (asProxy) {
ugi = UserGroupInformation.createProxyUser("proxy", ugi);
}
@@ -1846,11 +1890,11 @@ private Socket checkConnect(String addr, boolean asProxy) throws Exception {
// create a mock socket that throws on connect.
SocketException expectedConnectEx =
new SocketException("Expected connect failure");
- Socket s = Mockito.mock(Socket.class);
- SocketFactory mockFactory = Mockito.mock(SocketFactory.class);
- Mockito.doReturn(s).when(mockFactory).createSocket();
+ Socket s = mock(Socket.class);
+ SocketFactory mockFactory = mock(SocketFactory.class);
+ doReturn(s).when(mockFactory).createSocket();
doThrow(expectedConnectEx).when(s).connect(
- any(SocketAddress.class), Mockito.anyInt());
+ any(SocketAddress.class), anyInt());
// do a dummy call and expect it to throw an exception on connect.
// tests should verify if/how a bind occurred.
@@ -1864,7 +1908,7 @@ private Socket checkConnect(String addr, boolean asProxy) throws Exception {
fail("call didn't throw connect exception");
} catch (SocketException se) {
// ipc layer re-wraps exceptions, so check the cause.
- Assert.assertSame(expectedConnectEx, se.getCause());
+ assertSame(expectedConnectEx, se.getCause());
}
return s;
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPCServerResponder.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPCServerResponder.java
index 7d7905e6b4674..fa9a1606539ac 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPCServerResponder.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIPCServerResponder.java
@@ -18,7 +18,10 @@
package org.apache.hadoop.ipc;
-import static org.junit.Assert.*;
+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.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -41,8 +44,8 @@
import org.apache.hadoop.ipc.RPC.RpcKind;
import org.apache.hadoop.ipc.Server.Call;
import org.apache.hadoop.net.NetUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -189,7 +192,8 @@ public void checkServerResponder(final int handlerCount,
// call 4: sendResponse, should remain blocked
// call 5: immediate, prove handler is still free
// call 4: sendResponse, expect it to return
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testDeferResponse() throws IOException, InterruptedException {
final AtomicReference deferredCall = new AtomicReference();
final AtomicInteger count = new AtomicInteger();
@@ -234,11 +238,11 @@ public Integer call() throws IOException {
// make sure it blocked
try {
future1.get(1, TimeUnit.SECONDS);
- Assert.fail("ipc shouldn't have responded");
+ fail("ipc shouldn't have responded");
} catch (TimeoutException te) {
// ignore, expected
} catch (Exception ex) {
- Assert.fail("unexpected exception:"+ex);
+ fail("unexpected exception:"+ex);
}
assertFalse(future1.isDone());
waitingCalls[0] = deferredCall.get();
@@ -259,11 +263,11 @@ public Integer call() throws IOException {
// make sure it blocked
try {
future2.get(1, TimeUnit.SECONDS);
- Assert.fail("ipc shouldn't have responded");
+ fail("ipc shouldn't have responded");
} catch (TimeoutException te) {
// ignore, expected
} catch (Exception ex) {
- Assert.fail("unexpected exception:"+ex);
+ fail("unexpected exception:"+ex);
}
assertFalse(future2.isDone());
waitingCalls[1] = deferredCall.get();
@@ -280,17 +284,17 @@ public Integer call() throws IOException {
int val = future1.get(1, TimeUnit.SECONDS);
assertEquals(2, val);
} catch (Exception ex) {
- Assert.fail("unexpected exception:"+ex);
+ fail("unexpected exception:"+ex);
}
// make sure it's still blocked
try {
future2.get(1, TimeUnit.SECONDS);
- Assert.fail("ipc shouldn't have responded");
+ fail("ipc shouldn't have responded");
} catch (TimeoutException te) {
// ignore, expected
} catch (Exception ex) {
- Assert.fail("unexpected exception:"+ex);
+ fail("unexpected exception:"+ex);
}
assertFalse(future2.isDone());
@@ -303,7 +307,7 @@ public Integer call() throws IOException {
int val = future2.get(1, TimeUnit.SECONDS);
assertEquals(4, val);
} catch (Exception ex) {
- Assert.fail("unexpected exception:"+ex);
+ fail("unexpected exception:"+ex);
}
server.stop();
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIdentityProviders.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIdentityProviders.java
index b528186ad26a5..396014aa46874 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIdentityProviders.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestIdentityProviders.java
@@ -18,12 +18,12 @@
package org.apache.hadoop.ipc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.io.IOException;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMiniRPCBenchmark.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMiniRPCBenchmark.java
index a130fa9757a92..dd63b8b5d3766 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMiniRPCBenchmark.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMiniRPCBenchmark.java
@@ -18,7 +18,7 @@
package org.apache.hadoop.ipc;
import org.apache.hadoop.conf.Configuration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.event.Level;
/**
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMultipleProtocolServer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMultipleProtocolServer.java
index c1b0858697682..34ce1b2c30e36 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMultipleProtocolServer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestMultipleProtocolServer.java
@@ -18,22 +18,22 @@
package org.apache.hadoop.ipc;
import org.apache.hadoop.conf.Configuration;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class TestMultipleProtocolServer extends TestRpcBase {
private static RPC.Server server;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
super.setupConf();
server = setupTestServer(conf, 2);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
server.stop();
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProcessingDetails.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProcessingDetails.java
index 0ecc741b014b3..9858f6f090754 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProcessingDetails.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProcessingDetails.java
@@ -18,12 +18,12 @@
package org.apache.hadoop.ipc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.apache.hadoop.ipc.ProcessingDetails.Timing;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit tests for ProcessingDetails time unit conversion and output.
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRPCCompatibility.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRPCCompatibility.java
index d813c6b784f5d..4aa21890e3ed3 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRPCCompatibility.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRPCCompatibility.java
@@ -17,7 +17,9 @@
*/
package org.apache.hadoop.ipc;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -34,8 +36,7 @@
import org.apache.hadoop.ipc.protobuf.TestRpcServiceProtos.NewProtobufRpcProto;
import org.apache.hadoop.ipc.protobuf.TestRpcServiceProtos.NewerProtobufRpcProto;
import org.apache.hadoop.net.NetUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.apache.hadoop.thirdparty.protobuf.BlockingService;
import org.apache.hadoop.thirdparty.protobuf.RpcController;
@@ -71,8 +72,8 @@ public EmptyResponseProto ping(RpcController unused,
EmptyRequestProto request) throws ServiceException {
// Ensure clientId is received
byte[] clientId = Server.getClientId();
- Assert.assertNotNull(Server.getClientId());
- Assert.assertEquals(16, clientId.length);
+ assertNotNull(Server.getClientId());
+ assertEquals(16, clientId.length);
return EmptyResponseProto.newBuilder().build();
}
@@ -81,8 +82,8 @@ public EmptyResponseProto echo(RpcController unused,
EmptyRequestProto request) throws ServiceException {
// Ensure clientId is received
byte[] clientId = Server.getClientId();
- Assert.assertNotNull(Server.getClientId());
- Assert.assertEquals(16, clientId.length);
+ assertNotNull(Server.getClientId());
+ assertEquals(16, clientId.length);
return EmptyResponseProto.newBuilder().build();
}
}
@@ -94,8 +95,8 @@ public EmptyResponseProto ping(RpcController unused,
EmptyRequestProto request) throws ServiceException {
// Ensure clientId is received
byte[] clientId = Server.getClientId();
- Assert.assertNotNull(Server.getClientId());
- Assert.assertEquals(16, clientId.length);
+ assertNotNull(Server.getClientId());
+ assertEquals(16, clientId.length);
return EmptyResponseProto.newBuilder().build();
}
@@ -115,8 +116,8 @@ public EmptyResponseProto ping(RpcController unused,
EmptyRequestProto request) throws ServiceException {
// Ensure clientId is received
byte[] clientId = Server.getClientId();
- Assert.assertNotNull(Server.getClientId());
- Assert.assertEquals(16, clientId.length);
+ assertNotNull(Server.getClientId());
+ assertEquals(16, clientId.length);
return EmptyResponseProto.newBuilder().build();
}
@@ -125,8 +126,8 @@ public EmptyResponseProto echo(RpcController unused, EmptyRequestProto request)
throws ServiceException {
// Ensure clientId is received
byte[] clientId = Server.getClientId();
- Assert.assertNotNull(Server.getClientId());
- Assert.assertEquals(16, clientId.length);
+ assertNotNull(Server.getClientId());
+ assertEquals(16, clientId.length);
return EmptyResponseProto.newBuilder().build();
}
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRpc.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRpc.java
index a9eaccb3bf3df..2130b78b5e147 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRpc.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestProtoBufRpc.java
@@ -38,12 +38,10 @@
import org.apache.hadoop.thirdparty.protobuf.BlockingService;
import org.apache.hadoop.thirdparty.protobuf.RpcController;
import org.apache.hadoop.thirdparty.protobuf.ServiceException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import java.io.IOException;
import java.net.URISyntaxException;
@@ -54,7 +52,7 @@
import static org.apache.hadoop.test.MetricsAsserts.assertCounterGt;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.Assume.assumeFalse;
/**
@@ -62,7 +60,6 @@
* This test depends on test.proto definition of types in src/test/proto
* and protobuf service definition from src/test/test_rpc_service.proto
*/
-@RunWith(Parameterized.class)
public class TestProtoBufRpc extends TestRpcBase {
private static RPC.Server server;
private final static int SLEEP_DURATION = 1000;
@@ -77,9 +74,11 @@ public class TestProtoBufRpc extends TestRpcBase {
*/
private boolean testWithLegacyFirst;
- public TestProtoBufRpc(Boolean testWithLegacy, Boolean testWithLegacyFirst) {
- this.testWithLegacy = testWithLegacy;
- this.testWithLegacyFirst = testWithLegacyFirst;
+ public void initTestProtoBufRpc(Boolean pTestWithLegacy, Boolean pTestWithLegacyFirst)
+ throws IOException {
+ this.testWithLegacy = pTestWithLegacy;
+ this.testWithLegacyFirst = pTestWithLegacyFirst;
+ setUp();
}
@ProtocolInfo(protocolName = "testProto2", protocolVersion = 1)
@@ -151,7 +150,6 @@ public TestProtosLegacy.SleepResponseProto sleep(
}
}
- @Parameters
public static Collection
*/
- @Test(timeout = 30000)
+ @Test
+ @Timeout(value = 30)
public void testRollingAveragesRollover() throws Exception {
final MetricsRecordBuilder rb = mockMetricsRecordBuilder();
final String name = "foo2";
@@ -135,7 +140,8 @@ public void testRollingAveragesRollover() throws Exception {
* initialization.
* @throws Exception
*/
- @Test(timeout = 30000)
+ @Test
+ @Timeout(value = 30)
public void testMutableRollingAveragesMetric() throws Exception {
DummyTestMetric testMetric = new DummyTestMetric();
testMetric.create();
@@ -157,10 +163,8 @@ public Boolean get() {
double metric1Avg = getDoubleGauge("[Metric1]RollingAvgTesting", rb);
double metric2Avg = getDoubleGauge("[Metric2]RollingAvgTesting", rb);
- Assert.assertTrue("The rolling average of metric1 is not as expected",
- metric1Avg == 500.0);
- Assert.assertTrue("The rolling average of metric2 is not as expected",
- metric2Avg == 1000.0);
+ assertTrue(metric1Avg == 500.0, "The rolling average of metric1 is not as expected");
+ assertTrue(metric2Avg == 1000.0, "The rolling average of metric2 is not as expected");
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/lib/TestUniqNames.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/lib/TestUniqNames.java
index fb09ed2465e7d..94b13f0ec47ed 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/lib/TestUniqNames.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/lib/TestUniqNames.java
@@ -18,8 +18,8 @@
package org.apache.hadoop.metrics2.lib;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestUniqNames {
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestFileSink.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestFileSink.java
index 420c16bef577e..3b4c80ed1b685 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestFileSink.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestFileSink.java
@@ -35,9 +35,10 @@
import org.apache.hadoop.metrics2.impl.MetricsSystemImpl;
import org.apache.hadoop.metrics2.impl.TestMetricsConfig;
import org.apache.hadoop.metrics2.lib.MutableGaugeInt;
-import org.junit.After;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestFileSink {
@@ -81,7 +82,8 @@ private File getTestTempFile(String prefix, String suffix) throws IOException {
return File.createTempFile(prefix, suffix, dir);
}
- @Test(timeout=6000)
+ @Test
+ @Timeout(value = 6)
public void testFileSink() throws IOException {
outFile = getTestTempFile("test-file-sink-", ".out");
final String outPath = outFile.getAbsolutePath();
@@ -136,7 +138,7 @@ public void testFileSink() throws IOException {
assertTrue(expectedContentPattern.matcher(outFileContent).matches());
}
- @After
+ @AfterEach
public void after() {
if (outFile != null) {
outFile.delete();
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestGraphiteMetrics.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestGraphiteMetrics.java
index 9ea81c6e4c62e..51d51bed1173e 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestGraphiteMetrics.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestGraphiteMetrics.java
@@ -23,7 +23,7 @@
import org.apache.hadoop.metrics2.MetricsTag;
import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
import org.apache.hadoop.metrics2.impl.MsInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
@@ -33,7 +33,7 @@
import java.util.Set;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestPrometheusMetricsSink.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestPrometheusMetricsSink.java
index 50c77e135ec40..5abdff6c142c0 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestPrometheusMetricsSink.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestPrometheusMetricsSink.java
@@ -35,11 +35,13 @@
import org.apache.hadoop.metrics2.lib.Interns;
import org.apache.hadoop.metrics2.lib.MutableCounterLong;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test prometheus Sink.
@@ -69,11 +71,8 @@ public void testPublish() throws IOException {
//THEN
String writtenMetrics = stream.toString(UTF_8.name());
System.out.println(writtenMetrics);
- Assert.assertTrue(
- "The expected metric line is missing from prometheus metrics output",
- writtenMetrics.contains(
- "test_metrics_num_bucket_create_fails{context=\"dfs\"")
- );
+ assertTrue(writtenMetrics.contains("test_metrics_num_bucket_create_fails{context=\"dfs\""),
+ "The expected metric line is missing from prometheus metrics output");
metrics.unregisterSource("TestMetrics");
metrics.stop();
@@ -110,16 +109,12 @@ public void testPublishMultiple() throws IOException {
//THEN
String writtenMetrics = stream.toString(UTF_8.name());
System.out.println(writtenMetrics);
- Assert.assertTrue(
- "The expected first metric line is missing from prometheus metrics output",
- writtenMetrics.contains(
- "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue1\"")
- );
- Assert.assertTrue(
- "The expected second metric line is missing from prometheus metrics output",
- writtenMetrics.contains(
- "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue2\"")
- );
+ assertTrue(writtenMetrics.contains(
+ "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue1\""),
+ "The expected first metric line is missing from prometheus metrics output");
+ assertTrue(writtenMetrics.contains(
+ "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue2\""),
+ "The expected second metric line is missing from prometheus metrics output");
metrics.unregisterSource("TestMetrics1");
metrics.unregisterSource("TestMetrics2");
@@ -161,16 +156,12 @@ public void testPublishFlush() throws IOException {
//THEN
String writtenMetrics = stream.toString(UTF_8.name());
System.out.println(writtenMetrics);
- Assert.assertFalse(
- "The first metric should not exist after flushing",
- writtenMetrics.contains(
- "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue1\"")
- );
- Assert.assertTrue(
- "The expected metric line is missing from prometheus metrics output",
- writtenMetrics.contains(
- "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue2\"")
- );
+ assertFalse(writtenMetrics.contains(
+ "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue1\""),
+ "The first metric should not exist after flushing");
+ assertTrue(writtenMetrics.contains(
+ "test_metrics_num_bucket_create_fails{context=\"dfs\",testtag=\"testTagValue2\""),
+ "The expected metric line is missing from prometheus metrics output");
metrics.unregisterSource("TestMetrics");
metrics.stop();
@@ -181,13 +172,13 @@ public void testPublishFlush() throws IOException {
public void testNamingCamelCase() {
PrometheusMetricsSink sink = new PrometheusMetricsSink();
- Assert.assertEquals("rpc_time_some_metrics",
+ assertEquals("rpc_time_some_metrics",
sink.prometheusName("RpcTime", "SomeMetrics"));
- Assert.assertEquals("om_rpc_time_om_info_keys",
+ assertEquals("om_rpc_time_om_info_keys",
sink.prometheusName("OMRpcTime", "OMInfoKeys"));
- Assert.assertEquals("rpc_time_small",
+ assertEquals("rpc_time_small",
sink.prometheusName("RpcTime", "small"));
}
@@ -198,7 +189,7 @@ public void testNamingPipeline() {
String recordName = "SCMPipelineMetrics";
String metricName = "NumBlocksAllocated-"
+ "RATIS-THREE-47659e3d-40c9-43b3-9792-4982fc279aba";
- Assert.assertEquals(
+ assertEquals(
"scm_pipeline_metrics_"
+ "num_blocks_allocated_"
+ "ratis_three_47659e3d_40c9_43b3_9792_4982fc279aba",
@@ -211,7 +202,7 @@ public void testNamingPeriods() {
String recordName = "org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl";
String metricName = "DfsUsed";
- Assert.assertEquals(
+ assertEquals(
"org_apache_hadoop_hdfs_server_datanode_fsdataset_impl_fs_dataset_impl_dfs_used",
sink.prometheusName(recordName, metricName));
}
@@ -222,7 +213,7 @@ public void testNamingWhitespaces() {
String recordName = "JvmMetrics";
String metricName = "GcCount" + "G1 Old Generation";
- Assert.assertEquals(
+ assertEquals(
"jvm_metrics_gc_count_g1_old_generation",
sink.prometheusName(recordName, metricName));
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestRollingFileSystemSink.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestRollingFileSystemSink.java
index ac5a0be75eb17..c7623f3db7516 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestRollingFileSystemSink.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestRollingFileSystemSink.java
@@ -24,11 +24,11 @@
import org.apache.hadoop.metrics2.MetricsException;
import org.apache.hadoop.metrics2.impl.ConfigBuilder;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test that the init() method picks up all the configuration settings
@@ -51,18 +51,15 @@ public void testInit() {
sink.init(conf);
- assertEquals("The roll interval was not set correctly",
- sink.rollIntervalMillis, 600000);
- assertEquals("The roll offset interval was not set correctly",
- sink.rollOffsetIntervalMillis, 1);
- assertEquals("The base path was not set correctly",
- sink.basePath, new Path("path"));
- assertEquals("ignore-error was not set correctly",
- sink.ignoreError, true);
- assertEquals("allow-append was not set correctly",
- sink.allowAppend, true);
- assertEquals("The source was not set correctly",
- sink.source, "src");
+ assertEquals(sink.rollIntervalMillis, 600000,
+ "The roll interval was not set correctly");
+ assertEquals(sink.rollOffsetIntervalMillis, 1,
+ "The roll offset interval was not set correctly");
+ assertEquals(sink.basePath, new Path("path"),
+ "The base path was not set correctly");
+ assertEquals(sink.ignoreError, true, "ignore-error was not set correctly");
+ assertEquals(sink.allowAppend, true, "allow-append was not set correctly");
+ assertEquals(sink.source, "src", "The source was not set correctly");
}
/**
@@ -80,36 +77,36 @@ public void testSetInitialFlushTime() {
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.YEAR, 2016);
- assertNull("Last flush time should have been null prior to calling init()",
- rfsSink.nextFlush);
+ assertNull(
+ rfsSink.nextFlush, "Last flush time should have been null prior to calling init()");
rfsSink.setInitialFlushTime(calendar.getTime());
long diff =
rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertEquals("The initial flush time was calculated incorrectly", 0L, diff);
+ assertEquals(0L, diff, "The initial flush time was calculated incorrectly");
calendar.set(Calendar.MILLISECOND, 10);
rfsSink.setInitialFlushTime(calendar.getTime());
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertEquals("The initial flush time was calculated incorrectly",
- -10L, diff);
+ assertEquals(
+ -10L, diff, "The initial flush time was calculated incorrectly");
calendar.set(Calendar.SECOND, 1);
calendar.set(Calendar.MILLISECOND, 10);
rfsSink.setInitialFlushTime(calendar.getTime());
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertEquals("The initial flush time was calculated incorrectly",
- -10L, diff);
+ assertEquals(
+ -10L, diff, "The initial flush time was calculated incorrectly");
// Try again with a random offset
rfsSink = new RollingFileSystemSink(1000, 100);
- assertNull("Last flush time should have been null prior to calling init()",
- rfsSink.nextFlush);
+ assertNull(
+ rfsSink.nextFlush, "Last flush time should have been null prior to calling init()");
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
@@ -117,29 +114,29 @@ public void testSetInitialFlushTime() {
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertTrue("The initial flush time was calculated incorrectly: " + diff,
- (diff == 0L) || ((diff > -1000L) && (diff < -900L)));
+ assertTrue((diff == 0L) || ((diff > -1000L) && (diff < -900L)),
+ "The initial flush time was calculated incorrectly: " + diff);
calendar.set(Calendar.MILLISECOND, 10);
rfsSink.setInitialFlushTime(calendar.getTime());
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertTrue("The initial flush time was calculated incorrectly: " + diff,
- (diff >= -10L) && (diff <= 0L) || ((diff > -1000L) && (diff < -910L)));
+ assertTrue((diff >= -10L) && (diff <= 0L) || ((diff > -1000L) && (diff < -910L)),
+ "The initial flush time was calculated incorrectly: " + diff);
calendar.set(Calendar.SECOND, 1);
calendar.set(Calendar.MILLISECOND, 10);
rfsSink.setInitialFlushTime(calendar.getTime());
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertTrue("The initial flush time was calculated incorrectly: " + diff,
- (diff >= -10L) && (diff <= 0L) || ((diff > -1000L) && (diff < -910L)));
+ assertTrue((diff >= -10L) && (diff <= 0L) || ((diff > -1000L) && (diff < -910L)),
+ "The initial flush time was calculated incorrectly: " + diff);
// Now try pathological settings
rfsSink = new RollingFileSystemSink(1000, 1000000);
- assertNull("Last flush time should have been null prior to calling init()",
- rfsSink.nextFlush);
+ assertNull(rfsSink.nextFlush,
+ "Last flush time should have been null prior to calling init()");
calendar.set(Calendar.MILLISECOND, 1);
calendar.set(Calendar.SECOND, 0);
@@ -147,8 +144,8 @@ public void testSetInitialFlushTime() {
diff = rfsSink.nextFlush.getTimeInMillis() - calendar.getTimeInMillis();
- assertTrue("The initial flush time was calculated incorrectly: " + diff,
- (diff > -1000L) && (diff <= 0L));
+ assertTrue((diff > -1000L) && (diff <= 0L),
+ "The initial flush time was calculated incorrectly: " + diff);
}
/**
@@ -170,26 +167,26 @@ public void testUpdateRollTime() {
rfsSink.nextFlush.setTime(calendar.getTime());
rfsSink.updateFlushTime(calendar.getTime());
- assertEquals("The next roll time should have been 1 second in the future",
- calendar.getTimeInMillis() + 1000,
- rfsSink.nextFlush.getTimeInMillis());
+ assertEquals(calendar.getTimeInMillis() + 1000,
+ rfsSink.nextFlush.getTimeInMillis(),
+ "The next roll time should have been 1 second in the future");
rfsSink.nextFlush.setTime(calendar.getTime());
calendar.add(Calendar.MILLISECOND, 10);
rfsSink.updateFlushTime(calendar.getTime());
- assertEquals("The next roll time should have been 990 ms in the future",
- calendar.getTimeInMillis() + 990,
- rfsSink.nextFlush.getTimeInMillis());
+ assertEquals(calendar.getTimeInMillis() + 990,
+ rfsSink.nextFlush.getTimeInMillis(),
+ "The next roll time should have been 990 ms in the future");
rfsSink.nextFlush.setTime(calendar.getTime());
calendar.add(Calendar.SECOND, 2);
calendar.add(Calendar.MILLISECOND, 10);
rfsSink.updateFlushTime(calendar.getTime());
- assertEquals("The next roll time should have been 990 ms in the future",
- calendar.getTimeInMillis() + 990,
- rfsSink.nextFlush.getTimeInMillis());
+ assertEquals(calendar.getTimeInMillis() + 990,
+ rfsSink.nextFlush.getTimeInMillis(),
+ "The next roll time should have been 990 ms in the future");
}
/**
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestStatsDMetrics.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestStatsDMetrics.java
index 2ce02f74f196d..4e813ceaa5af4 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestStatsDMetrics.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/TestStatsDMetrics.java
@@ -18,7 +18,7 @@
package org.apache.hadoop.metrics2.sink;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,7 +38,8 @@
import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
import org.apache.hadoop.metrics2.impl.MsInfo;
import org.apache.hadoop.metrics2.sink.StatsDSink.StatsD;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
public class TestStatsDMetrics {
@@ -51,7 +52,8 @@ private AbstractMetric makeMetric(String name, Number value,
return metric;
}
- @Test(timeout=3000)
+ @Test
+ @Timeout(value = 3)
public void testPutMetrics() throws IOException, IllegalAccessException {
final StatsDSink sink = new StatsDSink();
List tags = new ArrayList();
@@ -76,17 +78,17 @@ public void testPutMetrics() throws IOException, IllegalAccessException {
String result =new String(p.getData(), 0, p.getLength(),
StandardCharsets.UTF_8);
- assertTrue(
- "Received data did not match data sent",
- result.equals("host.process.jvm.Context.foo1:1.25|c") ||
- result.equals("host.process.jvm.Context.foo2:2.25|g"));
+ assertTrue(result.equals("host.process.jvm.Context.foo1:1.25|c") ||
+ result.equals("host.process.jvm.Context.foo2:2.25|g"),
+ "Received data did not match data sent");
} finally {
sink.close();
}
}
- @Test(timeout=3000)
+ @Test
+ @Timeout(value = 3)
public void testPutMetrics2() throws IOException, IllegalAccessException {
StatsDSink sink = new StatsDSink();
List tags = new ArrayList();
@@ -111,9 +113,9 @@ public void testPutMetrics2() throws IOException, IllegalAccessException {
String result =
new String(p.getData(), 0, p.getLength(), StandardCharsets.UTF_8);
- assertTrue("Received data did not match data sent",
- result.equals("process.jvm.Context.foo1:1|c") ||
- result.equals("process.jvm.Context.foo2:2|g"));
+ assertTrue(result.equals("process.jvm.Context.foo1:1|c") ||
+ result.equals("process.jvm.Context.foo2:2|g"),
+ "Received data did not match data sent");
} finally {
sink.close();
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/ganglia/TestGangliaSink.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/ganglia/TestGangliaSink.java
index 59ba18803f6bc..3a8c1dcd1083e 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/ganglia/TestGangliaSink.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/ganglia/TestGangliaSink.java
@@ -21,14 +21,14 @@
import org.apache.commons.configuration2.SubsetConfiguration;
import org.apache.hadoop.metrics2.impl.ConfigBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.DatagramSocket;
import java.net.MulticastSocket;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestGangliaSink {
@Test
@@ -38,8 +38,8 @@ public void testShouldCreateDatagramSocketByDefault() throws Exception {
GangliaSink30 gangliaSink = new GangliaSink30();
gangliaSink.init(conf);
DatagramSocket socket = gangliaSink.getDatagramSocket();
- assertFalse("Did not create DatagramSocket",
- socket == null || socket instanceof MulticastSocket);
+ assertFalse(socket == null || socket instanceof MulticastSocket,
+ "Did not create DatagramSocket");
}
@Test
@@ -49,8 +49,8 @@ public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Excepti
GangliaSink30 gangliaSink = new GangliaSink30();
gangliaSink.init(conf);
DatagramSocket socket = gangliaSink.getDatagramSocket();
- assertFalse("Did not create DatagramSocket",
- socket == null || socket instanceof MulticastSocket);
+ assertFalse(socket == null || socket instanceof MulticastSocket,
+ "Did not create DatagramSocket");
}
@Test
@@ -60,10 +60,10 @@ public void testShouldCreateMulticastSocket() throws Exception {
GangliaSink30 gangliaSink = new GangliaSink30();
gangliaSink.init(conf);
DatagramSocket socket = gangliaSink.getDatagramSocket();
- assertTrue("Did not create MulticastSocket",
- socket != null && socket instanceof MulticastSocket);
+ assertTrue(socket != null && socket instanceof MulticastSocket,
+ "Did not create MulticastSocket");
int ttl = ((MulticastSocket) socket).getTimeToLive();
- assertEquals("Did not set default TTL", 1, ttl);
+ assertEquals(1, ttl, "Did not set default TTL");
}
@Test
@@ -73,10 +73,10 @@ public void testShouldSetMulticastSocketTtl() throws Exception {
GangliaSink30 gangliaSink = new GangliaSink30();
gangliaSink.init(conf);
DatagramSocket socket = gangliaSink.getDatagramSocket();
- assertTrue("Did not create MulticastSocket",
- socket != null && socket instanceof MulticastSocket);
+ assertTrue(socket != null && socket instanceof MulticastSocket,
+ "Did not create MulticastSocket");
int ttl = ((MulticastSocket) socket).getTimeToLive();
- assertEquals("Did not set TTL", 3, ttl);
+ assertEquals(3, ttl, "Did not set TTL");
}
@Test
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/source/TestJvmMetrics.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/source/TestJvmMetrics.java
index 5eca1296994cc..2110f33981dde 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/source/TestJvmMetrics.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/source/TestJvmMetrics.java
@@ -20,13 +20,16 @@
import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
import org.apache.hadoop.util.GcTimeMonitor;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyFloat;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.verify;
import static org.apache.hadoop.test.MetricsAsserts.*;
import org.apache.hadoop.conf.Configuration;
@@ -36,26 +39,25 @@
import org.apache.hadoop.service.ServiceStateException;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.JvmPauseMonitor;
+import org.junit.jupiter.api.Timeout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.concurrent.TimeUnit;
import static org.apache.hadoop.metrics2.source.JvmMetricsInfo.*;
import static org.apache.hadoop.metrics2.impl.MsInfo.*;
+@Timeout(30)
public class TestJvmMetrics {
- @Rule
- public Timeout timeout = new Timeout(30000, TimeUnit.MILLISECONDS);
private JvmPauseMonitor pauseMonitor;
private GcTimeMonitor gcTimeMonitor;
/**
* Robust shutdown of the monitors if they haven't been stopped already.
*/
- @After
+ @AfterEach
public void teardown() {
ServiceOperations.stop(pauseMonitor);
if (gcTimeMonitor != null) {
@@ -129,7 +131,7 @@ public void testStopBeforeStart() throws Throwable {
pauseMonitor.init(new Configuration());
pauseMonitor.stop();
pauseMonitor.start();
- Assert.fail("Expected an exception, got " + pauseMonitor);
+ fail("Expected an exception, got " + pauseMonitor);
} catch (ServiceStateException e) {
GenericTestUtils.assertExceptionContains("cannot enter state", e);
}
@@ -141,7 +143,7 @@ public void testStopBeforeInit() throws Throwable {
try {
pauseMonitor.stop();
pauseMonitor.init(new Configuration());
- Assert.fail("Expected an exception, got " + pauseMonitor);
+ fail("Expected an exception, got " + pauseMonitor);
} catch (ServiceStateException e) {
GenericTestUtils.assertExceptionContains("cannot enter state", e);
}
@@ -193,10 +195,10 @@ public void alert(GcTimeMonitor.GcData gcData) {
gcCount = gcData.getAccumulatedGcCount();
}
- Assert.assertTrue(maxGcTimePercentage > 0);
- Assert.assertTrue(gcCount > 0);
- Assert.assertTrue(alerter.numAlerts > 0);
- Assert.assertTrue(alerter.maxGcTimePercentage >= alertGcPerc);
+ assertTrue(maxGcTimePercentage > 0);
+ assertTrue(gcCount > 0);
+ assertTrue(alerter.numAlerts > 0);
+ assertTrue(alerter.maxGcTimePercentage >= alertGcPerc);
}
@Test
@@ -205,8 +207,8 @@ public void testJvmMetricsSingletonWithSameProcessName() {
.initSingleton("test", null);
JvmMetrics jvmMetrics2 = org.apache.hadoop.metrics2.source.JvmMetrics
.initSingleton("test", null);
- Assert.assertEquals("initSingleton should return the singleton instance",
- jvmMetrics1, jvmMetrics2);
+ assertEquals(jvmMetrics1, jvmMetrics2,
+ "initSingleton should return the singleton instance");
}
@Test
@@ -217,12 +219,12 @@ public void testJvmMetricsSingletonWithDifferentProcessNames() {
final String process2Name = "process2";
JvmMetrics jvmMetrics2 = org.apache.hadoop.metrics2.source.JvmMetrics
.initSingleton(process2Name, null);
- Assert.assertEquals("initSingleton should return the singleton instance",
- jvmMetrics1, jvmMetrics2);
- Assert.assertEquals("unexpected process name of the singleton instance",
- process1Name, jvmMetrics1.processName);
- Assert.assertEquals("unexpected process name of the singleton instance",
- process1Name, jvmMetrics2.processName);
+ assertEquals(jvmMetrics1, jvmMetrics2,
+ "initSingleton should return the singleton instance");
+ assertEquals(process1Name, jvmMetrics1.processName,
+ "unexpected process name of the singleton instance");
+ assertEquals(process1Name, jvmMetrics2.processName,
+ "unexpected process name of the singleton instance");
}
/**
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMBeans.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMBeans.java
index 3c93dbee06953..fcd2e9aba7359 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMBeans.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMBeans.java
@@ -17,8 +17,7 @@
package org.apache.hadoop.metrics2.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.management.MBeanServer;
import javax.management.ObjectName;
@@ -26,6 +25,8 @@
import java.util.HashMap;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Test MXBean addition of key/value pairs to registered MBeans.
*/
@@ -46,7 +47,7 @@ public void testRegister() throws Exception {
int jmxCounter = (int) platformMBeanServer
.getAttribute(objectName, "Counter");
- Assert.assertEquals(counter, jmxCounter);
+ assertEquals(counter, jmxCounter);
} finally {
if (objectName != null) {
MBeans.unregister(objectName);
@@ -70,7 +71,7 @@ public void testRegisterWithAdditionalProperties() throws Exception {
ManagementFactory.getPlatformMBeanServer();
int jmxCounter =
(int) platformMBeanServer.getAttribute(objectName, "Counter");
- Assert.assertEquals(counter, jmxCounter);
+ assertEquals(counter, jmxCounter);
} finally {
if (objectName != null) {
MBeans.unregister(objectName);
@@ -85,7 +86,7 @@ public void testGetMbeanNameName() {
ObjectName mBeanName = MBeans.getMBeanName("Service",
"Name", properties);
- Assert.assertEquals("Service",
+ assertEquals("Service",
MBeans.getMbeanNameService(mBeanName));
properties.put("key", "value");
@@ -94,7 +95,7 @@ public void testGetMbeanNameName() {
"Name",
properties);
- Assert.assertEquals("Service",
+ assertEquals("Service",
MBeans.getMbeanNameService(mBeanName));
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMetricsCache.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMetricsCache.java
index e69947ecdc233..2d059b2386e42 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMetricsCache.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestMetricsCache.java
@@ -21,9 +21,14 @@
import java.util.Arrays;
import java.util.Collection;
-import org.junit.Test;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
+import org.junit.jupiter.api.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 static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import org.apache.hadoop.metrics2.AbstractMetric;
import org.apache.hadoop.metrics2.MetricsRecord;
@@ -48,15 +53,15 @@ public class TestMetricsCache {
verify(mr).name();
verify(mr).tags();
verify(mr).metrics();
- assertEquals("same record size", cr.metrics().size(),
- ((Collection)mr.metrics()).size());
- assertEquals("same metric value", 0, cr.getMetric("m"));
+ assertEquals(cr.metrics().size(), ((Collection) mr.metrics()).size(),
+ "same record size");
+ assertEquals(0, cr.getMetric("m"), "same metric value");
MetricsRecord mr2 = makeRecord("r",
Arrays.asList(makeTag("t", "tv")),
Arrays.asList(makeMetric("m", 2), makeMetric("m2", 42)));
cr = cache.update(mr2);
- assertEquals("contains 3 metric", 3, cr.metrics().size());
+ assertEquals(3, cr.metrics().size(), "contains 3 metric");
checkMetricValue("updated metric value", cr, "m", 2);
checkMetricValue("old metric value", cr, "m1", 1);
checkMetricValue("new metric value", cr, "m2", 42);
@@ -65,21 +70,21 @@ public class TestMetricsCache {
Arrays.asList(makeTag("t", "tv3")), // different tag value
Arrays.asList(makeMetric("m3", 3)));
cr = cache.update(mr3); // should get a new record
- assertEquals("contains 1 metric", 1, cr.metrics().size());
+ assertEquals(1, cr.metrics().size(), "contains 1 metric");
checkMetricValue("updated metric value", cr, "m3", 3);
// tags cache should be empty so far
- assertEquals("no tags", 0, cr.tags().size());
+ assertEquals(0, cr.tags().size(), "no tags");
// until now
cr = cache.update(mr3, true);
- assertEquals("Got 1 tag", 1, cr.tags().size());
- assertEquals("Tag value", "tv3", cr.getTag("t"));
+ assertEquals(1, cr.tags().size(), "Got 1 tag");
+ assertEquals("tv3", cr.getTag("t"), "Tag value");
checkMetricValue("Metric value", cr, "m3", 3);
}
@SuppressWarnings("deprecation")
@Test public void testGet() {
MetricsCache cache = new MetricsCache();
- assertNull("empty", cache.get("r", Arrays.asList(makeTag("t", "t"))));
+ assertNull(cache.get("r", Arrays.asList(makeTag("t", "t"))), "empty");
MetricsRecord mr = makeRecord("r",
Arrays.asList(makeTag("t", "t")),
Arrays.asList(makeMetric("m", 1)));
@@ -87,8 +92,8 @@ public class TestMetricsCache {
MetricsCache.Record cr = cache.get("r", mr.tags());
LOG.debug("tags="+ mr.tags() +" cr="+ cr);
- assertNotNull("Got record", cr);
- assertEquals("contains 1 metric", 1, cr.metrics().size());
+ assertNotNull(cr, "Got record");
+ assertEquals(1, cr.metrics().size(), "contains 1 metric");
checkMetricValue("new metric value", cr, "m", 1);
}
@@ -102,7 +107,7 @@ public class TestMetricsCache {
Arrays.asList(makeMetric("m", 0), makeMetric("m1", 1)));
MetricsCache.Record cr = cache.update(mr);
- assertTrue("t value should be null", null == cr.getTag("t"));
+ assertTrue(null == cr.getTag("t"), "t value should be null");
}
@Test public void testOverflow() {
@@ -115,17 +120,17 @@ public class TestMetricsCache {
Arrays.asList(makeMetric("m", i))));
checkMetricValue("new metric value", cr, "m", i);
if (i < MetricsCache.MAX_RECS_PER_NAME_DEFAULT) {
- assertNotNull("t0 is still there", cache.get("r", t0));
+ assertNotNull(cache.get("r", t0), "t0 is still there");
}
}
- assertNull("t0 is gone", cache.get("r", t0));
+ assertNull(cache.get("r", t0), "t0 is gone");
}
private void checkMetricValue(String description, MetricsCache.Record cr,
String key, Number val) {
- assertEquals(description, val, cr.getMetric(key));
- assertNotNull("metric not null", cr.getMetricInstance(key));
- assertEquals(description, val, cr.getMetricInstance(key).value());
+ assertEquals(val, cr.getMetric(key), description);
+ assertNotNull(cr.getMetricInstance(key), "metric not null");
+ assertEquals(val, cr.getMetricInstance(key).value(), description);
}
private MetricsRecord makeRecord(String name, Collection tags,
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleQuantiles.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleQuantiles.java
index aefd7a264b05d..dc361c9a2c1c3 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleQuantiles.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleQuantiles.java
@@ -25,8 +25,8 @@
import java.util.Random;
import org.apache.hadoop.metrics2.lib.MutableInverseQuantiles;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -39,7 +39,7 @@ public class TestSampleQuantiles {
SampleQuantiles estimator;
final static int NUM_REPEATS = 10;
- @Before
+ @BeforeEach
public void init() {
estimator = new SampleQuantiles(quantiles);
}
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleStat.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleStat.java
index 0fb0ad8ace959..04f8470de59c1 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleStat.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleStat.java
@@ -18,8 +18,8 @@
package org.apache.hadoop.metrics2.util;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test the running sample stat computation
@@ -32,36 +32,36 @@ public class TestSampleStat {
*/
@Test public void testSimple() {
SampleStat stat = new SampleStat();
- assertEquals("num samples", 0, stat.numSamples());
- assertEquals("mean", 0.0, stat.mean(), EPSILON);
- assertEquals("variance", 0.0, stat.variance(), EPSILON);
- assertEquals("stddev", 0.0, stat.stddev(), EPSILON);
- assertEquals("min", SampleStat.MinMax.DEFAULT_MIN_VALUE, stat.min(), EPSILON);
- assertEquals("max", SampleStat.MinMax.DEFAULT_MAX_VALUE, stat.max(), EPSILON);
+ assertEquals(0, stat.numSamples(), "num samples");
+ assertEquals(0.0, stat.mean(), EPSILON, "mean");
+ assertEquals(0.0, stat.variance(), EPSILON, "variance");
+ assertEquals(0.0, stat.stddev(), EPSILON, "stddev");
+ assertEquals(SampleStat.MinMax.DEFAULT_MIN_VALUE, stat.min(), EPSILON, "min");
+ assertEquals(SampleStat.MinMax.DEFAULT_MAX_VALUE, stat.max(), EPSILON, "max");
stat.add(3);
- assertEquals("num samples", 1L, stat.numSamples());
- assertEquals("mean", 3.0, stat.mean(), EPSILON);
- assertEquals("variance", 0.0, stat.variance(), EPSILON);
- assertEquals("stddev", 0.0, stat.stddev(), EPSILON);
- assertEquals("min", 3.0, stat.min(), EPSILON);
- assertEquals("max", 3.0, stat.max(), EPSILON);
+ assertEquals(1L, stat.numSamples(), "num samples");
+ assertEquals(3.0, stat.mean(), EPSILON, "mean");
+ assertEquals(0.0, stat.variance(), EPSILON, "variance");
+ assertEquals(0.0, stat.stddev(), EPSILON, "stddev");
+ assertEquals(3.0, stat.min(), EPSILON, "min");
+ assertEquals(3.0, stat.max(), EPSILON, "max");
stat.add(2).add(1);
- assertEquals("num samples", 3L, stat.numSamples());
- assertEquals("mean", 2.0, stat.mean(), EPSILON);
- assertEquals("variance", 1.0, stat.variance(), EPSILON);
- assertEquals("stddev", 1.0, stat.stddev(), EPSILON);
- assertEquals("min", 1.0, stat.min(), EPSILON);
- assertEquals("max", 3.0, stat.max(), EPSILON);
+ assertEquals(3L, stat.numSamples(), "num samples");
+ assertEquals(2.0, stat.mean(), EPSILON, "mean");
+ assertEquals(1.0, stat.variance(), EPSILON, "variance");
+ assertEquals(1.0, stat.stddev(), EPSILON, "stddev");
+ assertEquals(1.0, stat.min(), EPSILON, "min");
+ assertEquals(3.0, stat.max(), EPSILON, "max");
stat.reset();
- assertEquals("num samples", 0, stat.numSamples());
- assertEquals("mean", 0.0, stat.mean(), EPSILON);
- assertEquals("variance", 0.0, stat.variance(), EPSILON);
- assertEquals("stddev", 0.0, stat.stddev(), EPSILON);
- assertEquals("min", SampleStat.MinMax.DEFAULT_MIN_VALUE, stat.min(), EPSILON);
- assertEquals("max", SampleStat.MinMax.DEFAULT_MAX_VALUE, stat.max(), EPSILON);
+ assertEquals(0, stat.numSamples(), "num samples");
+ assertEquals(0.0, stat.mean(), EPSILON, "mean");
+ assertEquals(0.0, stat.variance(), EPSILON, "variance");
+ assertEquals(0.0, stat.stddev(), EPSILON, "stddev");
+ assertEquals(SampleStat.MinMax.DEFAULT_MIN_VALUE, stat.min(), EPSILON, "min");
+ assertEquals(SampleStat.MinMax.DEFAULT_MAX_VALUE, stat.max(), EPSILON, "max");
}
}