瀏覽代碼

HADOOP-19415. [JDK17] Upgrade JUnit from 4 to 5 in hadoop-common Part5. (#7357)

Co-authored-by: Chris Nauroth <cnauroth@apache.org>
Reviewed-by: Chris Nauroth <cnauroth@apache.org>
Signed-off-by: Shilun Fan <slfan1989@apache.org>
slfan1989 4 月之前
父節點
當前提交
81146fed2f
共有 77 個文件被更改,包括 1404 次插入1300 次删除
  1. 2 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java
  2. 16 16
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java
  3. 6 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java
  4. 4 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAutoCloseableLock.java
  5. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestBasicDiskValidator.java
  6. 19 34
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java
  7. 25 24
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java
  8. 14 15
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java
  9. 10 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java
  10. 3 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java
  11. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java
  12. 5 11
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java
  13. 8 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java
  14. 8 14
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java
  15. 5 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java
  16. 4 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDirectBufferPool.java
  17. 40 23
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java
  18. 21 21
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java
  19. 13 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java
  20. 15 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java
  21. 53 49
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java
  22. 8 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java
  23. 31 48
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java
  24. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java
  25. 38 28
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java
  26. 39 40
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java
  27. 19 17
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java
  28. 37 28
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java
  29. 43 38
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java
  30. 35 29
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java
  31. 24 20
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java
  32. 24 19
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java
  33. 30 27
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java
  34. 8 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java
  35. 17 15
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java
  36. 11 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java
  37. 6 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java
  38. 14 13
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java
  39. 31 30
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java
  40. 15 12
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java
  41. 3 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java
  42. 64 39
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java
  43. 3 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java
  44. 9 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java
  45. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java
  46. 8 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java
  47. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProtoUtil.java
  48. 4 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java
  49. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java
  50. 14 16
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java
  51. 11 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java
  52. 25 25
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java
  53. 25 34
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java
  54. 38 44
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java
  55. 10 8
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownThreadsHelper.java
  56. 10 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java
  57. 11 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java
  58. 3 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java
  59. 62 63
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java
  60. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java
  61. 11 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java
  62. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestTime.java
  63. 3 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java
  64. 19 19
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java
  65. 56 39
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java
  66. 61 46
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java
  67. 6 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java
  68. 54 54
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java
  69. 16 23
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java
  70. 40 35
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java
  71. 16 15
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java
  72. 16 15
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java
  73. 57 60
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java
  74. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java
  75. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java
  76. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java
  77. 27 34
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java

+ 2 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java

@@ -17,11 +17,8 @@
  */
 package org.apache.hadoop.test;
 
-import org.junit.Rule;
-import org.junit.rules.TestRule;
-import org.junit.rules.Timeout;
 
-import java.util.concurrent.TimeUnit;
+import org.junit.jupiter.api.Timeout;
 
 /**
  * Class for test units to extend in order that their individual tests will
@@ -29,9 +26,7 @@ import java.util.concurrent.TimeUnit;
  * This provides an automatic regression check for tests that begin running
  * longer than expected.
  */
+@Timeout(10)
 public class UnitTestcaseTimeLimit {
   public final int timeOutSecs = 10;
-  
-  @Rule public TestRule globalTimeout =
-      new Timeout(timeOutSecs, TimeUnit.SECONDS);
 }

+ 16 - 16
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java

@@ -20,11 +20,11 @@ package org.apache.hadoop.util;
 
 import static org.apache.hadoop.util.ApplicationClassLoader.constructUrlsFromClasspath;
 import static org.apache.hadoop.util.ApplicationClassLoader.isSystemClass;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -39,8 +39,8 @@ import java.util.zip.ZipEntry;
 import org.apache.commons.io.IOUtils;
 import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.test.GenericTestUtils;
-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.Splitter;
 
@@ -48,7 +48,7 @@ public class TestApplicationClassLoader {
   
   private static File testDir = GenericTestUtils.getTestDir("appclassloader");
   
-  @Before
+  @BeforeEach
   public void setUp() {
     FileUtil.fullyDelete(testDir);
     testDir.mkdirs();
@@ -57,17 +57,17 @@ public class TestApplicationClassLoader {
   @Test
   public void testConstructUrlsFromClasspath() throws Exception {
     File file = new File(testDir, "file");
-    assertTrue("Create file", file.createNewFile());
+    assertTrue(file.createNewFile(), "Create file");
 
     File dir = new File(testDir, "dir");
-    assertTrue("Make dir", dir.mkdir());
+    assertTrue(dir.mkdir(), "Make dir");
 
     File jarsDir = new File(testDir, "jarsdir");
-    assertTrue("Make jarsDir", jarsDir.mkdir());
+    assertTrue(jarsDir.mkdir(), "Make jarsDir");
     File nonJarFile = new File(jarsDir, "nonjar");
-    assertTrue("Create non-jar file", nonJarFile.createNewFile());
+    assertTrue(nonJarFile.createNewFile(), "Create non-jar file");
     File jarFile = new File(jarsDir, "a.jar");
-    assertTrue("Create jar file", jarFile.createNewFile());
+    assertTrue(jarFile.createNewFile(), "Create jar file");
 
     File nofile = new File(testDir, "nofile");
     // don't create nofile
@@ -130,11 +130,11 @@ public class TestApplicationClassLoader {
     ClassLoader appClassloader = new ApplicationClassLoader(
         new URL[] { testJar }, currentClassLoader, null);
 
-    assertNull("Resource should be null for current classloader",
-        currentClassLoader.getResourceAsStream("resource.txt"));
+    assertNull(currentClassLoader.getResourceAsStream("resource.txt"),
+        "Resource should be null for current classloader");
 
     InputStream in = appClassloader.getResourceAsStream("resource.txt");
-    assertNotNull("Resource should not be null for app classloader", in);
+    assertNotNull(in, "Resource should not be null for app classloader");
     assertEquals("hello", IOUtils.toString(in, StandardCharsets.UTF_8));
   }
   

+ 6 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java

@@ -17,8 +17,10 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+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.fail;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -70,8 +72,8 @@ public class TestAsyncDiskService {
     } catch (RuntimeException ex) {
       e = ex;
     }
-    assertNotNull("Executing a task on a non-existing volume should throw an "
-        + "Exception.", e);
+    assertNotNull(e, "Executing a task on a non-existing volume should throw an "
+        + "Exception.");
     
     service.shutdown();
     if (!service.awaitTermination(5000)) {

+ 4 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAutoCloseableLock.java

@@ -17,11 +17,11 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 /**
  * A test class for AutoCloseableLock.
  */

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestBasicDiskValidator.java

@@ -17,7 +17,7 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.hadoop.util.DiskChecker.DiskErrorException;
 
@@ -37,7 +37,7 @@ public class TestBasicDiskValidator extends TestDiskChecker {
 
       DiskValidatorFactory.getInstance(BasicDiskValidator.NAME).
           checkStatus(localDir);
-      assertTrue("call to checkDir() succeeded.", success);
+      assertTrue(success, "call to checkDir() succeeded.");
     } catch (DiskErrorException e) {
       // call to checkDir() succeeded even though it was expected to fail
       // if success is false, otherwise throw the exception

+ 19 - 34
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java

@@ -18,9 +18,10 @@
 package org.apache.hadoop.util;
 
 import java.io.IOException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestCacheableIPList {
 
@@ -44,10 +45,8 @@ public class TestCacheableIPList {
     CacheableIPList cipl = new CacheableIPList(
         new FileBasedIPList("ips.txt"),100);
 
-    assertFalse("10.113.221.222 is in the list",
-        cipl.isIn("10.113.221.222"));
-    assertFalse ("10.222.103.121 is  in the list",
-        cipl.isIn("10.222.103.121"));
+    assertFalse(cipl.isIn("10.113.221.222"), "10.113.221.222 is in the list");
+    assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is  in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
     String[]ips2 = {"10.119.103.112", "10.221.102.0/23",
@@ -56,10 +55,8 @@ public class TestCacheableIPList {
     TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2);
     Thread.sleep(101);
 
-    assertTrue("10.113.221.222 is not in the list",
-        cipl.isIn("10.113.221.222"));
-    assertTrue ("10.222.103.121 is not in the list",
-        cipl.isIn("10.222.103.121"));
+    assertTrue(cipl.isIn("10.113.221.222"), "10.113.221.222 is not in the list");
+    assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
   }
@@ -85,10 +82,8 @@ public class TestCacheableIPList {
     CacheableIPList cipl = new CacheableIPList(
         new FileBasedIPList("ips.txt"),100);
 
-    assertTrue("10.113.221.222 is not in the list",
-        cipl.isIn("10.113.221.222"));
-    assertTrue ("10.222.103.121 is not in the list",
-        cipl.isIn("10.222.103.121"));
+    assertTrue(cipl.isIn("10.113.221.222"), "10.113.221.222 is not in the list");
+    assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
     String[]ips2 = {"10.119.103.112", "10.221.102.0/23", "10.113.221.221"};
@@ -96,10 +91,8 @@ public class TestCacheableIPList {
     TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2);
     Thread.sleep(1005);
 
-    assertFalse("10.113.221.222 is in the list",
-        cipl.isIn("10.113.221.222"));
-    assertFalse ("10.222.103.121 is  in the list",
-        cipl.isIn("10.222.103.121"));
+    assertFalse(cipl.isIn("10.113.221.222"), "10.113.221.222 is in the list");
+    assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is  in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
   }
@@ -124,10 +117,8 @@ public class TestCacheableIPList {
     CacheableIPList cipl = new CacheableIPList(
         new FileBasedIPList("ips.txt"),100);
 
-    assertFalse("10.113.221.222 is in the list",
-        cipl.isIn("10.113.221.222"));
-    assertFalse ("10.222.103.121 is  in the list",
-        cipl.isIn("10.222.103.121"));
+    assertFalse(cipl.isIn("10.113.221.222"), "10.113.221.222 is in the list");
+    assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is  in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
     String[]ips2 = {"10.119.103.112", "10.221.102.0/23",
@@ -136,10 +127,8 @@ public class TestCacheableIPList {
     TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2);
     cipl.refresh();
 
-    assertTrue("10.113.221.222 is not in the list",
-        cipl.isIn("10.113.221.222"));
-    assertTrue ("10.222.103.121 is not in the list",
-        cipl.isIn("10.222.103.121"));
+    assertTrue(cipl.isIn("10.113.221.222"), "10.113.221.222 is not in the list");
+    assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
   }
@@ -165,10 +154,8 @@ public class TestCacheableIPList {
     CacheableIPList cipl = new CacheableIPList(
         new FileBasedIPList("ips.txt"),100);
 
-    assertTrue("10.113.221.222 is not in the list",
-        cipl.isIn("10.113.221.222"));
-    assertTrue ("10.222.103.121 is not in the list",
-        cipl.isIn("10.222.103.121"));
+    assertTrue(cipl.isIn("10.113.221.222"), "10.113.221.222 is not in the list");
+    assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
     String[]ips2 = {"10.119.103.112", "10.221.102.0/23", "10.113.221.221"};
@@ -176,10 +163,8 @@ public class TestCacheableIPList {
     TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2);
     cipl.refresh();
 
-    assertFalse("10.113.221.222 is in the list",
-        cipl.isIn("10.113.221.222"));
-    assertFalse ("10.222.103.121 is  in the list",
-        cipl.isIn("10.222.103.121"));
+    assertFalse(cipl.isIn("10.113.221.222"), "10.113.221.222 is in the list");
+    assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is  in the list");
 
     TestFileBasedIPList.removeFile("ips.txt");
   }

+ 25 - 24
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java

@@ -17,14 +17,15 @@
  */
 package org.apache.hadoop.util;
 
-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 java.util.ArrayList;
 import java.util.Iterator;
 import java.util.concurrent.TimeUnit;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestChunkedArrayList {
 
@@ -103,41 +104,41 @@ public class TestChunkedArrayList {
     // Iterate through all list elements.
     Iterator<Integer> iter = list.iterator();
     for (int i = 0; i < NUM_ELEMS; i++) {
-      Assert.assertTrue(iter.hasNext());
+      assertTrue(iter.hasNext());
       Integer val = iter.next();
-      Assert.assertEquals(Integer.valueOf(i), val);
+      assertEquals(Integer.valueOf(i), val);
     }
-    Assert.assertFalse(iter.hasNext());
-    Assert.assertEquals(NUM_ELEMS, list.size());
+    assertFalse(iter.hasNext());
+    assertEquals(NUM_ELEMS, list.size());
 
     // Remove even elements.
     iter = list.iterator();
     for (int i = 0; i < NUM_ELEMS; i++) {
-      Assert.assertTrue(iter.hasNext());
+      assertTrue(iter.hasNext());
       Integer val = iter.next();
-      Assert.assertEquals(Integer.valueOf(i), val);
+      assertEquals(Integer.valueOf(i), val);
       if (i % 2 == 0) {
         iter.remove();
       }
     }
-    Assert.assertFalse(iter.hasNext());
-    Assert.assertEquals(NUM_ELEMS / 2, list.size());
+    assertFalse(iter.hasNext());
+    assertEquals(NUM_ELEMS / 2, list.size());
 
     // Iterate through all odd list elements.
     iter = list.iterator();
     for (int i = 0; i < NUM_ELEMS / 2; i++) {
-      Assert.assertTrue(iter.hasNext());
+      assertTrue(iter.hasNext());
       Integer val = iter.next();
-      Assert.assertEquals(Integer.valueOf(1 + (2 * i)), val);
+      assertEquals(Integer.valueOf(1 + (2 * i)), val);
       iter.remove();
     }
-    Assert.assertFalse(iter.hasNext());
+    assertFalse(iter.hasNext());
 
     // Check that list is now empty.
-    Assert.assertEquals(0, list.size());
-    Assert.assertTrue(list.isEmpty());
+    assertEquals(0, list.size());
+    assertTrue(list.isEmpty());
     iter = list.iterator();
-    Assert.assertFalse(iter.hasNext());
+    assertFalse(iter.hasNext());
   }
 
   @Test
@@ -148,15 +149,15 @@ public class TestChunkedArrayList {
       list.add(i);
     }
 
-    Assert.assertEquals(Integer.valueOf(100), list.get(100));
-    Assert.assertEquals(Integer.valueOf(1000), list.get(1000));
-    Assert.assertEquals(Integer.valueOf(10000), list.get(10000));
-    Assert.assertEquals(Integer.valueOf(100000), list.get(100000));
+    assertEquals(Integer.valueOf(100), list.get(100));
+    assertEquals(Integer.valueOf(1000), list.get(1000));
+    assertEquals(Integer.valueOf(10000), list.get(10000));
+    assertEquals(Integer.valueOf(100000), list.get(100000));
 
     Iterator<Integer> iter = list.iterator();
     iter.next();
     iter.remove();
-    Assert.assertEquals(Integer.valueOf(1), list.get(0));
+    assertEquals(Integer.valueOf(1), list.get(0));
 
     iter = list.iterator();
     for (int i = 0; i < 500; i++) {
@@ -164,7 +165,7 @@ public class TestChunkedArrayList {
     }
     iter.remove();
 
-    Assert.assertEquals(Integer.valueOf(502), list.get(500));
-    Assert.assertEquals(Integer.valueOf(602), list.get(600));
+    assertEquals(Integer.valueOf(502), list.get(500));
+    assertEquals(Integer.valueOf(602), list.get(600));
   }
 }

+ 14 - 15
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java

@@ -23,42 +23,41 @@ import java.io.File;
 import org.apache.hadoop.fs.viewfs.ViewFileSystem;
 
 import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.assertj.core.api.Assertions.assertThat;
 
 public class TestClassUtil {
 
-  @Test(timeout=10000)
+  @Test
+  @Timeout(value = 10)
   public void testFindContainingJar() {
     String containingJar = ClassUtil.findContainingJar(Assertions.class);
-    Assertions
-        .assertThat(containingJar)
+    assertThat(containingJar)
         .describedAs("Containing jar for %s", Assertions.class)
         .isNotNull();
     File jarFile = new File(containingJar);
-    Assertions
-        .assertThat(jarFile)
+    assertThat(jarFile)
         .describedAs("Containing jar %s", jarFile)
         .exists();
-    Assertions
-        .assertThat(jarFile.getName())
+    assertThat(jarFile.getName())
         .describedAs("Containing jar name %s", jarFile.getName())
         .matches("assertj-core.*[.]jar");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testFindContainingClass() {
     String classFileLocation = ClassUtil.findClassLocation(ViewFileSystem.class);
-    Assertions
-        .assertThat(classFileLocation)
+    assertThat(classFileLocation)
         .describedAs("Class path for %s", ViewFileSystem.class)
         .isNotNull();
     File classFile = new File(classFileLocation);
-    Assertions
-        .assertThat(classFile)
+    assertThat(classFile)
         .describedAs("Containing class file %s", classFile)
         .exists();
-    Assertions
-        .assertThat(classFile.getName())
+    assertThat(classFile.getName())
         .describedAs("Containing class file name %s", classFile.getName())
         .matches("ViewFileSystem.class");
   }

+ 10 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java

@@ -17,7 +17,11 @@
  */
 package org.apache.hadoop.util;
 
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -32,9 +36,9 @@ import java.util.jar.Manifest;
 import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,7 +61,7 @@ public class TestClasspath {
   private ByteArrayOutputStream stdout, stderr;
   private PrintStream printStdout, printStderr;
 
-  @Before
+  @BeforeEach
   public void setUp() {
     assertTrue(FileUtil.fullyDelete(TEST_DIR));
     assertTrue(TEST_DIR.mkdirs());
@@ -73,7 +77,7 @@ public class TestClasspath {
     System.setErr(printStderr);
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     System.setOut(oldStdout);
     System.setErr(oldStderr);

+ 3 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java

@@ -18,12 +18,13 @@
 
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.util.List;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestConfTest {
 

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java

@@ -22,7 +22,7 @@ import java.util.Set;
 
 import org.assertj.core.api.Assertions;
 import org.assertj.core.api.IterableAssert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.test.AbstractHadoopTestBase;

+ 5 - 11
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java

@@ -17,9 +17,9 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import java.math.BigInteger;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestCpuTimeTracker {
   @Test
@@ -29,24 +29,18 @@ public class TestCpuTimeTracker {
         BigInteger.valueOf(100),
         System.currentTimeMillis());
     float val1 = tracker.getCpuTrackerUsagePercent();
-    assertTrue(
-        "Not invalid CPU usage",
-        val1 == -1.0);
+    assertTrue(val1 == -1.0, "Not invalid CPU usage");
     Thread.sleep(1000);
     tracker.updateElapsedJiffies(
         BigInteger.valueOf(200),
         System.currentTimeMillis());
     float val2 = tracker.getCpuTrackerUsagePercent();
-    assertTrue(
-        "Not positive CPU usage",
-        val2 > 0);
+    assertTrue(val2 > 0, "Not positive CPU usage");
     Thread.sleep(1000);
     tracker.updateElapsedJiffies(
         BigInteger.valueOf(0),
         System.currentTimeMillis());
     float val3 = tracker.getCpuTrackerUsagePercent();
-    assertTrue(
-        "Not positive CPU usage",
-        val3 == 0.0);
+    assertTrue(val3 == 0.0, "Not positive CPU usage");
   }
 }

+ 8 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java

@@ -22,22 +22,21 @@ import java.io.DataInputStream;
 import java.io.IOException;
 import java.util.Objects;
 import java.util.Random;
-import java.util.concurrent.TimeUnit;
 
 import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
-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.assertNotEquals;
 
 /**
  * Unittests for CrcComposer.
  */
+@Timeout(10)
 public class TestCrcComposer {
-  @Rule
-  public Timeout globalTimeout = new Timeout(10000, TimeUnit.MILLISECONDS);
 
   private final Random rand = new Random(1234);
 
@@ -55,7 +54,7 @@ public class TestCrcComposer {
   private byte[] crcBytesByChunk;
   private byte[] crcBytesByCell;
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException {
     rand.nextBytes(data);
     fullCrc = getRangeChecksum(data, 0, dataSize);

+ 8 - 14
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java

@@ -19,21 +19,18 @@ package org.apache.hadoop.util;
 
 import java.util.Objects;
 import java.util.Random;
-import java.util.concurrent.TimeUnit;
 
 import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 /**
  * Unittests for CrcUtil.
  */
+@Timeout(10)
 public class TestCrcUtil {
-  @Rule
-  public Timeout globalTimeout = new Timeout(10000, TimeUnit.MILLISECONDS);
 
   private static final Random RANDOM = new Random(1234);
 
@@ -132,13 +129,10 @@ public class TestCrcUtil {
       compositeCrc = CrcUtil.compose(
           compositeCrc, partialCrc, partialChunkSize, crcPolynomial);
     }
-    assertEquals(
-        String.format(
-            "Using CRC type '%s' with crcPolynomial '0x%08x' and chunkSize '%d'"
-            + ", expected '0x%08x', got '0x%08x'",
-            type, crcPolynomial, chunkSize, fullCrc, compositeCrc),
-        fullCrc,
-        compositeCrc);
+    assertEquals(fullCrc, compositeCrc, String.format(
+        "Using CRC type '%s' with crcPolynomial '0x%08x' and chunkSize '%d'" +
+        ", expected '0x%08x', got '0x%08x'",
+        type, crcPolynomial, chunkSize, fullCrc, compositeCrc));
   }
 
   /**

+ 5 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java

@@ -22,9 +22,12 @@ import java.util.Random;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.hadoop.fs.ChecksumException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-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;
 
 public class TestDataChecksum {
 

+ 4 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDirectBufferPool.java

@@ -17,14 +17,14 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
 
 import java.nio.ByteBuffer;
 import java.util.List;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestDirectBufferPool {
   final org.apache.hadoop.util.DirectBufferPool pool = new org.apache.hadoop.util.DirectBufferPool();

+ 40 - 23
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java

@@ -21,12 +21,15 @@ import java.io.*;
 import java.nio.file.Files;
 
 import org.apache.hadoop.util.DiskChecker.FileIoProvider;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import static org.junit.Assert.*;
+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.mockito.Mockito.*;
+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.conf.Configuration;
 import org.apache.hadoop.fs.FileStatus;
@@ -47,34 +50,38 @@ public class TestDiskChecker {
 
   private FileIoProvider fileIoProvider = null;
 
-  @Before
+  @BeforeEach
   public void setup() {
     // Some tests replace the static field DiskChecker#fileIoProvider.
     // Cache it so we can restore it after each test completes.
     fileIoProvider = DiskChecker.getFileOutputStreamProvider();
   }
 
-  @After
+  @AfterEach
   public void cleanup() {
     DiskChecker.replaceFileOutputStreamProvider(fileIoProvider);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testMkdirs_dirExists() throws Throwable {
     _mkdirs(true, defaultPerm, defaultPerm);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testMkdirs_noDir() throws Throwable {
     _mkdirs(false, defaultPerm, defaultPerm);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testMkdirs_dirExists_badUmask() throws Throwable {
     _mkdirs(true, defaultPerm, invalidPerm);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testMkdirs_noDir_badUmask() throws Throwable {
     _mkdirs(false, defaultPerm, invalidPerm);
   }
@@ -106,27 +113,32 @@ public class TestDiskChecker {
     }
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_normal() throws Throwable {
     _checkDirs(true, new FsPermission("755"), true);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notDir() throws Throwable {
     _checkDirs(false, new FsPermission("000"), false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notReadable() throws Throwable {
     _checkDirs(true, new FsPermission("000"), false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notWritable() throws Throwable {
     _checkDirs(true, new FsPermission("444"), false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notListable() throws Throwable {
     _checkDirs(true, new FsPermission("666"), false);   // not listable
   }
@@ -161,7 +173,7 @@ public class TestDiskChecker {
     try {
       DiskChecker.checkDir(FileSystem.getLocal(new Configuration()),
           new Path(localDir.getAbsolutePath()), perm);
-      assertTrue("checkDir success, expected failure", success);
+      assertTrue(success, "checkDir success, expected failure");
     } catch (DiskErrorException e) {
       if (success) {
         throw e; // Unexpected exception!
@@ -175,27 +187,32 @@ public class TestDiskChecker {
    * permission for result of mapper.
    */
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_normal_local() throws Throwable {
     checkDirs(true, "755", true);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notDir_local() throws Throwable {
     checkDirs(false, "000", false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notReadable_local() throws Throwable {
     checkDirs(true, "000", false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notWritable_local() throws Throwable {
     checkDirs(true, "444", false);
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCheckDir_notListable_local() throws Throwable {
     checkDirs(true, "666", false);
   }
@@ -207,7 +224,7 @@ public class TestDiskChecker {
         localDir.getAbsolutePath()));
     try {
       DiskChecker.checkDir(localDir);
-      assertTrue("checkDir success, expected failure", success);
+      assertTrue(success, "checkDir success, expected failure");
     } catch (DiskErrorException e) {
       if (success) {
         throw e; // Unexpected exception!

+ 21 - 21
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java

@@ -20,9 +20,8 @@ package org.apache.hadoop.util;
 
 import org.apache.hadoop.util.DiskChecker.DiskErrorException;
 import org.apache.hadoop.util.DiskChecker.FileIoProvider;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -30,19 +29,18 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.attribute.PosixFilePermissions;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 
 /**
  * Verify {@link DiskChecker} validation routines that perform
  * Disk IO.
  */
+@Timeout(30)
 public final class TestDiskCheckerWithDiskIo {
-  @Rule
-  public Timeout testTimeout = new Timeout(30_000, TimeUnit.MILLISECONDS);
 
   /**
    * Verify DiskChecker ignores at least 2 transient file creation errors.
@@ -57,11 +55,13 @@ public final class TestDiskCheckerWithDiskIo {
   /**
    * Verify DiskChecker bails after 3 file creation errors.
    */
-  @Test(expected = DiskErrorException.class)
+  @Test
   public final void testDiskIoDetectsCreateErrors() throws Throwable {
-    DiskChecker.replaceFileOutputStreamProvider(new TestFileIoProvider(
-        DiskChecker.DISK_IO_MAX_ITERATIONS, 0));
-    checkDirs(false);
+    assertThrows(DiskErrorException.class, () -> {
+      DiskChecker.replaceFileOutputStreamProvider(new TestFileIoProvider(
+          DiskChecker.DISK_IO_MAX_ITERATIONS, 0));
+      checkDirs(false);
+    });
   }
 
   /**
@@ -77,11 +77,13 @@ public final class TestDiskCheckerWithDiskIo {
   /**
    * Verify DiskChecker bails after 3 file write errors.
    */
-  @Test(expected = DiskErrorException.class)
+  @Test
   public final void testDiskIoDetectsWriteErrors() throws Throwable {
-    DiskChecker.replaceFileOutputStreamProvider(new TestFileIoProvider(
-        0, DiskChecker.DISK_IO_MAX_ITERATIONS));
-    checkDirs(false);
+    assertThrows(DiskErrorException.class, ()->{
+      DiskChecker.replaceFileOutputStreamProvider(new TestFileIoProvider(
+          0, DiskChecker.DISK_IO_MAX_ITERATIONS));
+      checkDirs(false);
+    });
   }
 
   /**
@@ -93,15 +95,13 @@ public final class TestDiskCheckerWithDiskIo {
     assertTrue(".001".matches("\\.00\\d$"));
     for (int i = 1; i < DiskChecker.DISK_IO_MAX_ITERATIONS; ++i) {
       final File file = DiskChecker.getFileNameForDiskIoCheck(rootDir, i);
-      assertTrue(
-          "File name does not match expected pattern: " + file,
-          file.toString().matches("^.*\\.[0-9]+$"));
+      assertTrue(file.toString().matches("^.*\\.[0-9]+$"),
+          "File name does not match expected pattern: " + file);
     }
     final File guidFile = DiskChecker.getFileNameForDiskIoCheck(
         rootDir, DiskChecker.DISK_IO_MAX_ITERATIONS);
-    assertTrue(
-        "File name does not match expected pattern: " + guidFile,
-        guidFile.toString().matches("^.*\\.[A-Za-z0-9-]+$"));
+    assertTrue(guidFile.toString().matches("^.*\\.[A-Za-z0-9-]+$"),
+        "File name does not match expected pattern: " + guidFile);
   }
 
   /**

+ 13 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java

@@ -17,10 +17,11 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-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.junit.jupiter.api.Assertions.assertThrows;
 
 import org.apache.hadoop.util.DiskChecker.DiskErrorException;
 
@@ -38,13 +39,13 @@ public class TestDiskValidatorFactory {
   @Test
   public void testGetInstance() throws DiskErrorException {
     DiskValidator diskValidator = DiskValidatorFactory.getInstance("basic");
-    assertNotNull("Fail to get the instance.", diskValidator);
+    assertNotNull(diskValidator, "Fail to get the instance.");
 
-    assertEquals("Fail to create the correct instance.",
-        diskValidator.getClass(), BasicDiskValidator.class);
+    assertEquals(diskValidator.getClass(), BasicDiskValidator.class,
+        "Fail to create the correct instance.");
 
-    assertNotNull("Fail to cache the object", DiskValidatorFactory.INSTANCES.
-        get(BasicDiskValidator.class));
+    assertNotNull(DiskValidatorFactory.INSTANCES.
+        get(BasicDiskValidator.class), "Fail to cache the object");
   }
 
   /**
@@ -52,8 +53,10 @@ public class TestDiskValidatorFactory {
    * a non-exist class.
    * @throws DiskErrorException if fail to get the instance.
    */
-  @Test(expected = DiskErrorException.class)
+  @Test
   public void testGetInstanceOfNonExistClass() throws DiskErrorException {
-    DiskValidatorFactory.getInstance("non-exist");
+    assertThrows(DiskErrorException.class, () -> {
+      DiskValidatorFactory.getInstance("non-exist");
+    });
   }
 }

+ 15 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java

@@ -17,11 +17,14 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 /**
  * The class to test DurationInfo.
  */
@@ -31,17 +34,17 @@ public class TestDurationInfo {
   @Test
   public void testDurationInfoCreation() throws Exception {
     DurationInfo info = new DurationInfo(log, "test");
-    Assert.assertTrue(info.value() >= 0);
+    assertTrue(info.value() >= 0);
     Thread.sleep(1000);
     info.finished();
-    Assert.assertTrue(info.value() > 0);
+    assertTrue(info.value() > 0);
 
     info = new DurationInfo(log, true, "test format %s", "value");
-    Assert.assertEquals("test format value: duration 0:00.000s",
+    assertEquals("test format value: duration 0:00.000s",
         info.toString());
 
     info = new DurationInfo(log, false, "test format %s", "value");
-    Assert.assertEquals("test format value: duration 0:00.000s",
+    assertEquals("test format value: duration 0:00.000s",
         info.toString());
   }
 
@@ -51,12 +54,14 @@ public class TestDurationInfo {
     Thread.sleep(1000);
     info.close();
     info.close();
-    Assert.assertTrue(info.value() > 0);
+    assertTrue(info.value() > 0);
   }
 
-  @Test(expected = NullPointerException.class)
+  @Test
   public void testDurationInfoCreationWithNullMsg() {
-    DurationInfo info = new DurationInfo(log, null);
-    info.close();
+    assertThrows(NullPointerException.class, ()->{
+      DurationInfo info = new DurationInfo(log, null);
+      info.close();
+    });
   }
 }

+ 53 - 49
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java

@@ -18,14 +18,14 @@
 package org.apache.hadoop.util;
 
 import static org.apache.hadoop.test.LambdaTestUtils.intercept;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.util.ExitUtil.ExitException;
 import org.apache.hadoop.util.ExitUtil.HaltException;
@@ -33,7 +33,7 @@ import org.apache.hadoop.test.AbstractHadoopTestBase;
 
 public class TestExitUtil extends AbstractHadoopTestBase {
 
-  @Before
+  @BeforeEach
   public void before() {
     ExitUtil.disableSystemExit();
     ExitUtil.disableSystemHalt();
@@ -41,7 +41,7 @@ public class TestExitUtil extends AbstractHadoopTestBase {
     ExitUtil.resetFirstHaltException();
   }
 
-  @After
+  @AfterEach
   public void after() {
     ExitUtil.resetFirstExitException();
     ExitUtil.resetFirstHaltException();
@@ -53,36 +53,39 @@ public class TestExitUtil extends AbstractHadoopTestBase {
     ExitException ee1 = new ExitException(1, "TestExitUtil forged 1st ExitException");
     ExitException ee2 = new ExitException(2, "TestExitUtil forged 2nd ExitException");
     // check proper initial settings
-    assertFalse("ExitUtil.terminateCalled initial value should be false",
-        ExitUtil.terminateCalled());
-    assertNull("ExitUtil.getFirstExitException initial value should be null",
-        ExitUtil.getFirstExitException());
+    assertFalse(ExitUtil.terminateCalled(),
+        "ExitUtil.terminateCalled initial value should be false");
+    assertNull(ExitUtil.getFirstExitException(),
+        "ExitUtil.getFirstExitException initial value should be null");
 
     // simulate/check 1st call
     ExitException ee = intercept(ExitException.class, ()->ExitUtil.terminate(ee1));
-    assertSame("ExitUtil.terminate should have rethrown its ExitException argument but it "
-        + "had thrown something else", ee1, ee);
-    assertTrue("ExitUtil.terminateCalled should be true after 1st ExitUtil.terminate call",
-        ExitUtil.terminateCalled());
-    assertSame("ExitUtil.terminate should store its 1st call's ExitException",
-        ee1, ExitUtil.getFirstExitException());
+    assertSame(ee1, ee, "ExitUtil.terminate should have rethrown its ExitException argument but it "
+        + "had thrown something else");
+    assertTrue(ExitUtil.terminateCalled(),
+        "ExitUtil.terminateCalled should be true after 1st ExitUtil.terminate call");
+    assertSame(ee1, ExitUtil.getFirstExitException(),
+        "ExitUtil.terminate should store its 1st call's ExitException");
 
     // simulate/check 2nd call not overwritting 1st one
     ee = intercept(ExitException.class, ()->ExitUtil.terminate(ee2));
-    assertSame("ExitUtil.terminate should have rethrown its HaltException argument but it "
-        + "had thrown something else", ee2, ee);
-    assertTrue("ExitUtil.terminateCalled should still be true after 2nd ExitUtil.terminate call",
-        ExitUtil.terminateCalled());
+    assertSame(ee2, ee,
+        "ExitUtil.terminate should have rethrown its HaltException argument but it "
+        + "had thrown something else");
+    assertTrue(ExitUtil.terminateCalled(),
+        "ExitUtil.terminateCalled should still be true after 2nd ExitUtil.terminate call");
     // 2nd call rethrown the 2nd ExitException yet only the 1st only should have been stored
-    assertSame("ExitUtil.terminate when called twice should only remember 1st call's "
-        + "ExitException", ee1, ExitUtil.getFirstExitException());
+    assertSame(ee1, ExitUtil.getFirstExitException(),
+        "ExitUtil.terminate when called twice should only remember 1st call's "
+        + "ExitException");
 
     // simulate cleanup, also tries to make sure state is ok for all junit still has to do
     ExitUtil.resetFirstExitException();
-    assertFalse("ExitUtil.terminateCalled should be false after "
-        + "ExitUtil.resetFirstExitException call", ExitUtil.terminateCalled());
-    assertNull("ExitUtil.getFirstExitException should be null after "
-        + "ExitUtil.resetFirstExitException call", ExitUtil.getFirstExitException());
+    assertFalse(ExitUtil.terminateCalled(), "ExitUtil.terminateCalled should be false after "
+        + "ExitUtil.resetFirstExitException call");
+    assertNull(ExitUtil.getFirstExitException(),
+        "ExitUtil.getFirstExitException should be null after "
+        + "ExitUtil.resetFirstExitException call");
   }
 
   @Test
@@ -94,34 +97,35 @@ public class TestExitUtil extends AbstractHadoopTestBase {
     HaltException he2 = new HaltException(2, "TestExitUtil forged 2nd HaltException");
 
     // check proper initial settings
-    assertFalse("ExitUtil.haltCalled initial value should be false",
-        ExitUtil.haltCalled());
-    assertNull("ExitUtil.getFirstHaltException initial value should be null",
-        ExitUtil.getFirstHaltException());
+    assertFalse(ExitUtil.haltCalled(),
+        "ExitUtil.haltCalled initial value should be false");
+    assertNull(ExitUtil.getFirstHaltException(),
+        "ExitUtil.getFirstHaltException initial value should be null");
 
     // simulate/check 1st call
     HaltException he = intercept(HaltException.class, ()->ExitUtil.halt(he1));
-    assertSame("ExitUtil.halt should have rethrown its HaltException argument but it had "
-        +"thrown something else", he1, he);
-    assertTrue("ExitUtil.haltCalled should be true after 1st ExitUtil.halt call",
-        ExitUtil.haltCalled());
-    assertSame("ExitUtil.halt should store its 1st call's HaltException",
-        he1, ExitUtil.getFirstHaltException());
+    assertSame(he1, he, "ExitUtil.halt should have rethrown its HaltException argument but it had "
+        +"thrown something else");
+    assertTrue(ExitUtil.haltCalled(),
+        "ExitUtil.haltCalled should be true after 1st ExitUtil.halt call");
+    assertSame(he1, ExitUtil.getFirstHaltException(),
+        "ExitUtil.halt should store its 1st call's HaltException");
 
     // simulate/check 2nd call not overwritting 1st one
     he = intercept(HaltException.class, ()->ExitUtil.halt(he2));
-    assertSame("ExitUtil.halt should have rethrown its HaltException argument but it had "
-        +"thrown something else", he2, he);
-    assertTrue("ExitUtil.haltCalled should still be true after 2nd ExitUtil.halt call",
-        ExitUtil.haltCalled());
-    assertSame("ExitUtil.halt when called twice should only remember 1st call's HaltException",
-        he1, ExitUtil.getFirstHaltException());
+    assertSame(he2, he, "ExitUtil.halt should have rethrown its HaltException argument but it had "
+        + "thrown something else");
+    assertTrue(ExitUtil.haltCalled(),
+        "ExitUtil.haltCalled should still be true after 2nd ExitUtil.halt call");
+    assertSame(he1, ExitUtil.getFirstHaltException(),
+        "ExitUtil.halt when called twice should only remember 1st call's HaltException");
 
     // simulate cleanup, also tries to make sure state is ok for all junit still has to do
     ExitUtil.resetFirstHaltException();
-    assertFalse("ExitUtil.haltCalled should be false after "
-        + "ExitUtil.resetFirstHaltException call", ExitUtil.haltCalled());
-    assertNull("ExitUtil.getFirstHaltException should be null after "
-        + "ExitUtil.resetFirstHaltException call", ExitUtil.getFirstHaltException());
+    assertFalse(ExitUtil.haltCalled(), "ExitUtil.haltCalled should be false after "
+        + "ExitUtil.resetFirstHaltException call");
+    assertNull(ExitUtil.getFirstHaltException(),
+        "ExitUtil.getFirstHaltException should be null after "
+        + "ExitUtil.resetFirstHaltException call");
   }
 }

+ 8 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java

@@ -17,18 +17,21 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import java.text.NumberFormat;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
 /**
  * Test for FastNumberFormat
  */
 public class TestFastNumberFormat {
   private final int MIN_DIGITS = 6;
 
-  @Test(timeout = 1000)
+  @Test
+  @Timeout(value = 1)
   public void testLongWithPadding() throws Exception {
     NumberFormat numberFormat = NumberFormat.getInstance();
     numberFormat.setGroupingUsed(false);
@@ -39,8 +42,8 @@ public class TestFastNumberFormat {
       StringBuilder sb = new StringBuilder();
       FastNumberFormat.format(sb, l, MIN_DIGITS);
       String fastNumberStr = sb.toString();
-      Assert.assertEquals("Number formats should be equal",
-          numberFormat.format(l), fastNumberStr);
+      assertEquals(
+          numberFormat.format(l), fastNumberStr, "Number formats should be equal");
     }
   }
 }

+ 31 - 48
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java

@@ -22,13 +22,16 @@ import java.io.IOException;
 import java.util.Arrays;
 
 import org.apache.commons.io.FileUtils;
-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 static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestFileBasedIPList {
 
-  @After
+  @AfterEach
   public void tearDown() {
     removeFile("ips.txt");
   }
@@ -47,23 +50,15 @@ public class TestFileBasedIPList {
 
     IPList ipList = new FileBasedIPList("ips.txt");
 
-    assertTrue ("10.119.103.112 is not in the list",
-        ipList.isIn("10.119.103.112"));
-    assertFalse ("10.119.103.113 is in the list",
-        ipList.isIn("10.119.103.113"));
-
-    assertTrue ("10.221.102.0 is not in the list",
-        ipList.isIn("10.221.102.0"));
-    assertTrue ("10.221.102.1 is not in the list",
-        ipList.isIn("10.221.102.1"));
-    assertTrue ("10.221.103.1 is not in the list",
-        ipList.isIn("10.221.103.1"));
-    assertTrue ("10.221.103.255 is not in the list",
-        ipList.isIn("10.221.103.255"));
-    assertFalse("10.221.104.0 is in the list",
-        ipList.isIn("10.221.104.0"));
-    assertFalse("10.221.104.1 is in the list",
-        ipList.isIn("10.221.104.1"));
+    assertTrue(ipList.isIn("10.119.103.112"), "10.119.103.112 is not in the list");
+    assertFalse(ipList.isIn("10.119.103.113"), "10.119.103.113 is in the list");
+
+    assertTrue(ipList.isIn("10.221.102.0"), "10.221.102.0 is not in the list");
+    assertTrue(ipList.isIn("10.221.102.1"), "10.221.102.1 is not in the list");
+    assertTrue(ipList.isIn("10.221.103.1"), "10.221.103.1 is not in the list");
+    assertTrue(ipList.isIn("10.221.103.255"), "10.221.103.255 is not in the list");
+    assertFalse(ipList.isIn("10.221.104.0"), "10.221.104.0 is in the list");
+    assertFalse(ipList.isIn("10.221.104.1"), "10.221.104.1 is in the list");
   }
 
   /**
@@ -79,8 +74,7 @@ public class TestFileBasedIPList {
 
     IPList ipList = new FileBasedIPList("ips.txt");
 
-    assertFalse ("Null Ip is in the list",
-        ipList.isIn(null));
+    assertFalse(ipList.isIn(null), "Null Ip is in the list");
   }
 
   /**
@@ -98,25 +92,17 @@ public class TestFileBasedIPList {
 
     IPList ipList = new FileBasedIPList("ips.txt");
 
-    assertTrue ("10.119.103.112 is not in the list",
-        ipList.isIn("10.119.103.112"));
-    assertFalse ("10.119.103.113 is in the list",
-        ipList.isIn("10.119.103.113"));
-
-    assertTrue ("10.221.103.121 is not in the list",
-        ipList.isIn("10.221.103.121"));
-    assertFalse("10.221.104.0 is in the list",
-        ipList.isIn("10.221.104.0"));
-
-    assertTrue ("10.222.103.121 is not in the list",
-        ipList.isIn("10.222.103.121"));
-    assertFalse("10.223.104.0 is in the list",
-        ipList.isIn("10.223.104.0"));
-
-    assertTrue ("10.113.221.221 is not in the list",
-        ipList.isIn("10.113.221.221"));
-    assertFalse("10.113.221.222 is in the list",
-        ipList.isIn("10.113.221.222"));
+    assertTrue(ipList.isIn("10.119.103.112"), "10.119.103.112 is not in the list");
+    assertFalse(ipList.isIn("10.119.103.113"), "10.119.103.113 is in the list");
+
+    assertTrue(ipList.isIn("10.221.103.121"), "10.221.103.121 is not in the list");
+    assertFalse(ipList.isIn("10.221.104.0"), "10.221.104.0 is in the list");
+
+    assertTrue(ipList.isIn("10.222.103.121"), "10.222.103.121 is not in the list");
+    assertFalse(ipList.isIn("10.223.104.0"), "10.223.104.0 is in the list");
+
+    assertTrue(ipList.isIn("10.113.221.221"), "10.113.221.221 is not in the list");
+    assertFalse(ipList.isIn("10.113.221.222"), "10.113.221.222 is in the list");
   }
 
   /**
@@ -129,8 +115,7 @@ public class TestFileBasedIPList {
 
     IPList ipl = new FileBasedIPList(null);
 
-    assertFalse("110.113.221.222 is in the list",
-        ipl.isIn("110.113.221.222"));
+    assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list");
   }
 
   /**
@@ -143,8 +128,7 @@ public class TestFileBasedIPList {
 
     IPList ipl = new FileBasedIPList("missingips.txt");
 
-    assertFalse("110.113.221.222 is in the list",
-        ipl.isIn("110.113.221.222"));
+    assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list");
   }
 
   /**
@@ -159,8 +143,7 @@ public class TestFileBasedIPList {
     createFileWithEntries ("ips.txt", ips);
     IPList ipl = new FileBasedIPList("ips.txt");
 
-    assertFalse("110.113.221.222 is in the list",
-        ipl.isIn("110.113.221.222"));
+    assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list");
   }
 
   /**

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java

@@ -19,17 +19,17 @@ package org.apache.hadoop.util;
 
 import java.io.ByteArrayOutputStream;
 import java.io.PrintStream;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
 import org.apache.hadoop.util.FindClass;
 import org.apache.hadoop.util.ToolRunner;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * Test the find class logic
  */
-public class TestFindClass extends Assert {
+public class TestFindClass extends Assertions {
   private static final Logger LOG =
       LoggerFactory.getLogger(TestFindClass.class);
 

+ 38 - 28
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java

@@ -23,8 +23,12 @@ import java.util.Iterator;
 import java.util.Random;
 
 import org.apache.hadoop.HadoopIllegalArgumentException;
-import org.junit.Assert;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestGSet {
   private static final Random ran = new Random();
@@ -53,7 +57,7 @@ public class TestGSet {
       try {
         //test contains with a null element
         gset.contains(null);
-        Assert.fail();
+        fail();
       } catch(NullPointerException e) {
         LightWeightGSet.LOG.info("GOOD: getting " + e, e);
       }
@@ -66,7 +70,7 @@ public class TestGSet {
       try {
         //test get with a null element
         gset.get(null);
-        Assert.fail();
+        fail();
       } catch(NullPointerException e) {
         LightWeightGSet.LOG.info("GOOD: getting " + e, e);
       }
@@ -79,14 +83,14 @@ public class TestGSet {
       try {
         //test put with a null element
         gset.put(null);
-        Assert.fail();
+        fail();
       } catch(NullPointerException e) {
         LightWeightGSet.LOG.info("GOOD: getting " + e, e);
       }
       try {
         //test putting an element which is not implementing LinkedElement
         gset.put(1);
-        Assert.fail();
+        fail();
       } catch(IllegalArgumentException e) {
         LightWeightGSet.LOG.info("GOOD: getting " + e, e);
       }
@@ -117,7 +121,7 @@ public class TestGSet {
                 gset.remove(data[1]);
               }
             }
-            Assert.fail();
+            fail();
           } catch(ConcurrentModificationException e) {
             LightWeightGSet.LOG.info("GOOD: getting " + e, e);
           }
@@ -132,7 +136,7 @@ public class TestGSet {
                 gset.put(data[0]);
               }
             }
-            Assert.fail();
+            fail();
           } catch(ConcurrentModificationException e) {
             LightWeightGSet.LOG.info("GOOD: getting " + e, e);
           }
@@ -147,7 +151,7 @@ public class TestGSet {
                 gset.put(data[3]);
               }
             }
-            Assert.fail();
+            fail();
           } catch(ConcurrentModificationException e) {
             LightWeightGSet.LOG.info("GOOD: getting " + e, e);
           }
@@ -261,7 +265,7 @@ public class TestGSet {
     for(int i = 0; i < test.data.size(); i++) {
       test.remove(test.data.get(i));
     }
-    Assert.assertEquals(0, test.gset.size());
+    assertEquals(0, test.gset.size());
     println("DONE " + test.stat());
 
     //check remove and add again
@@ -313,12 +317,12 @@ public class TestGSet {
       gset = resizable ? new LightWeightResizableGSet<IntElement, IntElement>() :
         new LightWeightGSet<IntElement, IntElement>(tablelength);
 
-      Assert.assertEquals(0, gset.size());
+      assertEquals(0, gset.size());
     }
 
     private boolean containsTest(IntElement key) {
       final boolean e = expected.contains(key);
-      Assert.assertEquals(e, gset.contains(key));
+      assertEquals(e, gset.contains(key));
       return e;
     }
     @Override
@@ -330,7 +334,7 @@ public class TestGSet {
 
     private IntElement getTest(IntElement key) {
       final IntElement e = expected.get(key);
-      Assert.assertEquals(e.id, gset.get(key).id);
+      assertEquals(e.id, gset.get(key).id);
       return e;
     }
     @Override
@@ -343,9 +347,9 @@ public class TestGSet {
     private IntElement putTest(IntElement element) {
       final IntElement e = expected.put(element);
       if (e == null) {
-        Assert.assertEquals(null, gset.put(element));
+        assertEquals(null, gset.put(element));
       } else {
-        Assert.assertEquals(e.id, gset.put(element).id);
+        assertEquals(e.id, gset.put(element).id);
       }
       return e;
     }
@@ -359,9 +363,9 @@ public class TestGSet {
     private IntElement removeTest(IntElement key) {
       final IntElement e = expected.remove(key);
       if (e == null) {
-        Assert.assertEquals(null, gset.remove(key));
+        assertEquals(null, gset.remove(key));
       } else {
-        Assert.assertEquals(e.id, gset.remove(key).id);
+        assertEquals(e.id, gset.remove(key).id);
       }
       return e;
     }
@@ -374,7 +378,7 @@ public class TestGSet {
 
     private int sizeTest() {
       final int s = expected.size();
-      Assert.assertEquals(s, gset.size());
+      assertEquals(s, gset.size());
       return s;
     }
     @Override
@@ -427,7 +431,7 @@ public class TestGSet {
     public void clear() {
       expected.clear();
       gset.clear();
-      Assert.assertEquals(0, size());
+      assertEquals(0, size());
     }
 
     @Override
@@ -504,27 +508,33 @@ public class TestGSet {
    * Test for {@link LightWeightGSet#computeCapacity(double, String)}
    * with invalid percent less than 0.
    */
-  @Test(expected=HadoopIllegalArgumentException.class)
+  @Test
   public void testComputeCapacityNegativePercent() {
-    LightWeightGSet.computeCapacity(1024, -1.0, "testMap");
+    assertThrows(HadoopIllegalArgumentException.class, () -> {
+      LightWeightGSet.computeCapacity(1024, -1.0, "testMap");
+    });
   }
   
   /** 
    * Test for {@link LightWeightGSet#computeCapacity(double, String)}
    * with invalid percent greater than 100.
    */
-  @Test(expected=HadoopIllegalArgumentException.class)
+  @Test
   public void testComputeCapacityInvalidPercent() {
-    LightWeightGSet.computeCapacity(1024, 101.0, "testMap");
+    assertThrows(HadoopIllegalArgumentException.class, () -> {
+      LightWeightGSet.computeCapacity(1024, 101.0, "testMap");
+    });
   }
   
   /** 
    * Test for {@link LightWeightGSet#computeCapacity(double, String)}
    * with invalid negative max memory
    */
-  @Test(expected=HadoopIllegalArgumentException.class)
+  @Test
   public void testComputeCapacityInvalidMemory() {
-    LightWeightGSet.computeCapacity(-1, 50.0, "testMap");
+    assertThrows(HadoopIllegalArgumentException.class, () -> {
+      LightWeightGSet.computeCapacity(-1, 50.0, "testMap");
+    });
   }
   
   private static boolean isPowerOfTwo(int num) {
@@ -545,16 +555,16 @@ public class TestGSet {
     LightWeightGSet.LOG.info("Validating - total memory " + maxMemory + " percent "
         + percent + " returned capacity " + capacity);
     // Returned capacity is zero or power of two
-    Assert.assertTrue(isPowerOfTwo(capacity));
+    assertTrue(isPowerOfTwo(capacity));
 
     // Ensure the capacity returned is the nearest to the asked perecentage
     int capacityPercent = getPercent(maxMemory, capacity);
     if (capacityPercent == percent) {
       return;
     } else if (capacityPercent > percent) {
-      Assert.assertTrue(getPercent(maxMemory, capacity * 2) > percent);
+      assertTrue(getPercent(maxMemory, capacity * 2) > percent);
     } else {
-      Assert.assertTrue(getPercent(maxMemory, capacity / 2) < percent);
+      assertTrue(getPercent(maxMemory, capacity / 2) < percent);
     }
   }
   

+ 39 - 40
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java

@@ -17,12 +17,12 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -45,9 +45,9 @@ import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.thirdparty.com.google.common.collect.Maps;
 
@@ -69,9 +69,9 @@ public class TestGenericOptionsParser {
     args[1] = tmpFile.toURI().toString();
     new GenericOptionsParser(conf, args);
     String files = conf.get("tmpfiles");
-    assertNotNull("files is null", files);
-    assertEquals("files option does not match",
-      localFs.makeQualified(tmpPath).toString(), files);
+    assertNotNull(files, "files is null");
+    assertEquals(localFs.makeQualified(tmpPath).toString(), files,
+        "files option does not match");
     
     // pass file as uri
     Configuration conf1 = new Configuration();
@@ -80,9 +80,9 @@ public class TestGenericOptionsParser {
     args[1] = tmpURI.toString();
     new GenericOptionsParser(conf1, args);
     files = conf1.get("tmpfiles");
-    assertNotNull("files is null", files);
-    assertEquals("files option does not match", 
-      localFs.makeQualified(new Path(tmpURI)).toString(), files);
+    assertNotNull(files, "files is null");
+    assertEquals(localFs.makeQualified(new Path(tmpURI)).toString(), files,
+        "files option does not match");
    
     // pass a file that does not exist.
     // GenericOptionParser should throw exception
@@ -95,11 +95,11 @@ public class TestGenericOptionsParser {
     } catch (Exception e) {
       th = e;
     }
-    assertNotNull("throwable is null", th);
-    assertTrue("FileNotFoundException is not thrown",
-      th instanceof FileNotFoundException);
+    assertNotNull(th, "throwable is null");
+    assertTrue(th instanceof FileNotFoundException,
+        "FileNotFoundException is not thrown");
     files = conf2.get("tmpfiles");
-    assertNull("files is not null", files);
+    assertNull(files, "files is not null");
   }
 
   @Test
@@ -116,17 +116,17 @@ public class TestGenericOptionsParser {
     args[1] = tmpJar.toURI().toString();
     new GenericOptionsParser(conf, args);
     String libjars = conf.get("tmpjars");
-    assertNotNull("libjars is null", libjars);
-    assertEquals("libjars does not match",
-        localFs.makeQualified(tmpJarPath).toString(), libjars);
+    assertNotNull(libjars, "libjars is null");
+    assertEquals(localFs.makeQualified(tmpJarPath).toString(), libjars,
+        "libjars does not match");
 
     // now test the wildcard
     args[1] = testDir.toURI().toString() + "*";
     new GenericOptionsParser(conf, args);
     libjars = conf.get("tmpjars");
-    assertNotNull("libjars is null", libjars);
-    assertEquals("libjars does not match",
-        localFs.makeQualified(tmpJarPath).toString(), libjars);
+    assertNotNull(libjars, "libjars is null");
+    assertEquals(localFs.makeQualified(tmpJarPath).toString(), libjars,
+        "libjars does not match");
   }
 
   /**
@@ -210,8 +210,8 @@ public class TestGenericOptionsParser {
     args[0] = "--newOpt";
     args[1] = "7";
     GenericOptionsParser g = new GenericOptionsParser(opts, args);
-    assertEquals("New option was ignored",
-      "7", g.getCommandLine().getOptionValues("newOpt")[0]);
+    assertEquals("7", g.getCommandLine().getOptionValues("newOpt")[0],
+        "New option was ignored");
   }
 
   /**
@@ -223,13 +223,13 @@ public class TestGenericOptionsParser {
     args[0] = "--conf=foo";
     args[1] = "--conf=bar";
     GenericOptionsParser g = new GenericOptionsParser(args);
-    assertEquals("1st conf param is incorrect",
-      "foo", g.getCommandLine().getOptionValues("conf")[0]);
-    assertEquals("2st conf param is incorrect",
-      "bar", g.getCommandLine().getOptionValues("conf")[1]);
+    assertEquals("foo", g.getCommandLine().getOptionValues("conf")[0],
+        "1st conf param is incorrect");
+    assertEquals("bar", g.getCommandLine().getOptionValues("conf")[1],
+        "2st conf param is incorrect");
   }
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
     conf = new Configuration();
     localFs = FileSystem.getLocal(conf);
@@ -238,7 +238,7 @@ public class TestGenericOptionsParser {
       localFs.delete(new Path(testDir.toString()), true);
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if(testDir.exists()) {
       localFs.delete(new Path(testDir.toString()), true);
@@ -270,8 +270,8 @@ public class TestGenericOptionsParser {
       th = e;
     }
     assertNotNull(th);
-    assertTrue("FileNotFoundException is not thrown",
-        th instanceof FileNotFoundException);
+    assertTrue(th instanceof FileNotFoundException,
+        "FileNotFoundException is not thrown");
     
     // create file
     Path tmpPath = localFs.makeQualified(new Path(tmpFile.toString()));
@@ -284,8 +284,8 @@ public class TestGenericOptionsParser {
 
     new GenericOptionsParser(conf, args);
     String fileName = conf.get("mapreduce.job.credentials.binary");
-    assertNotNull("files is null", fileName);
-    assertEquals("files option does not match", tmpPath.toString(), fileName);
+    assertNotNull(fileName, "files is null");
+    assertEquals(tmpPath.toString(), fileName, "files option does not match");
     
     Credentials ugiCreds =
         UserGroupInformation.getCurrentUser().getCredentials();
@@ -379,9 +379,8 @@ public class TestGenericOptionsParser {
       assertEquals(entry.getValue(), conf.get(entry.getKey()));
     }
 
-    assertArrayEquals(
-      Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs),
-      expectedRemainingArgs, remainingArgs);
+    assertArrayEquals(expectedRemainingArgs, remainingArgs,
+        Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs));
   }
 
   /** Test passing null as args. Some classes still call

+ 19 - 17
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java

@@ -21,8 +21,11 @@ package org.apache.hadoop.util;
 import java.util.ArrayList;
 import java.util.List;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.conf.Configuration;
 
@@ -41,9 +44,8 @@ public class TestGenericsUtil {
     Integer[] arr = GenericsUtil.toArray(list);
 
     for (int i = 0; i < arr.length; i++) {
-      assertEquals(
-              "Array has identical elements as input list",
-              list.get(i), arr[i]);
+      assertEquals(list.get(i), arr[i],
+          "Array has identical elements as input list");
     }
   }
 
@@ -66,8 +68,8 @@ public class TestGenericsUtil {
     //this method should not throw IndexOutOfBoundsException
     String[] arr = GenericsUtil.<String>toArray(String.class, list);
 
-    assertEquals("Assert list creation w/ no elements results in length 0",
-            0, arr.length);
+    assertEquals(0, arr.length,
+        "Assert list creation w/ no elements results in length 0");
   }
 
   /** This class uses generics */
@@ -117,9 +119,8 @@ public class TestGenericsUtil {
     parser =
       new GenericOptionsParser(new Configuration(),
                                new String[] {"-Dx=y=z"});
-    assertEquals(
-            "Options parser gets entire ='s expresion",
-            "y=z", parser.getConfiguration().get("x"));
+    assertEquals("y=z", parser.getConfiguration().get("x"),
+        "Options parser gets entire ='s expresion");
   }
 
   @Test
@@ -128,20 +129,21 @@ public class TestGenericsUtil {
     //test with Integer
     Integer x = new Integer(42);
     Class<Integer> c = GenericsUtil.getClass(x);
-    assertEquals("Correct generic type is acquired from object",
-            Integer.class, c);
+    assertEquals(Integer.class, c,
+        "Correct generic type is acquired from object");
 
     //test with GenericClass<Integer>
     GenericClass<Integer> testSubject = new GenericClass<Integer>();
     Class<GenericClass<Integer>> c2 = GenericsUtil.getClass(testSubject);
-    assertEquals("Inner generics are acquired from object.",
-            GenericClass.class, c2);
+    assertEquals(GenericClass.class, c2,
+        "Inner generics are acquired from object.");
   }
 
   @Test
   public void testIsLog4jLogger() throws Exception {
-    assertFalse("False if clazz is null", GenericsUtil.isLog4jLogger((Class<?>) null));
-    assertTrue("The implementation is Log4j",
-        GenericsUtil.isLog4jLogger(TestGenericsUtil.class));
+    assertFalse(GenericsUtil.isLog4jLogger((Class<?>) null),
+        "False if clazz is null");
+    assertTrue(GenericsUtil.isLog4jLogger(TestGenericsUtil.class),
+        "The implementation is Log4j");
   }
 }

+ 37 - 28
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java

@@ -25,9 +25,17 @@ import java.util.Map;
 
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.HostsFileReader.HostDetails;
-import org.junit.*;
 
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+
+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;
 
 /*
  * Test for HostsFileReader.java
@@ -43,11 +51,11 @@ public class TestHostsFileReader {
   String includesFile = HOSTS_TEST_DIR + "/dfs.include";
   private String excludesXmlFile = HOSTS_TEST_DIR + "/dfs.exclude.xml";
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     // Delete test files after running tests
     EXCLUDES_FILE.delete();
@@ -136,7 +144,7 @@ public class TestHostsFileReader {
       new HostsFileReader(
           HOSTS_TEST_DIR + "/doesnt-exist",
           HOSTS_TEST_DIR + "/doesnt-exist");
-      Assert.fail("Should throw NoSuchFileException");
+      fail("Should throw NoSuchFileException");
     } catch (NoSuchFileException ex) {
       // Exception as expected
     }
@@ -158,7 +166,7 @@ public class TestHostsFileReader {
     assertTrue(INCLUDES_FILE.delete());
     try {
       hfp.refresh();
-      Assert.fail("Should throw NoSuchFileException");
+      fail("Should throw NoSuchFileException");
     } catch (NoSuchFileException ex) {
       // Exception as expected
     }
@@ -376,34 +384,35 @@ public class TestHostsFileReader {
     HostDetails details = hfp.getHostDetails();
     HostDetails lazyDetails = hfp.getLazyLoadedHostDetails();
 
-    assertEquals("Details: no. of excluded hosts", 2,
-        details.getExcludedHosts().size());
-    assertEquals("Details: no. of included hosts", 2,
-        details.getIncludedHosts().size());
-    assertEquals("LazyDetails: no. of excluded hosts", 4,
-        lazyDetails.getExcludedHosts().size());
-    assertEquals("LayDetails: no. of included hosts", 0,
-        lazyDetails.getIncludedHosts().size());
+    assertEquals(2, details.getExcludedHosts().size(),
+        "Details: no. of excluded hosts");
+    assertEquals(2, details.getIncludedHosts().size(),
+        "Details: no. of included hosts");
+    assertEquals(4, lazyDetails.getExcludedHosts().size(),
+        "LazyDetails: no. of excluded hosts");
+    assertEquals(0, lazyDetails.getIncludedHosts().size(),
+        "LayDetails: no. of included hosts");
 
     hfp.finishRefresh();
 
     details = hfp.getHostDetails();
-    assertEquals("Details: no. of excluded hosts", 4,
-        details.getExcludedHosts().size());
-    assertEquals("Details: no. of included hosts", 0,
-        details.getIncludedHosts().size());
-    assertNull("Lazy host details should be null",
-        hfp.getLazyLoadedHostDetails());
+    assertEquals(4, details.getExcludedHosts().size(),
+        "Details: no. of excluded hosts");
+    assertEquals(0, details.getIncludedHosts().size(),
+        "Details: no. of included hosts");
+    assertNull(hfp.getLazyLoadedHostDetails(), "Lazy host details should be null");
   }
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void testFinishRefreshWithoutLazyRefresh() throws IOException {
-    FileWriter efw = new FileWriter(excludesFile);
-    FileWriter ifw = new FileWriter(includesFile);
-    efw.close();
-    ifw.close();
-
-    HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
-    hfp.finishRefresh();
+    assertThrows(IllegalStateException.class, () -> {
+      FileWriter efw = new FileWriter(excludesFile);
+      FileWriter ifw = new FileWriter(includesFile);
+      efw.close();
+      ifw.close();
+
+      HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
+      hfp.finishRefresh();
+    });
   }
 }

+ 43 - 38
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java

@@ -19,9 +19,7 @@ package org.apache.hadoop.util;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.Assert;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
 
 import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.core.MediaType;
@@ -37,27 +35,34 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;
 
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 public class TestHttpExceptionUtils {
 
   @Test
   public void testCreateServletException() throws IOException {
     StringWriter writer = new StringWriter();
     PrintWriter printWriter = new PrintWriter(writer);
-    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
-    Mockito.when(response.getWriter()).thenReturn(printWriter);
+    HttpServletResponse response = mock(HttpServletResponse.class);
+    when(response.getWriter()).thenReturn(printWriter);
     int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
     Exception ex = new IOException("Hello IOEX");
     HttpExceptionUtils.createServletExceptionResponse(response, status, ex);
-    Mockito.verify(response).setStatus(status);
-    Mockito.verify(response).setContentType(Mockito.eq("application/json"));
+    verify(response).setStatus(status);
+    verify(response).setContentType(eq("application/json"));
     ObjectMapper mapper = new ObjectMapper();
     Map json = mapper.readValue(writer.toString(), Map.class);
     json = (Map) json.get(HttpExceptionUtils.ERROR_JSON);
-    Assert.assertEquals(IOException.class.getName(),
+    assertEquals(IOException.class.getName(),
         json.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON));
-    Assert.assertEquals(IOException.class.getSimpleName(),
+    assertEquals(IOException.class.getSimpleName(),
         json.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON));
-    Assert.assertEquals("Hello IOEX",
+    assertEquals("Hello IOEX",
         json.get(HttpExceptionUtils.ERROR_MESSAGE_JSON));
   }
 
@@ -66,32 +71,32 @@ public class TestHttpExceptionUtils {
     Exception ex = new IOException("Hello IOEX");
     Response response = HttpExceptionUtils.createJerseyExceptionResponse(
         Response.Status.INTERNAL_SERVER_ERROR, ex);
-    Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
+    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
         response.getStatus());
-    Assert.assertArrayEquals(
+    assertArrayEquals(
         Arrays.asList(MediaType.APPLICATION_JSON_TYPE).toArray(),
         response.getMetadata().get("Content-Type").toArray());
     Map entity = (Map) response.getEntity();
     entity = (Map) entity.get(HttpExceptionUtils.ERROR_JSON);
-    Assert.assertEquals(IOException.class.getName(),
+    assertEquals(IOException.class.getName(),
         entity.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON));
-    Assert.assertEquals(IOException.class.getSimpleName(),
+    assertEquals(IOException.class.getSimpleName(),
         entity.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON));
-    Assert.assertEquals("Hello IOEX",
+    assertEquals("Hello IOEX",
         entity.get(HttpExceptionUtils.ERROR_MESSAGE_JSON));
   }
 
   @Test
   public void testValidateResponseOK() throws IOException {
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_CREATED);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_CREATED);
     HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
   }
 
   @Test
   public void testValidateResponseFailNoErrorMessage() throws Exception {
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
     LambdaTestUtils.intercept(IOException.class,
         () -> HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED));
   }
@@ -100,13 +105,13 @@ public class TestHttpExceptionUtils {
   public void testValidateResponseNonJsonErrorMessage() throws Exception {
     String msg = "stream";
     InputStream is = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getErrorStream()).thenReturn(is);
-    Mockito.when(conn.getResponseMessage()).thenReturn("msg");
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getErrorStream()).thenReturn(is);
+    when(conn.getResponseMessage()).thenReturn("msg");
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
     LambdaTestUtils.interceptAndValidateMessageContains(IOException.class,
         Arrays.asList(Integer.toString(HttpURLConnection.HTTP_BAD_REQUEST), "msg",
-          "com.fasterxml.jackson.core.JsonParseException"),
+        "com.fasterxml.jackson.core.JsonParseException"),
         () -> HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED));
   }
 
@@ -121,10 +126,10 @@ public class TestHttpExceptionUtils {
     ObjectMapper jsonMapper = new ObjectMapper();
     String msg = jsonMapper.writeValueAsString(response);
     InputStream is = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getErrorStream()).thenReturn(is);
-    Mockito.when(conn.getResponseMessage()).thenReturn("msg");
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getErrorStream()).thenReturn(is);
+    when(conn.getResponseMessage()).thenReturn("msg");
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
     LambdaTestUtils.intercept(IllegalStateException.class,
         "EX",
         () -> HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED));
@@ -142,13 +147,13 @@ public class TestHttpExceptionUtils {
     ObjectMapper jsonMapper = new ObjectMapper();
     String msg = jsonMapper.writeValueAsString(response);
     InputStream is = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getErrorStream()).thenReturn(is);
-    Mockito.when(conn.getResponseMessage()).thenReturn("msg");
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getErrorStream()).thenReturn(is);
+    when(conn.getResponseMessage()).thenReturn("msg");
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
     LambdaTestUtils.interceptAndValidateMessageContains(IOException.class,
         Arrays.asList(Integer.toString(HttpURLConnection.HTTP_BAD_REQUEST),
-          "foo.FooException", "EX"),
+        "foo.FooException", "EX"),
         () -> HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED));
   }
 
@@ -164,13 +169,13 @@ public class TestHttpExceptionUtils {
     ObjectMapper jsonMapper = new ObjectMapper();
     String msg = jsonMapper.writeValueAsString(response);
     InputStream is = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
-    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
-    Mockito.when(conn.getErrorStream()).thenReturn(is);
-    Mockito.when(conn.getResponseMessage()).thenReturn("msg");
-    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
+    HttpURLConnection conn = mock(HttpURLConnection.class);
+    when(conn.getErrorStream()).thenReturn(is);
+    when(conn.getResponseMessage()).thenReturn("msg");
+    when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST);
     LambdaTestUtils.interceptAndValidateMessageContains(IOException.class,
         Arrays.asList(Integer.toString(HttpURLConnection.HTTP_BAD_REQUEST),
-          "java.lang.String", "EX"),
+        "java.lang.String", "EX"),
         () -> HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED));
   }
 }

+ 35 - 29
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java

@@ -21,14 +21,18 @@ import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
 
-import org.junit.Assert;
-
 import org.apache.hadoop.util.IdentityHashStore;
 import org.apache.hadoop.util.IdentityHashStore.Visitor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+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;
+
 public class TestIdentityHashStore {
   private static final Logger LOG =
       LoggerFactory.getLogger(TestIdentityHashStore.class.getName());
@@ -55,43 +59,45 @@ public class TestIdentityHashStore {
     }
   }
 
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testStartingWithZeroCapacity() {
     IdentityHashStore<Key, Integer> store = 
         new IdentityHashStore<Key, Integer>(0);
     store.visitAll(new Visitor<Key, Integer>() {
       @Override
       public void accept(Key k, Integer v) {
-        Assert.fail("found key " + k + " in empty IdentityHashStore.");
+        fail("found key " + k + " in empty IdentityHashStore.");
       }
     });
-    Assert.assertTrue(store.isEmpty());
+    assertTrue(store.isEmpty());
     final Key key1 = new Key("key1");
     Integer value1 = new Integer(100);
     store.put(key1, value1);
-    Assert.assertTrue(!store.isEmpty());
-    Assert.assertEquals(value1, store.get(key1));
+    assertTrue(!store.isEmpty());
+    assertEquals(value1, store.get(key1));
     store.visitAll(new Visitor<Key, Integer>() {
       @Override
       public void accept(Key k, Integer v) {
-        Assert.assertEquals(key1, k);
+        assertEquals(key1, k);
       }
     });
-    Assert.assertEquals(value1, store.remove(key1));
-    Assert.assertTrue(store.isEmpty());
+    assertEquals(value1, store.remove(key1));
+    assertTrue(store.isEmpty());
   }
   
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testDuplicateInserts() {
     IdentityHashStore<Key, Integer> store = 
         new IdentityHashStore<Key, Integer>(4);
     store.visitAll(new Visitor<Key, Integer>() {
       @Override
       public void accept(Key k, Integer v) {
-        Assert.fail("found key " + k + " in empty IdentityHashStore.");
+        fail("found key " + k + " in empty IdentityHashStore.");
       }
     });
-    Assert.assertTrue(store.isEmpty());
+    assertTrue(store.isEmpty());
     Key key1 = new Key("key1");
     Integer value1 = new Integer(100);
     Integer value2 = new Integer(200);
@@ -100,10 +106,10 @@ public class TestIdentityHashStore {
     Key equalToKey1 = new Key("key1");
 
     // IdentityHashStore compares by object equality, not equals()
-    Assert.assertNull(store.get(equalToKey1)); 
+    assertNull(store.get(equalToKey1));
 
-    Assert.assertTrue(!store.isEmpty());
-    Assert.assertEquals(value1, store.get(key1));
+    assertTrue(!store.isEmpty());
+    assertEquals(value1, store.get(key1));
     store.put(key1, value2);
     store.put(key1, value3);
     final List<Integer> allValues = new LinkedList<Integer>();
@@ -113,16 +119,17 @@ public class TestIdentityHashStore {
         allValues.add(v);
       }
     });
-    Assert.assertEquals(3, allValues.size());
+    assertEquals(3, allValues.size());
     for (int i = 0; i < 3; i++) {
       Integer value = store.remove(key1);
-      Assert.assertTrue(allValues.remove(value));
+      assertTrue(allValues.remove(value));
     }
-    Assert.assertNull(store.remove(key1));
-    Assert.assertTrue(store.isEmpty());
+    assertNull(store.remove(key1));
+    assertTrue(store.isEmpty());
   }
   
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testAdditionsAndRemovals() {
     IdentityHashStore<Key, Integer> store = 
         new IdentityHashStore<Key, Integer>(0);
@@ -138,23 +145,22 @@ public class TestIdentityHashStore {
     store.visitAll(new Visitor<Key, Integer>() {
       @Override
       public void accept(Key k, Integer v) {
-        Assert.assertTrue(keys.contains(k));
+        assertTrue(keys.contains(k));
       }
     });
     for (int i = 0; i < NUM_KEYS; i++) {
-      Assert.assertEquals(Integer.valueOf(i),
+      assertEquals(Integer.valueOf(i),
           store.remove(keys.get(i)));
     }
     store.visitAll(new Visitor<Key, Integer>() {
       @Override
       public void accept(Key k, Integer v) {
-        Assert.fail("expected all entries to be removed");
+        fail("expected all entries to be removed");
       }
     });
-    Assert.assertTrue("expected the store to be " +
-        "empty, but found " + store.numElements() + " elements.",
-        store.isEmpty());
-    Assert.assertEquals(1024, store.capacity());
+    assertTrue(store.isEmpty(), "expected the store to be " +
+        "empty, but found " + store.numElements() + " elements.");
+    assertEquals(1024, store.capacity());
   }
   
 }

+ 24 - 20
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java

@@ -21,8 +21,8 @@ import java.io.IOException;
 import java.util.Arrays;
 import java.util.Random;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.hadoop.io.DataInputBuffer;
 import org.apache.hadoop.io.DataOutputBuffer;
@@ -38,8 +38,9 @@ public class TestIndexedSort {
     SampleSortable s = new SampleSortable(values);
     sorter.sort(s, 0, SAMPLE);
     int[] check = s.getSorted();
-    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
-        Arrays.toString(check), Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        Arrays.toString(values) + "\ndoesn't match\n" +
+        Arrays.toString(check));
     // Set random min/max, re-sort.
     Random r = new Random();
     int min = r.nextInt(SAMPLE);
@@ -54,8 +55,9 @@ public class TestIndexedSort {
     Arrays.sort(values);
     assertTrue(check[0] == 9);
     assertTrue(check[SAMPLE - 1] == 11);
-    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
-        Arrays.toString(check), Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        Arrays.toString(values) + "\ndoesn't match\n" +
+        Arrays.toString(check));
   }
 
   public void sortSorted(IndexedSorter sorter) throws Exception {
@@ -73,8 +75,9 @@ public class TestIndexedSort {
     SampleSortable s = new SampleSortable(values);
     sorter.sort(s, 0, SAMPLE);
     int[] check = s.getSorted();
-    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
-        Arrays.toString(check), Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        Arrays.toString(values) + "\ndoesn't match\n" +
+        Arrays.toString(check));
   }
 
   public void sortSequential(IndexedSorter sorter) throws Exception {
@@ -86,8 +89,9 @@ public class TestIndexedSort {
     SampleSortable s = new SampleSortable(values);
     sorter.sort(s, 0, SAMPLE);
     int[] check = s.getSorted();
-    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
-        Arrays.toString(check), Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        Arrays.toString(values) + "\ndoesn't match\n" +
+        Arrays.toString(check));
   }
 
   public void sortSingleRecord(IndexedSorter sorter) throws Exception {
@@ -96,8 +100,9 @@ public class TestIndexedSort {
     int[] values = s.getValues();
     sorter.sort(s, 0, SAMPLE);
     int[] check = s.getSorted();
-    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
-        Arrays.toString(check), Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        Arrays.toString(values) + "\ndoesn't match\n" +
+        Arrays.toString(check));
   }
 
   public void sortRandom(IndexedSorter sorter) throws Exception {
@@ -110,8 +115,8 @@ public class TestIndexedSort {
     Arrays.sort(values);
     sorter.sort(s, 0, SAMPLE);
     int[] check = s.getSorted();
-    assertTrue("seed: " + seed + "\ndoesn't match\n",
-               Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        "seed: " + seed + "\ndoesn't match\n");
   }
 
   public void sortWritable(IndexedSorter sorter) throws Exception {
@@ -124,8 +129,8 @@ public class TestIndexedSort {
     Arrays.sort(values);
     sorter.sort(s, 0, SAMPLE);
     String[] check = s.getSorted();
-    assertTrue("seed: " + seed + "\ndoesn't match",
-               Arrays.equals(values, check));
+    assertTrue(Arrays.equals(values, check),
+        "seed: " + seed + "\ndoesn't match");
   }
 
 
@@ -267,15 +272,14 @@ public class TestIndexedSort {
 
     @Override
     public int compare(int i, int j) {
-      assertTrue("Expected fewer than " + maxcmp + " comparisons",
-                 ++comparisions < maxcmp);
+      assertTrue(++comparisions < maxcmp,
+          "Expected fewer than " + maxcmp + " comparisons");
       return s.compare(i, j);
     }
 
     @Override
     public void swap(int i, int j) {
-      assertTrue("Expected fewer than " + maxswp + " swaps",
-                 ++swaps < maxswp);
+      assertTrue(++swaps < maxswp, "Expected fewer than " + maxswp + " swaps");
       s.swap(i, j);
     }
 

+ 24 - 19
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java

@@ -23,13 +23,16 @@ import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
+import org.junit.jupiter.api.TestInfo;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import static org.mockito.Mockito.*;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+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.assertNull;
+import static org.mockito.Mockito.mock;
 
 /**
  * A test class for InstrumentedLock.
@@ -38,15 +41,14 @@ public class TestInstrumentedLock {
 
   static final Logger LOG = LoggerFactory.getLogger(TestInstrumentedLock.class);
 
-  @Rule public TestName name = new TestName();
-
   /**
    * Test exclusive access of the lock.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testMultipleThread() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testMultipleThread(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     InstrumentedLock lock = new InstrumentedLock(testname, LOG, 0, 300);
     lock.lock();
     try {
@@ -67,9 +69,10 @@ public class TestInstrumentedLock {
    * Test the correctness with try-with-resource syntax.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testTryWithResourceSyntax() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testTryWithResourceSyntax(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final AtomicReference<Thread> lockThread = new AtomicReference<>(null);
     Lock lock = new InstrumentedLock(testname, LOG, 0, 300) {
       @Override
@@ -105,9 +108,10 @@ public class TestInstrumentedLock {
    * and not log warning otherwise.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testLockLongHoldingReport() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testLockLongHoldingReport(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override
@@ -172,9 +176,10 @@ public class TestInstrumentedLock {
    * threshold and not log warning otherwise.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testLockLongWaitReport() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testLockLongWaitReport(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override

+ 30 - 27
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java

@@ -17,16 +17,16 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,16 +38,14 @@ public class TestInstrumentedReadWriteLock {
   static final Logger LOG = LoggerFactory.getLogger(
           TestInstrumentedReadWriteLock.class);
 
-  @Rule
-  public TestName name = new TestName();
-
   /**
    * Tests exclusive access of the write lock.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testWriteLock() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testWriteLock(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final ThreadLocal<Boolean> locked = new ThreadLocal<Boolean>();
     locked.set(Boolean.FALSE);
     InstrumentedReadWriteLock readWriteLock = new InstrumentedReadWriteLock(
@@ -95,9 +93,10 @@ public class TestInstrumentedReadWriteLock {
    * Tests the read lock.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testReadLock() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testReadLock(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     InstrumentedReadWriteLock readWriteLock = new InstrumentedReadWriteLock(
         true, testname, LOG, 2000, 300);
     final AutoCloseableLock readLock = new AutoCloseableLock(
@@ -129,9 +128,10 @@ public class TestInstrumentedReadWriteLock {
    * Tests the warning when the read lock is held longer than threshold.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testReadLockLongHoldingReport() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testReadLockLongHoldingReport(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override
@@ -184,9 +184,10 @@ public class TestInstrumentedReadWriteLock {
    * Tests the warning when the write lock is held longer than threshold.
    * @throws Exception
    */
-  @Test(timeout=10000)
-  public void testWriteLockLongHoldingReport() throws Exception {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testWriteLockLongHoldingReport(TestInfo testInfo) throws Exception {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override
@@ -238,9 +239,10 @@ public class TestInstrumentedReadWriteLock {
   /**
    * Tests the warning when the write lock is held longer than threshold.
    */
-  @Test(timeout=10000)
-  public void testWriteLockLongHoldingReportWithReentrant() {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testWriteLockLongHoldingReportWithReentrant(TestInfo testInfo) {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override
@@ -298,9 +300,10 @@ public class TestInstrumentedReadWriteLock {
   /**
    * Tests the warning when the read lock is held longer than threshold.
    */
-  @Test(timeout=10000)
-  public void testReadLockLongHoldingReportWithReentrant() {
-    String testname = name.getMethodName();
+  @Test
+  @Timeout(value = 10)
+  public void testReadLockLongHoldingReportWithReentrant(TestInfo testInfo) {
+    String testname = testInfo.getDisplayName();
     final AtomicLong time = new AtomicLong(0);
     Timer mclock = new Timer() {
       @Override

+ 8 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java

@@ -19,8 +19,7 @@
 package org.apache.hadoop.util;
 
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.LoggerFactory;
 
 import java.io.ByteArrayInputStream;
@@ -37,6 +36,9 @@ import java.util.jar.JarInputStream;
 import java.util.jar.JarOutputStream;
 import java.util.jar.Manifest;
 
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 public class TestJarFinder {
 
   @Test
@@ -44,7 +46,7 @@ public class TestJarFinder {
 
     //picking a class that is for sure in a JAR in the classpath
     String jar = JarFinder.getJar(LoggerFactory.class);
-    Assert.assertTrue(new File(jar).exists());
+    assertTrue(new File(jar).exists());
   }
 
   private static void delete(File file) throws IOException {
@@ -75,7 +77,7 @@ public class TestJarFinder {
     //picking a class that is for sure in a directory in the classpath
     //in this case the JAR is created on the fly
     String jar = JarFinder.getJar(TestJarFinder.class);
-    Assert.assertTrue(new File(jar).exists());
+    assertTrue(new File(jar).exists());
   }
 
   @Test
@@ -102,7 +104,7 @@ public class TestJarFinder {
     JarFinder.jarDir(dir, "", zos);
     JarInputStream jis =
       new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
-    Assert.assertNotNull(jis.getManifest());
+    assertNotNull(jis.getManifest());
     jis.close();
   }
 
@@ -121,7 +123,7 @@ public class TestJarFinder {
     JarFinder.jarDir(dir, "", zos);
     JarInputStream jis =
       new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
-    Assert.assertNotNull(jis.getManifest());
+    assertNotNull(jis.getManifest());
     jis.close();
   }
 }

+ 17 - 15
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java

@@ -22,8 +22,10 @@ import java.util.Date;
 import java.util.Iterator;
 import java.util.Random;
 
-import org.junit.Assert;
-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.assertTrue;
 
 /** Testing {@link LightWeightCache} */
 public class TestLightWeightCache {
@@ -81,7 +83,7 @@ public class TestLightWeightCache {
     print("  check size ................. ");
     for(int i = 0; i < test.data.size(); i++) {
       test.cache.put(test.data.get(i));
-      Assert.assertTrue(test.cache.size() <= sizeLimit);
+      assertTrue(test.cache.size() <= sizeLimit);
     }
     println("DONE " + test.stat());
   }
@@ -169,7 +171,7 @@ public class TestLightWeightCache {
     for(int i = 0; i < test.data.size(); i++) {
       test.remove(test.data.get(i));
     }
-    Assert.assertEquals(0, test.cache.size());
+    assertEquals(0, test.cache.size());
     println("DONE " + test.stat());
 
     //check remove and put again
@@ -232,17 +234,17 @@ public class TestLightWeightCache {
       cache = new LightWeightCache<IntEntry, IntEntry>(tablelength, sizeLimit,
           creationExpirationPeriod, 0, fakeTimer);
 
-      Assert.assertEquals(0, cache.size());
+      assertEquals(0, cache.size());
     }
 
     private boolean containsTest(IntEntry key) {
       final boolean c = cache.contains(key);
       if (c) {
-        Assert.assertTrue(hashMap.contains(key));
+        assertTrue(hashMap.contains(key));
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
+          assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -257,11 +259,11 @@ public class TestLightWeightCache {
     private IntEntry getTest(IntEntry key) {
       final IntEntry c = cache.get(key);
       if (c != null) {
-        Assert.assertEquals(hashMap.get(key).id, c.id);
+        assertEquals(hashMap.get(key).id, c.id);
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
+          assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -276,12 +278,12 @@ public class TestLightWeightCache {
     private IntEntry putTest(IntEntry entry) {
       final IntEntry c = cache.put(entry);
       if (c != null) {
-        Assert.assertEquals(hashMap.put(entry).id, c.id);
+        assertEquals(hashMap.put(entry).id, c.id);
       } else {
         final IntEntry h = hashMap.put(entry);
         if (h != null && h != entry) {
           // if h == entry, its expiration time is already updated
-          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
+          assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -296,11 +298,11 @@ public class TestLightWeightCache {
     private IntEntry removeTest(IntEntry key) {
       final IntEntry c = cache.remove(key);
       if (c != null) {
-        Assert.assertEquals(c.id, hashMap.remove(key).id);
+        assertEquals(c.id, hashMap.remove(key).id);
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
+          assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -314,7 +316,7 @@ public class TestLightWeightCache {
 
     private int sizeTest() {
       final int c = cache.size();
-      Assert.assertTrue(hashMap.size() >= c);
+      assertTrue(hashMap.size() >= c);
       return c;
     }
     @Override
@@ -373,7 +375,7 @@ public class TestLightWeightCache {
     public void clear() {
       hashMap.clear();
       cache.clear();
-      Assert.assertEquals(0, size());
+      assertEquals(0, size());
     }
 
     @Override

+ 11 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java

@@ -22,11 +22,14 @@ import java.util.Iterator;
 import java.util.Random;
 
 import org.apache.hadoop.util.LightWeightGSet.LinkedElement;
-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;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 /** Testing {@link LightWeightGSet} */
 public class TestLightWeightGSet {
   public static final Logger LOG =
@@ -65,7 +68,8 @@ public class TestLightWeightGSet {
     }
   }
 
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testRemoveAllViaIterator() {
     ArrayList<Integer> list = getRandomList(100, 123);
     LightWeightGSet<TestElement, TestElement> set =
@@ -78,10 +82,11 @@ public class TestLightWeightGSet {
       iter.next();
       iter.remove();
     }
-    Assert.assertEquals(0, set.size());
+    assertEquals(0, set.size());
   }
 
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testRemoveSomeViaIterator() {
     ArrayList<Integer> list = getRandomList(100, 123);
     LightWeightGSet<TestElement, TestElement> set =
@@ -105,7 +110,7 @@ public class TestLightWeightGSet {
     }
     for (Iterator<TestElement> iter = set.iterator();
         iter.hasNext(); ) {
-      Assert.assertTrue(iter.next().getVal() <= mode);
+      assertTrue(iter.next().getVal() <= mode);
     }
   }
 }

+ 6 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java

@@ -23,7 +23,8 @@ import java.util.Iterator;
 import java.util.Random;
 import java.util.Set;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -126,7 +127,8 @@ public class TestLightWeightResizableGSet {
     }
   }
 
-  @Test(timeout = 60000)
+  @Test
+  @Timeout(value = 60)
   public void testBasicOperations() {
     TestElement[] elements = generateElements(1 << 16);
     final LightWeightResizableGSet<TestKey, TestElement> set =
@@ -191,7 +193,8 @@ public class TestLightWeightResizableGSet {
     assertThat(set.size()).isZero();
   }
 
-  @Test(timeout = 60000)
+  @Test
+  @Timeout(value = 60)
   public void testRemoveAll() {
     TestElement[] elements = generateElements(1 << 16);
     final LightWeightResizableGSet<TestKey, TestElement> set =

+ 14 - 13
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java

@@ -23,8 +23,9 @@ import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 
 import org.apache.hadoop.io.Text;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestLineReader {
 
@@ -90,10 +91,10 @@ public class TestLineReader {
     lineReader.readLine(line);
     lineReader.close();
 
-    Assert.assertEquals(fillerString.toString(), line.toString());
+    assertEquals(fillerString.toString(), line.toString());
 
     lineReader.readLine(line);
-    Assert.assertEquals(expected, line.toString());
+    assertEquals(expected, line.toString());
   }
 
   /**
@@ -122,23 +123,23 @@ public class TestLineReader {
     final Text line = new Text();
 
     lineReader.readLine(line);
-    Assert.assertEquals("", line.toString());
+    assertEquals("", line.toString());
     lineReader.readLine(line);
-    Assert.assertEquals("Kerala ", line.toString());
+    assertEquals("Kerala ", line.toString());
 
     lineReader.readLine(line);
-    Assert.assertEquals("Bangalore", line.toString());
+    assertEquals("Bangalore", line.toString());
 
     lineReader.readLine(line);
-    Assert.assertEquals(" North Korea", line.toString());
+    assertEquals(" North Korea", line.toString());
 
     lineReader.readLine(line);
-    Assert.assertEquals("", line.toString());
+    assertEquals("", line.toString());
     lineReader.readLine(line);
-    Assert.assertEquals("Guantanamo", line.toString());
+    assertEquals("Guantanamo", line.toString());
 
     lineReader.readLine(line);
-    Assert.assertEquals(("ecord" + "recor" + "core"), line.toString());
+    assertEquals(("ecord" + "recor" + "core"), line.toString());
 
     lineReader.close();
   }
@@ -157,9 +158,9 @@ public class TestLineReader {
     final Text line = new Text();
 
     lineReader.readLine(line);
-    Assert.assertEquals("a", line.toString());
+    assertEquals("a", line.toString());
     lineReader.readLine(line);
-    Assert.assertEquals("ccc", line.toString());
+    assertEquals("ccc", line.toString());
 
     lineReader.close();
   }

+ 31 - 30
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java

@@ -18,15 +18,16 @@
 
 package org.apache.hadoop.util;
 
-import org.assertj.core.api.Assertions;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
 /**
  * Simple tests for utility class Lists.
  */
@@ -36,27 +37,27 @@ public class TestLists {
   public void testAddToEmptyArrayList() {
     List<String> list = Lists.newArrayList();
     list.add("record1");
-    Assert.assertEquals(1, list.size());
-    Assert.assertEquals("record1", list.get(0));
+    assertEquals(1, list.size());
+    assertEquals("record1", list.get(0));
   }
 
   @Test
   public void testAddToEmptyLinkedList() {
     List<String> list = Lists.newLinkedList();
     list.add("record1");
-    Assert.assertEquals(1, list.size());
-    Assert.assertEquals("record1", list.get(0));
+    assertEquals(1, list.size());
+    assertEquals("record1", list.get(0));
   }
 
   @Test
   public void testVarArgArrayLists() {
     List<String> list = Lists.newArrayList("record1", "record2", "record3");
     list.add("record4");
-    Assert.assertEquals(4, list.size());
-    Assert.assertEquals("record1", list.get(0));
-    Assert.assertEquals("record2", list.get(1));
-    Assert.assertEquals("record3", list.get(2));
-    Assert.assertEquals("record4", list.get(3));
+    assertEquals(4, list.size());
+    assertEquals("record1", list.get(0));
+    assertEquals("record2", list.get(1));
+    assertEquals("record3", list.get(2));
+    assertEquals("record4", list.get(3));
   }
 
   @Test
@@ -67,7 +68,7 @@ public class TestLists {
     set.add("record3");
     List<String> list = Lists.newArrayList(set);
     list.add("record4");
-    Assert.assertEquals(4, list.size());
+    assertEquals(4, list.size());
   }
 
   @Test
@@ -78,7 +79,7 @@ public class TestLists {
     set.add("record3");
     List<String> list = Lists.newLinkedList(set);
     list.add("record4");
-    Assert.assertEquals(4, list.size());
+    assertEquals(4, list.size());
   }
 
   @Test
@@ -91,34 +92,34 @@ public class TestLists {
     list.add("e");
     List<List<String>> res = Lists.
             partition(list, 2);
-    Assertions.assertThat(res)
+    assertThat(res)
             .describedAs("Number of partitions post partition")
             .hasSize(3);
-    Assertions.assertThat(res.get(0))
+    assertThat(res.get(0))
             .describedAs("Number of elements in first partition")
             .hasSize(2);
-    Assertions.assertThat(res.get(2))
+    assertThat(res.get(2))
             .describedAs("Number of elements in last partition")
             .hasSize(1);
 
     List<List<String>> res2 = Lists.
             partition(list, 1);
-    Assertions.assertThat(res2)
+    assertThat(res2)
             .describedAs("Number of partitions post partition")
             .hasSize(5);
-    Assertions.assertThat(res2.get(0))
+    assertThat(res2.get(0))
             .describedAs("Number of elements in first partition")
             .hasSize(1);
-    Assertions.assertThat(res2.get(4))
+    assertThat(res2.get(4))
             .describedAs("Number of elements in last partition")
             .hasSize(1);
 
     List<List<String>> res3 = Lists.
             partition(list, 6);
-    Assertions.assertThat(res3)
+    assertThat(res3)
             .describedAs("Number of partitions post partition")
             .hasSize(1);
-    Assertions.assertThat(res3.get(0))
+    assertThat(res3.get(0))
             .describedAs("Number of elements in first partition")
             .hasSize(5);
   }
@@ -129,18 +130,18 @@ public class TestLists {
     list.add("record1");
     list.add("record2");
     list.add("record3");
-    Assert.assertEquals(3, list.size());
-    Assert.assertEquals("record1", list.get(0));
-    Assert.assertEquals("record2", list.get(1));
-    Assert.assertEquals("record3", list.get(2));
+    assertEquals(3, list.size());
+    assertEquals("record1", list.get(0));
+    assertEquals("record2", list.get(1));
+    assertEquals("record3", list.get(2));
     list = Lists.newArrayListWithCapacity(3);
     list.add("record1");
     list.add("record2");
     list.add("record3");
-    Assert.assertEquals(3, list.size());
-    Assert.assertEquals("record1", list.get(0));
-    Assert.assertEquals("record2", list.get(1));
-    Assert.assertEquals("record3", list.get(2));
+    assertEquals(3, list.size());
+    assertEquals("record1", list.get(0));
+    assertEquals("record2", list.get(1));
+    assertEquals("record3", list.get(2));
   }
 
 }

+ 15 - 12
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java

@@ -17,10 +17,11 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -29,7 +30,7 @@ import java.util.HashMap;
 import java.util.Map;
 
 import org.apache.hadoop.thirdparty.com.google.common.net.InetAddresses;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestMachineList {
   private static String IP_LIST = "10.119.103.110,10.119.103.112,10.119.103.114";
@@ -186,14 +187,16 @@ public class TestMachineList {
     assertFalse(ml.includes("10.119.103.111"));
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testNullIpAddress() {
-    //create MachineList with a list of of ip ranges specified in CIDR format
-    MachineList ml = new MachineList(CIDR_LIST, new TestAddressFactory());
-
-    //test for exclusion with a null IP
-    assertFalse(ml.includes((String) null));
-    assertFalse(ml.includes((InetAddress) null));
+    assertThrows(IllegalArgumentException.class, () -> {
+      //create MachineList with a list of ip ranges specified in CIDR format
+      MachineList ml = new MachineList(CIDR_LIST, new TestAddressFactory());
+
+      //test for exclusion with a null IP
+      assertFalse(ml.includes((String) null));
+      assertFalse(ml.includes((InetAddress) null));
+    });
   }
 
   @Test

+ 3 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java

@@ -17,8 +17,9 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.crypto.OpensslCipher;
 import org.apache.hadoop.io.compress.zlib.ZlibFactory;

+ 64 - 39
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java

@@ -17,8 +17,9 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.*;
-import static org.junit.Assume.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -27,13 +28,9 @@ import java.util.Collection;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.ChecksumException;
 
-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.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class TestNativeCrc32 {
 
   private static final long BASE_POSITION = 0;
@@ -42,14 +39,13 @@ public class TestNativeCrc32 {
     "io.bytes.per.checksum";
   private static final int NUM_CHUNKS = 3;
 
-  private final DataChecksum.Type checksumType;
+  private DataChecksum.Type checksumType;
 
   private int bytesPerChecksum;
   private String fileName;
   private ByteBuffer data, checksums;
   private DataChecksum checksum;
 
-  @Parameters
   public static Collection<Object[]> data() {
     Collection<Object[]> params = new ArrayList<Object[]>(2);
     params.add(new Object[] { DataChecksum.Type.CRC32 });
@@ -57,16 +53,15 @@ public class TestNativeCrc32 {
     return params;
   }
 
-  public TestNativeCrc32(DataChecksum.Type checksumType) {
-    this.checksumType = checksumType;
+  public void initTestNativeCrc32(DataChecksum.Type pChecksumType) {
+    this.checksumType = pChecksumType;
+    setup();
   }
 
-  @Before
   public void setup() {
     assumeTrue(NativeCrc32.isAvailable());
-    assertEquals(
-      "These tests assume they can write a checksum value as a 4-byte int.", 4,
-      checksumType.size);
+    assertEquals(4, checksumType.size,
+        "These tests assume they can write a checksum value as a 4-byte int.");
     Configuration conf = new Configuration();
     bytesPerChecksum = conf.getInt(IO_BYTES_PER_CHECKSUM_KEY,
       IO_BYTES_PER_CHECKSUM_DEFAULT);
@@ -74,25 +69,33 @@ public class TestNativeCrc32 {
     checksum = DataChecksum.newDataChecksum(checksumType, bytesPerChecksum);
   }
 
-  @Test
-  public void testVerifyChunkedSumsSuccess() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testVerifyChunkedSumsSuccess(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndValidChecksums();
     NativeCrc32.verifyChunkedSums(bytesPerChecksum, checksumType.id,
       checksums, data, fileName, BASE_POSITION);
   }
 
-  @Test
-  public void testVerifyChunkedSumsFail() {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testVerifyChunkedSumsFail(DataChecksum.Type pChecksumType) {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndInvalidChecksums();
     assertThrows(ChecksumException.class,
         () -> NativeCrc32.verifyChunkedSums(bytesPerChecksum, checksumType.id,
-            checksums, data, fileName, BASE_POSITION));
+        checksums, data, fileName, BASE_POSITION));
   }
 
-  @Test
-  public void testVerifyChunkedSumsSuccessOddSize() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testVerifyChunkedSumsSuccessOddSize(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     // Test checksum with an odd number of bytes. This is a corner case that
     // is often broken in checksum calculation, because there is an loop which
     // handles an even multiple or 4 or 8 bytes and then some additional code
@@ -107,8 +110,11 @@ public class TestNativeCrc32 {
     bytesPerChecksum++;
   }
 
-  @Test
-  public void testVerifyChunkedSumsByteArraySuccess() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testVerifyChunkedSumsByteArraySuccess(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateArrayByteBuffers();
     fillDataAndValidChecksums();
     NativeCrc32.verifyChunkedSumsByteArray(bytesPerChecksum, checksumType.id,
@@ -116,8 +122,10 @@ public class TestNativeCrc32 {
       data.remaining(), fileName, BASE_POSITION);
   }
 
-  @Test
-  public void testVerifyChunkedSumsByteArrayFail() {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testVerifyChunkedSumsByteArrayFail(DataChecksum.Type pChecksumType) {
+    initTestNativeCrc32(pChecksumType);
     allocateArrayByteBuffers();
     fillDataAndInvalidChecksums();
     assertThrows(ChecksumException.class,
@@ -127,24 +135,33 @@ public class TestNativeCrc32 {
             BASE_POSITION));
   }
 
-  @Test
-  public void testCalculateChunkedSumsSuccess() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testCalculateChunkedSumsSuccess(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndValidChecksums();
     NativeCrc32.calculateChunkedSums(bytesPerChecksum, checksumType.id,
       checksums, data);
   }
 
-  @Test
-  public void testCalculateChunkedSumsFail() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testCalculateChunkedSumsFail(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndInvalidChecksums();
     NativeCrc32.calculateChunkedSums(bytesPerChecksum, checksumType.id,
       checksums, data);
   }
 
-  @Test
-  public void testCalculateChunkedSumsByteArraySuccess() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testCalculateChunkedSumsByteArraySuccess(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateArrayByteBuffers();
     fillDataAndValidChecksums();
     NativeCrc32.calculateChunkedSumsByteArray(bytesPerChecksum, checksumType.id,
@@ -152,8 +169,11 @@ public class TestNativeCrc32 {
       data.remaining());
   }
 
-  @Test
-  public void testCalculateChunkedSumsByteArrayFail() throws ChecksumException {
+  @ParameterizedTest
+  @MethodSource("data")
+  public void testCalculateChunkedSumsByteArrayFail(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateArrayByteBuffers();
     fillDataAndInvalidChecksums();
     NativeCrc32.calculateChunkedSumsByteArray(bytesPerChecksum, checksumType.id,
@@ -161,9 +181,12 @@ public class TestNativeCrc32 {
       data.remaining());
   }
 
-  @Test
+  @ParameterizedTest
+  @MethodSource("data")
   @SuppressWarnings("deprecation")
-  public void testNativeVerifyChunkedSumsSuccess() throws ChecksumException {
+  public void testNativeVerifyChunkedSumsSuccess(DataChecksum.Type pChecksumType)
+      throws ChecksumException {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndValidChecksums();
     NativeCrc32.nativeVerifyChunkedSums(bytesPerChecksum, checksumType.id,
@@ -171,9 +194,11 @@ public class TestNativeCrc32 {
       fileName, BASE_POSITION);
   }
 
-  @Test
+  @ParameterizedTest
+  @MethodSource("data")
   @SuppressWarnings("deprecation")
-  public void testNativeVerifyChunkedSumsFail() {
+  public void testNativeVerifyChunkedSumsFail(DataChecksum.Type pChecksumType) {
+    initTestNativeCrc32(pChecksumType);
     allocateDirectByteBuffers();
     fillDataAndInvalidChecksums();
     assertThrows(ChecksumException.class,

+ 3 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java

@@ -19,8 +19,9 @@ package org.apache.hadoop.util;
 
 import java.io.ByteArrayOutputStream;
 import java.io.PrintStream;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.util.ExitUtil.ExitException;
 

+ 9 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java

@@ -18,21 +18,20 @@
 
 package org.apache.hadoop.util;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestOptions {
 
   @Test
   public void testAppend() throws Exception {
-    assertArrayEquals("first append",
-                      new String[]{"Dr.", "Who", "hi", "there"},
-                      Options.prependOptions(new String[]{"hi", "there"},
-                                             "Dr.", "Who"));
-    assertArrayEquals("second append",
-                      new String[]{"aa","bb","cc","dd","ee","ff"},
-                      Options.prependOptions(new String[]{"dd", "ee", "ff"},
-                                             "aa", "bb", "cc"));
+    assertArrayEquals(new String[]{"Dr.", "Who", "hi", "there"},
+        Options.prependOptions(new String[]{"hi", "there"},
+        "Dr.", "Who"), "first append");
+    assertArrayEquals(new String[]{"aa", "bb", "cc", "dd", "ee", "ff"},
+        Options.prependOptions(new String[]{"dd", "ee", "ff"},
+        "aa", "bb", "cc"), "second append");
   }
 
   @Test

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java

@@ -20,7 +20,7 @@ package org.apache.hadoop.util;
 
 import java.util.function.Supplier;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.test.LambdaTestUtils;
 

+ 8 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java

@@ -18,8 +18,9 @@
 
 package org.apache.hadoop.util;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestProgress {
 
@@ -27,18 +28,18 @@ public class TestProgress {
   public void testSet(){
     Progress progress = new Progress();
     progress.set(Float.NaN);
-    Assert.assertEquals(0, progress.getProgress(), 0.0);
+    assertEquals(0, progress.getProgress(), 0.0);
 
     progress.set(Float.NEGATIVE_INFINITY);
-    Assert.assertEquals(0,progress.getProgress(),0.0);
+    assertEquals(0, progress.getProgress(), 0.0);
 
     progress.set(-1);
-    Assert.assertEquals(0,progress.getProgress(),0.0);
+    assertEquals(0, progress.getProgress(), 0.0);
 
     progress.set((float) 1.1);
-    Assert.assertEquals(1,progress.getProgress(),0.0);
+    assertEquals(1, progress.getProgress(), 0.0);
 
     progress.set(Float.POSITIVE_INFINITY);
-    Assert.assertEquals(1,progress.getProgress(),0.0);
+    assertEquals(1, progress.getProgress(), 0.0);
   }
 }

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProtoUtil.java

@@ -17,8 +17,8 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -31,7 +31,7 @@ import org.apache.hadoop.ipc.RPC.RpcKind;
 import org.apache.hadoop.ipc.RpcConstants;
 import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcRequestHeaderProto;
 import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcRequestHeaderProto.OperationProto;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.thirdparty.protobuf.CodedOutputStream;
 

+ 4 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java

@@ -29,8 +29,9 @@ import java.util.Random;
 import java.util.zip.CRC32;
 import java.util.zip.Checksum;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 /**
  * Unit test to verify that the pure-Java CRC32 algorithm gives
@@ -96,7 +97,7 @@ public class TestPureJavaCrc32 {
   }
 
   private void checkSame() {
-    Assert.assertEquals(theirs.getValue(), ours.getValue());
+    assertEquals(theirs.getValue(), ours.getValue());
   }
 
   /**

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java

@@ -19,9 +19,9 @@ package org.apache.hadoop.util;
 
 import java.util.zip.Checksum;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 
 public class TestPureJavaCrc32C {
@@ -32,6 +32,6 @@ public class TestPureJavaCrc32C {
     long crc1 = csum.getValue();
     csum.reset();
     long crc2 = csum.getValue();
-    assertEquals("reset should give same as initial value", crc1, crc2);
+    assertEquals(crc1, crc2, "reset should give same as initial value");
   }
 }

+ 14 - 16
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java

@@ -18,9 +18,9 @@
 
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.metrics2.MetricsSource;
 import org.apache.hadoop.metrics2.MetricsSystem;
@@ -28,9 +28,8 @@ import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
 import org.apache.hadoop.metrics2.impl.MetricsRecords;
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.util.DiskChecker.DiskErrorException;
-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 java.io.File;
 import java.nio.file.Files;
@@ -44,7 +43,7 @@ public class TestReadWriteDiskValidator {
 
   private MetricsSystem ms;
 
-  @Before
+  @BeforeEach
   public void setUp() {
     ms = DefaultMetricsSystem.instance();
   }
@@ -64,14 +63,13 @@ public class TestReadWriteDiskValidator {
 
     ReadWriteDiskValidatorMetrics metric =
         ReadWriteDiskValidatorMetrics.getMetric(testDir.toString());
-    Assert.assertEquals("The count number of estimator in MutableQuantiles"
-        + "metrics of file read is not right",
-        metric.getFileReadQuantiles()[0].getEstimator().getCount(), count);
+    assertEquals(metric.getFileReadQuantiles()[0].getEstimator().getCount(), count,
+        "The count number of estimator in MutableQuantiles"
+        + "metrics of file read is not right");
 
-    Assert.assertEquals("The count number of estimator in MutableQuantiles"
-        + "metrics of file write is not right",
-        metric.getFileWriteQuantiles()[0].getEstimator().getCount(),
-        count);
+    assertEquals(metric.getFileWriteQuantiles()[0].getEstimator().getCount(),
+        count, "The count number of estimator in MutableQuantiles"
+        + "metrics of file write is not right");
 
     MetricsSource source = ms.getSource(
         ReadWriteDiskValidatorMetrics.sourceName(testDir.toString()));
@@ -154,8 +152,8 @@ public class TestReadWriteDiskValidator {
         "FailureCount", 2);
     Long lastFailureTime2 = (Long) MetricsRecords.getMetricValueByName(
         collector.getRecords().get(1), "LastFailureTime");
-    assertTrue("The first failure time should be less than the second one",
-        lastFailureTime1 < lastFailureTime2);
+    assertTrue(lastFailureTime1 < lastFailureTime2,
+        "The first failure time should be less than the second one");
 
     testDir.delete();
   }

+ 11 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java

@@ -25,13 +25,15 @@ import java.net.URLClassLoader;
 import java.util.HashMap;
 import java.util.List;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.test.GenericTestUtils.LogCapturer;
 import org.assertj.core.api.Assertions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -40,7 +42,7 @@ public class TestReflectionUtils {
   private static Class toConstruct[] = { String.class, TestReflectionUtils.class, HashMap.class };
   private Throwable failure = null;
 
-  @Before
+  @BeforeEach
   public void setUp() {
     ReflectionUtils.clearCache();
   }
@@ -116,7 +118,7 @@ public class TestReflectionUtils {
       assertEquals(cl, o.getClass());
     }
     System.gc();
-    assertTrue(cacheSize()+" too big", cacheSize()<iterations);
+    assertTrue(cacheSize()<iterations, cacheSize()+" too big");
   }
   
   @Test
@@ -151,10 +153,10 @@ public class TestReflectionUtils {
       }
     }
     
-    assertTrue("Missing parent field", containsParentField);
-    assertTrue("Missing child field", containsChildField);
-    assertTrue("Missing parent method", containsParentMethod);
-    assertTrue("Missing child method", containsChildMethod);
+    assertTrue(containsParentField, "Missing parent field");
+    assertTrue(containsChildField, "Missing child field");
+    assertTrue(containsParentMethod, "Missing parent method");
+    assertTrue(containsChildMethod, "Missing child method");
   }
 
   @Test

+ 25 - 25
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java

@@ -18,10 +18,10 @@
 package org.apache.hadoop.util;
 
 import static org.apache.hadoop.util.RunJar.MATCH_ANY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
@@ -46,10 +46,9 @@ import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.fs.LocalFileSystem;
 import org.apache.hadoop.fs.Path;
 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;
 
 public class TestRunJar {
   private static final String FOOBAR_TXT = "foobar.txt";
@@ -62,7 +61,7 @@ public class TestRunJar {
   private static final long MOCKED_NOW = 1_460_389_972_000L;
   private static final long MOCKED_NOW_PLUS_TWO_SEC = MOCKED_NOW + 2_000;
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
     TEST_ROOT_DIR = GenericTestUtils.getTestDir(getClass().getSimpleName());
     if (!TEST_ROOT_DIR.exists()) {
@@ -72,7 +71,7 @@ public class TestRunJar {
     makeTestJar();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     FileUtil.fullyDelete(TEST_ROOT_DIR);
   }
@@ -106,10 +105,10 @@ public class TestRunJar {
     // Unjar everything
     RunJar.unJar(new File(TEST_ROOT_DIR, TEST_JAR_NAME),
                  unjarDir, MATCH_ANY);
-    assertTrue("foobar unpacked",
-               new File(unjarDir, TestRunJar.FOOBAR_TXT).exists());
-    assertTrue("foobaz unpacked",
-               new File(unjarDir, FOOBAZ_TXT).exists());
+    assertTrue(new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(),
+        "foobar unpacked");
+    assertTrue(new File(unjarDir, FOOBAZ_TXT).exists(),
+        "foobaz unpacked");
   }
 
   /**
@@ -123,10 +122,9 @@ public class TestRunJar {
     RunJar.unJar(new File(TEST_ROOT_DIR, TEST_JAR_NAME),
                  unjarDir,
                  Pattern.compile(".*baz.*"));
-    assertFalse("foobar not unpacked",
-                new File(unjarDir, TestRunJar.FOOBAR_TXT).exists());
-    assertTrue("foobaz unpacked",
-               new File(unjarDir, FOOBAZ_TXT).exists());
+    assertFalse(new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(),
+        "foobar not unpacked");
+    assertTrue(new File(unjarDir, FOOBAZ_TXT).exists(), "foobaz unpacked");
   }
 
   private File generateBigJar(File dir) throws Exception {
@@ -157,18 +155,18 @@ public class TestRunJar {
   public void testBigJar() throws Exception {
     Random r = new Random(System.currentTimeMillis());
     File dir = new File(TEST_ROOT_DIR, Long.toHexString(r.nextLong()));
-    Assert.assertTrue(dir.mkdirs());
+    assertTrue(dir.mkdirs());
     File input = generateBigJar(dir);
     File output = new File(dir, "job2.jar");
     try {
       try (InputStream is = new FileInputStream(input)) {
         RunJar.unJarAndSave(is, dir, "job2.jar", Pattern.compile(".*"));
       }
-      Assert.assertEquals(input.length(), output.length());
+      assertEquals(input.length(), output.length());
       for (int i = 0; i < 10; ++i) {
         File subdir = new File(dir, ((i % 2 == 0) ? "dir/" : ""));
         File f = new File(subdir, "f" + Integer.toString(i));
-        Assert.assertEquals(756, f.length());
+        assertEquals(756, f.length());
       }
     } finally {
       // Clean up
@@ -186,14 +184,16 @@ public class TestRunJar {
             unjarDir, MATCH_ANY);
 
     String failureMessage = "Last modify time was lost during unJar";
-    assertEquals(failureMessage, MOCKED_NOW, new File(unjarDir, TestRunJar.FOOBAR_TXT).lastModified());
-    assertEquals(failureMessage, MOCKED_NOW_PLUS_TWO_SEC, new File(unjarDir, FOOBAZ_TXT).lastModified());
+    assertEquals(MOCKED_NOW, new File(unjarDir, TestRunJar.FOOBAR_TXT).lastModified(),
+        failureMessage);
+    assertEquals(MOCKED_NOW_PLUS_TWO_SEC, new File(unjarDir, FOOBAZ_TXT).lastModified(),
+        failureMessage);
   }
 
   private File getUnjarDir(String dirName) {
     File unjarDir = new File(TEST_ROOT_DIR, dirName);
-    assertFalse("unjar dir shouldn't exist at test start",
-                new File(unjarDir, TestRunJar.FOOBAR_TXT).exists());
+    assertFalse(new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(),
+        "unjar dir shouldn't exist at test start");
     return unjarDir;
   }
 

+ 25 - 34
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java

@@ -17,11 +17,14 @@
  */
 package org.apache.hadoop.util;
 
-import java.util.concurrent.TimeUnit;
 import java.util.function.Supplier;
 import org.apache.commons.io.FileUtils;
 
-import org.junit.Assert;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Assertions;
 
 import java.io.BufferedReader;
 import java.io.File;
@@ -40,24 +43,11 @@ import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.test.GenericTestUtils;
 
 import static org.apache.hadoop.util.Shell.*;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
 
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.rules.Timeout;
-
-public class TestShell extends Assert {
-  /**
-   * Set the timeout for every test.
-   */
-  @Rule
-  public Timeout testTimeout = new Timeout(30000, TimeUnit.MILLISECONDS);
-
-  @Rule
-  public TestName methodName = new TestName();
+@Timeout(value = 30)
+public class TestShell extends Assertions {
 
   private File rootTestDir = GenericTestUtils.getTestDir();
 
@@ -94,11 +84,11 @@ public class TestShell extends Assert {
     }
   }
 
-  @Before
-  public void setup() {
+  @BeforeEach
+  public void setup(TestInfo testInfo) {
     rootTestDir.mkdirs();
-    assertTrue("Not a directory " + rootTestDir, rootTestDir.isDirectory());
-    methodDir = new File(rootTestDir, methodName.getMethodName());
+    assertTrue(rootTestDir.isDirectory(), "Not a directory " + rootTestDir);
+    methodDir = new File(rootTestDir, testInfo.getDisplayName());
   }
 
   @Test
@@ -115,7 +105,7 @@ public class TestShell extends Assert {
    * @param search what to search for it
    */
   private void assertInString(String string, String search) {
-    assertNotNull("Empty String", string);
+    assertNotNull(string, "Empty String");
     if (!string.contains(search)) {
       fail("Did not find \"" + search + "\" in " + string);
     }
@@ -133,7 +123,7 @@ public class TestShell extends Assert {
 
   @Test
   public void testShellCommandTimeout() throws Throwable {
-    Assume.assumeFalse(WINDOWS);
+    assumeFalse(WINDOWS);
     String rootDir = rootTestDir.getAbsolutePath();
     File shellFile = new File(rootDir, "timeout.sh");
     String timeoutCommand = "sleep 4; echo \"hello\"";
@@ -151,18 +141,18 @@ public class TestShell extends Assert {
       //When timing out exception is thrown.
     }
     shellFile.delete();
-    assertTrue("Script did not timeout" , shexc.isTimedOut());
+    assertTrue(shexc.isTimedOut(), "Script did not timeout");
   }
 
   @Test
   public void testEnvVarsWithInheritance() throws Exception {
-    Assume.assumeFalse(WINDOWS);
+    assumeFalse(WINDOWS);
     testEnvHelper(true);
   }
 
   @Test
   public void testEnvVarsWithoutInheritance() throws Exception {
-    Assume.assumeFalse(WINDOWS);
+    assumeFalse(WINDOWS);
     testEnvHelper(false);
   }
 
@@ -246,7 +236,7 @@ public class TestShell extends Assert {
       expectedCommand = new String[] {"bash", "-c", "kill -0 '" + anyPid +
             "'" };
     }
-    Assert.assertArrayEquals(expectedCommand, checkProcessAliveCommand);
+    assertArrayEquals(expectedCommand, checkProcessAliveCommand);
   }
 
   @Test
@@ -268,7 +258,7 @@ public class TestShell extends Assert {
       expectedCommand = new String[]{ "bash", "-c", "kill -9 '" + anyPid +
             "'"};
     }
-    Assert.assertArrayEquals(expectedCommand, checkProcessAliveCommand);
+    assertArrayEquals(expectedCommand, checkProcessAliveCommand);
   }
 
   private void testInterval(long interval) throws IOException {
@@ -388,7 +378,7 @@ public class TestShell extends Assert {
    */
   @Test
   public void testNoWinutilsOnUnix() throws Throwable {
-    Assume.assumeFalse(WINDOWS);
+    assumeFalse(WINDOWS);
     try {
       getWinUtilsFile();
     } catch (FileNotFoundException ex) {
@@ -477,9 +467,10 @@ public class TestShell extends Assert {
     assertEquals("''\\''foo'\\''bar'\\'''", Shell.bashQuote("'foo'bar'"));
   }
 
-  @Test(timeout=120000)
+  @Test
+  @Timeout(value = 120)
   public void testDestroyAllShellProcesses() throws Throwable {
-    Assume.assumeFalse(WINDOWS);
+    assumeFalse(WINDOWS);
     StringBuilder sleepCommand = new StringBuilder();
     sleepCommand.append("sleep 200");
     String[] shellCmd = {"bash", "-c", sleepCommand.toString()};
@@ -535,6 +526,6 @@ public class TestShell extends Assert {
 
   @Test
   public void testIsBashSupported() throws InterruptedIOException {
-    assumeTrue("Bash is not supported", Shell.checkIsBashSupported());
+    assumeTrue(Shell.checkIsBashSupported(), "Bash is not supported");
   }
 }

+ 38 - 44
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java

@@ -21,7 +21,7 @@ import java.util.List;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -30,11 +30,11 @@ import org.apache.hadoop.conf.Configuration;
 import static java.lang.Thread.sleep;
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.SERVICE_SHUTDOWN_TIMEOUT;
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.SERVICE_SHUTDOWN_TIMEOUT_DEFAULT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestShutdownHookManager {
 
@@ -54,7 +54,7 @@ public class TestShutdownHookManager {
    */
   @Test
   public void shutdownHookManager() {
-    assertNotNull("No ShutdownHookManager", mgr);
+    assertNotNull(mgr, "No ShutdownHookManager");
     assertEquals(0, mgr.getShutdownHooksInOrder().size());
     Hook hook1 = new Hook("hook1", 0, false);
     Hook hook2 = new Hook("hook2", 0, false);
@@ -102,13 +102,11 @@ public class TestShutdownHookManager {
     ShutdownHookManager.HookEntry hookEntry5 = mgr.getShutdownHooksInOrder()
         .get(0);
     assertEquals(hook5, hookEntry5.getHook());
-    assertEquals("default timeout not used",
-        ShutdownHookManager.getShutdownTimeout(new Configuration()),
-        hookEntry5.getTimeout());
-    assertEquals("hook priority", 5, hookEntry5.getPriority());
+    assertEquals(ShutdownHookManager.getShutdownTimeout(new Configuration()),
+        hookEntry5.getTimeout(), "default timeout not used");
+    assertEquals(5, hookEntry5.getPriority(), "hook priority");
     // remove this to avoid a longer sleep in the test run
-    assertTrue("failed to remove " + hook5,
-        mgr.removeShutdownHook(hook5));
+    assertTrue(mgr.removeShutdownHook(hook5), "failed to remove " + hook5);
 
 
     // now execute the hook shutdown sequence
@@ -116,7 +114,7 @@ public class TestShutdownHookManager {
     LOG.info("invoking executeShutdown()");
     int timeouts = mgr.executeShutdown();
     LOG.info("Shutdown completed");
-    assertEquals("Number of timed out hooks", 1, timeouts);
+    assertEquals(1, timeouts, "Number of timed out hooks");
 
     List<ShutdownHookManager.HookEntry> hooks
         = mgr.getShutdownHooksInOrder();
@@ -124,34 +122,32 @@ public class TestShutdownHookManager {
     // analyze the hooks
     for (ShutdownHookManager.HookEntry entry : hooks) {
       Hook hook = (Hook) entry.getHook();
-      assertTrue("Was not invoked " + hook, hook.invoked);
+      assertTrue(hook.invoked, "Was not invoked " + hook);
       // did any hook raise an exception?
       hook.maybeThrowAssertion();
     }
 
     // check the state of some of the invoked hooks
     // hook4 was invoked first, but it timed out.
-    assertEquals("Expected to be invoked first " + hook4,
-        1, hook4.invokedOrder);
-    assertFalse("Expected to time out " + hook4, hook4.completed);
+    assertEquals(1, hook4.invokedOrder, "Expected to be invoked first " + hook4);
+    assertFalse(hook4.completed, "Expected to time out " + hook4);
 
 
     // hook1 completed, but in order after the others, so its start time
     // is the longest.
-    assertTrue("Expected to complete " + hook1, hook1.completed);
+    assertTrue(hook1.completed, "Expected to complete " + hook1);
     long invocationInterval = hook1.startTime - hook4.startTime;
-    assertTrue("invocation difference too short " + invocationInterval,
-        invocationInterval >= hook4timeout * 1000);
-    assertTrue("sleeping hook4 blocked other threads for " + invocationInterval,
-        invocationInterval < hook4.sleepTime);
+    assertTrue(invocationInterval >= hook4timeout * 1000,
+        "invocation difference too short " + invocationInterval);
+    assertTrue(invocationInterval < hook4.sleepTime,
+        "sleeping hook4 blocked other threads for " + invocationInterval);
 
     // finally, clear the hooks
     mgr.clearShutdownHooks();
     // and verify that the hooks are empty
     assertFalse(mgr.hasShutdownHook(hook1));
-    assertEquals("shutdown hook list is not empty",
-        0,
-        mgr.getShutdownHooksInOrder().size());
+    assertEquals(0, mgr.getShutdownHooksInOrder().size(),
+        "shutdown hook list is not empty");
   }
 
   @Test
@@ -161,9 +157,8 @@ public class TestShutdownHookManager {
     long shutdownTimeout = 5;
     conf.setTimeDuration(SERVICE_SHUTDOWN_TIMEOUT,
         shutdownTimeout, TimeUnit.SECONDS);
-    assertEquals(SERVICE_SHUTDOWN_TIMEOUT,
-        shutdownTimeout,
-        ShutdownHookManager.getShutdownTimeout(conf));
+    assertEquals(shutdownTimeout, ShutdownHookManager.getShutdownTimeout(conf),
+        SERVICE_SHUTDOWN_TIMEOUT);
   }
 
   /**
@@ -177,9 +172,8 @@ public class TestShutdownHookManager {
     long shutdownTimeout = 50;
     conf.setTimeDuration(SERVICE_SHUTDOWN_TIMEOUT,
         shutdownTimeout, TimeUnit.NANOSECONDS);
-    assertEquals(SERVICE_SHUTDOWN_TIMEOUT,
-        ShutdownHookManager.TIMEOUT_MINIMUM,
-        ShutdownHookManager.getShutdownTimeout(conf));
+    assertEquals(ShutdownHookManager.TIMEOUT_MINIMUM,
+        ShutdownHookManager.getShutdownTimeout(conf), SERVICE_SHUTDOWN_TIMEOUT);
   }
 
   /**
@@ -197,37 +191,37 @@ public class TestShutdownHookManager {
     mgr.addShutdownHook(hook, 5);
     List<ShutdownHookManager.HookEntry> hookList
         = mgr.getShutdownHooksInOrder();
-    assertEquals("Hook added twice", 1, hookList.size());
+    assertEquals(1, hookList.size(), "Hook added twice");
     ShutdownHookManager.HookEntry entry = hookList.get(0);
-    assertEquals("priority of hook", 2, entry.getPriority());
-    assertEquals("timeout of hook", 1, entry.getTimeout());
+    assertEquals(2, entry.getPriority(), "priority of hook");
+    assertEquals(1, entry.getTimeout(), "timeout of hook");
 
     // remove the hook
-    assertTrue("failed to remove hook " + hook, mgr.removeShutdownHook(hook));
+    assertTrue(mgr.removeShutdownHook(hook), "failed to remove hook " + hook);
     // which will fail a second time
-    assertFalse("expected hook removal to fail", mgr.removeShutdownHook(hook));
+    assertFalse(mgr.removeShutdownHook(hook), "expected hook removal to fail");
 
     // now register it
     mgr.addShutdownHook(hook, 5);
     hookList = mgr.getShutdownHooksInOrder();
     entry = hookList.get(0);
-    assertEquals("priority of hook", 5, entry.getPriority());
-    assertNotEquals("timeout of hook", 1, entry.getTimeout());
+    assertEquals(5, entry.getPriority(), "priority of hook");
+    assertNotEquals(1, entry.getTimeout(), "timeout of hook");
 
   }
 
   @Test
   public void testShutdownRemove() throws Throwable {
-    assertNotNull("No ShutdownHookManager", mgr);
+    assertNotNull(mgr, "No ShutdownHookManager");
     assertEquals(0, mgr.getShutdownHooksInOrder().size());
     Hook hook1 = new Hook("hook1", 0, false);
     Hook hook2 = new Hook("hook2", 0, false);
     mgr.addShutdownHook(hook1, 9); // create Hook1 with priority 9
-    assertTrue("No hook1", mgr.hasShutdownHook(hook1)); // hook1 lookup works
+    assertTrue(mgr.hasShutdownHook(hook1), "No hook1"); // hook1 lookup works
     assertEquals(1, mgr.getShutdownHooksInOrder().size()); // 1 hook
-    assertFalse("Delete hook2 should not be allowed",
-      mgr.removeShutdownHook(hook2));
-    assertTrue("Can't delete hook1", mgr.removeShutdownHook(hook1));
+    assertFalse(mgr.removeShutdownHook(hook2),
+        "Delete hook2 should not be allowed");
+    assertTrue(mgr.removeShutdownHook(hook1), "Can't delete hook1");
     assertEquals(0, mgr.getShutdownHooksInOrder().size());
   }
 

+ 10 - 8
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownThreadsHelper.java

@@ -17,11 +17,12 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import java.util.concurrent.ScheduledThreadPoolExecutor;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestShutdownThreadsHelper {
   private Runnable sampleRunnable = new Runnable() {
@@ -35,14 +36,15 @@ public class TestShutdownThreadsHelper {
     }
   };
 
-  @Test (timeout = 3000)
+  @Test
+  @Timeout(value = 3)
   public void testShutdownThread() {
     Thread thread = new Thread(sampleRunnable);
     thread.start();
     boolean ret = ShutdownThreadsHelper.shutdownThread(thread);
     boolean isTerminated = !thread.isAlive();
-    assertEquals("Incorrect return value", ret, isTerminated);
-    assertTrue("Thread is not shutdown", isTerminated);
+    assertEquals(ret, isTerminated, "Incorrect return value");
+    assertTrue(isTerminated, "Thread is not shutdown");
 
   }
 
@@ -52,7 +54,7 @@ public class TestShutdownThreadsHelper {
     executor.execute(sampleRunnable);
     boolean ret = ShutdownThreadsHelper.shutdownExecutorService(executor);
     boolean isTerminated = executor.isTerminated();
-    assertEquals("Incorrect return value", ret, isTerminated);
-    assertTrue("ExecutorService is not shutdown", isTerminated);
+    assertEquals(ret, isTerminated, "Incorrect return value");
+    assertTrue(isTerminated, "ExecutorService is not shutdown");
   }
 }

+ 10 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java

@@ -19,23 +19,27 @@
 package org.apache.hadoop.util;
 
 import org.apache.commons.lang3.SystemUtils;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
 public class TestSignalLogger {
   public static final Logger LOG =
       LoggerFactory.getLogger(TestSignalLogger.class);
   
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testInstall() throws Exception {
-    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
+    assumeTrue(SystemUtils.IS_OS_UNIX);
     SignalLogger.INSTANCE.register(LOG);
     try {
       SignalLogger.INSTANCE.register(LOG);
-      Assert.fail("expected IllegalStateException from double registration");
+      fail("expected IllegalStateException from double registration");
     } catch (IllegalStateException e) {
       // fall through
     }

+ 11 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java

@@ -17,19 +17,21 @@
  */
 package org.apache.hadoop.util;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestStopWatch {
 
   @Test
   public void testStartAndStop() throws Exception {
     try (StopWatch sw = new StopWatch()) {
-      Assert.assertFalse(sw.isRunning());
+      assertFalse(sw.isRunning());
       sw.start();
-      Assert.assertTrue(sw.isRunning());
+      assertTrue(sw.isRunning());
       sw.stop();
-      Assert.assertFalse(sw.isRunning());
+      assertFalse(sw.isRunning());
     }
   }
 
@@ -46,16 +48,16 @@ public class TestStopWatch {
     try {
       sw.stop();
     } catch (Exception e) {
-      Assert.assertTrue("IllegalStateException is expected",
-          e instanceof IllegalStateException);
+      assertTrue(e instanceof IllegalStateException,
+          "IllegalStateException is expected");
     }
     sw.reset();
     sw.start();
     try {
       sw.start();
     } catch (Exception e) {
-      Assert.assertTrue("IllegalStateException is expected",
-          e instanceof IllegalStateException);
+      assertTrue(e instanceof IllegalStateException,
+          "IllegalStateException is expected");
     }
   }
 

+ 3 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java

@@ -18,10 +18,11 @@
 
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.apache.hadoop.util.StringInterner.*;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * 

+ 62 - 63
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java

@@ -24,12 +24,13 @@ import static org.apache.hadoop.test.LambdaTestUtils.intercept;
 import static org.apache.hadoop.util.StringUtils.STRING_COLLECTION_SPLIT_EQUALS_INVALID_ARG;
 import static org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix.long2String;
 import static org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix.string2long;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -48,8 +49,8 @@ import org.apache.commons.lang3.time.FastDateFormat;
 import org.apache.hadoop.test.UnitTestcaseTimeLimit;
 import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
 
-import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class TestStringUtils extends UnitTestcaseTimeLimit {
   final private static String NULL_STR = null;
@@ -66,7 +67,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
   final private static FastDateFormat FAST_DATE_FORMAT =
       FastDateFormat.getInstance("d-MMM-yyyy HH:mm:ss");
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testEscapeString() throws Exception {
     assertEquals(NULL_STR, StringUtils.escapeString(NULL_STR));
     assertEquals(EMPTY_STR, StringUtils.escapeString(EMPTY_STR));
@@ -80,7 +82,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
         StringUtils.escapeString(STR_WITH_BOTH2));
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSplit() throws Exception {
     assertEquals(NULL_STR, StringUtils.split(NULL_STR));
     String[] splits = StringUtils.split(EMPTY_STR);
@@ -110,7 +113,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     assertEquals(ESCAPED_STR_WITH_BOTH2, splits[0]);    
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSimpleSplit() throws Exception {
     final String[] TO_TEST = {
         "a/b/c",
@@ -120,13 +124,13 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
         "/",
         "////"};
     for (String testSubject : TO_TEST) {
-      assertArrayEquals("Testing '" + testSubject + "'",
-        testSubject.split("/"),
-        StringUtils.split(testSubject, '/'));
+      assertArrayEquals(testSubject.split("/"),
+          StringUtils.split(testSubject, '/'), "Testing '" + testSubject + "'");
     }
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testUnescapeString() throws Exception {
     assertEquals(NULL_STR, StringUtils.unEscapeString(NULL_STR));
     assertEquals(EMPTY_STR, StringUtils.unEscapeString(EMPTY_STR));
@@ -158,7 +162,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
         StringUtils.unEscapeString(ESCAPED_STR_WITH_BOTH2));
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testTraditionalBinaryPrefix() throws Exception {
     //test string2long(..)
     String[] symbol = {"k", "m", "g", "t", "p", "e"};
@@ -241,19 +246,19 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
         { // n = 2^e
           final long n = 1L << e;
           final String expected = (n/p.value) + " " + p.symbol;
-          assertEquals("n=" + n, expected, long2String(n, null, 2));
+          assertEquals(expected, long2String(n, null, 2), "n=" + n);
         }
   
         { // n = 2^e + 1
           final long n = (1L << e) + 1;
           final String expected = (n/p.value) + trailingZeros + p.symbol;
-          assertEquals("n=" + n, expected, long2String(n, null, decimalPlace));
+          assertEquals(expected, long2String(n, null, decimalPlace), "n=" + n);
         }
   
         { // n = 2^e - 1
           final long n = (1L << e) - 1;
           final String expected = ((n+1)/p.value) + trailingZeros + p.symbol;
-          assertEquals("n=" + n, expected, long2String(n, null, decimalPlace));
+          assertEquals(expected, long2String(n, null, decimalPlace), "n=" + n);
         }
       }
     }
@@ -284,7 +289,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     assertEquals("0.5430%", StringUtils.formatPercent(0.00543, 4));
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testJoin() {
     List<String> s = new ArrayList<String>();
     s.add("a");
@@ -300,7 +306,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     assertEquals("a:b:c", StringUtils.join(':', s.subList(0, 3)));
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testGetTrimmedStrings() throws Exception {
     String compactDirList = "/spindle1/hdfs,/spindle2/hdfs,/spindle3/hdfs";
     String spacedDirList = "/spindle1/hdfs, /spindle2/hdfs, /spindle3/hdfs";
@@ -322,7 +329,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     assertArrayEquals(emptyArray, estring);
   } 
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testCamelize() {
     // common use cases
     assertEquals("Map", StringUtils.camelize("MAP"));
@@ -358,7 +366,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     assertEquals("Zz", StringUtils.camelize("zZ"));
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testStringToURI() {
     String[] str = new String[] { "file://" };
     try {
@@ -369,20 +378,19 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     }
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSimpleHostName() {
-    assertEquals("Should return hostname when FQDN is specified",
-            "hadoop01",
-            StringUtils.simpleHostname("hadoop01.domain.com"));
-    assertEquals("Should return hostname when only hostname is specified",
-            "hadoop01",
-            StringUtils.simpleHostname("hadoop01"));
-    assertEquals("Should not truncate when IP address is passed",
-            "10.10.5.68",
-            StringUtils.simpleHostname("10.10.5.68"));
+    assertEquals("hadoop01", StringUtils.simpleHostname("hadoop01.domain.com"),
+        "Should return hostname when FQDN is specified");
+    assertEquals("hadoop01", StringUtils.simpleHostname("hadoop01"),
+        "Should return hostname when only hostname is specified");
+    assertEquals("10.10.5.68", StringUtils.simpleHostname("10.10.5.68"),
+        "Should not truncate when IP address is passed");
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testReplaceTokensShellEnvVars() {
     Pattern pattern = StringUtils.SHELL_ENV_VAR_PATTERN;
     Map<String, String> replacements = new HashMap<String, String>();
@@ -403,7 +411,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
       replacements));
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testReplaceTokensWinEnvVars() {
     Pattern pattern = StringUtils.WIN_ENV_VAR_PATTERN;
     Map<String, String> replacements = new HashMap<String, String>();
@@ -471,8 +480,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
               FAST_DATE_FORMAT, start, end);
           String formattedTime2 = StringUtils.getFormattedTimeWithDiff(
               FAST_DATE_FORMAT, start, end);
-          assertTrue("Method returned inconsistent results indicative of"
-              + " a race condition", formattedTime1.equals(formattedTime2));
+          assertTrue(formattedTime1.equals(formattedTime2),
+              "Method returned inconsistent results indicative of a race condition");
 
         }
       });
@@ -487,16 +496,14 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     long timeDiff = 523452311;
     String timeDiffStr = "99hrs, 59mins, 59sec";
 
-    assertEquals("Incorrect time diff string returned", timeDiffStr,
-        StringUtils.formatTimeSortable(timeDiff));
+    assertEquals(timeDiffStr, StringUtils.formatTimeSortable(timeDiff),
+        "Incorrect time diff string returned");
   }
 
   @Test
   public void testIsAlpha() {
-    assertTrue("Reported hello as non-alpha string",
-        StringUtils.isAlpha("hello"));
-    assertFalse("Reported hello1 as alpha string",
-        StringUtils.isAlpha("hello1"));
+    assertTrue(StringUtils.isAlpha("hello"), "Reported hello as non-alpha string");
+    assertFalse(StringUtils.isAlpha("hello1"), "Reported hello1 as alpha string");
   }
 
   @Test
@@ -504,8 +511,8 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     String htmlStr = "<p>Hello. How are you?</p>";
     String escapedStr = "&lt;p&gt;Hello. How are you?&lt;/p&gt;";
 
-    assertEquals("Incorrect escaped HTML string returned",
-        escapedStr, StringUtils.escapeHTML(htmlStr));
+    assertEquals(escapedStr, StringUtils.escapeHTML(htmlStr),
+        "Incorrect escaped HTML string returned");
   }
 
   @Test
@@ -521,21 +528,18 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
   public void testStringCollectionSplitByEqualsSuccess() {
     Map<String, String> splitMap =
         StringUtils.getTrimmedStringCollectionSplitByEquals("");
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(0);
 
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(null);
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(0);
 
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(
         "element.first.key1 = element.first.val1");
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(1)
         .containsEntry("element.first.key1", "element.first.val1");
@@ -543,8 +547,7 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(
         "element.xyz.key1 =element.abc.val1 , element.xyz.key2= element.abc.val2");
 
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(2)
         .containsEntry("element.xyz.key1", "element.abc.val1")
@@ -558,8 +561,7 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
             + " element.xyz.key6      =       element.abc.val6 \n , \n"
             + "element.xyz.key7=element.abc.val7,\n");
 
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(7)
         .containsEntry("element.xyz.key1", "element.abc.val1")
@@ -572,8 +574,7 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
 
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(
         "element.first.key1 = element.first.val2 ,element.first.key1 =element.first.val1");
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(1)
         .containsEntry("element.first.key1", "element.first.val1");
@@ -581,16 +582,14 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(
         ",,, , ,, ,element.first.key1 = element.first.val2 ,"
             + "element.first.key1 = element.first.val1 , ,,, ,");
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(1)
         .containsEntry("element.first.key1", "element.first.val1");
 
     splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(
         ",, , ,      ,, ,");
-    Assertions
-        .assertThat(splitMap)
+    assertThat(splitMap)
         .describedAs("Map of key value pairs split by equals(=) and comma(,)")
         .hasSize(0);
 
@@ -634,7 +633,7 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
   }
 
   // Benchmark for StringUtils split
-  public static void main(String []args) {
+  /*public static void main(String []args) {
     final String TO_SPLIT = "foo,bar,baz,blah,blah";
     for (boolean useOurs : new boolean[] { false, true }) {
       for (int outer=0; outer < 10; outer++) {
@@ -658,5 +657,5 @@ public class TestStringUtils extends UnitTestcaseTimeLimit {
         }
       }
     }
-  }
+  }*/
 }

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java

@@ -24,10 +24,10 @@ import java.io.IOException;
 import java.util.Random;
 
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-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;
 
 /**
  * A JUnit test to test {@link SysInfoLinux}

+ 11 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java

@@ -18,8 +18,9 @@
 
 package org.apache.hadoop.util;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestSysInfoWindows {
 
@@ -43,7 +44,8 @@ public class TestSysInfoWindows {
     }
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void parseSystemInfoString() {
     SysInfoWindowsMock tester = new SysInfoWindowsMock();
     tester.setSysinfoString(
@@ -69,7 +71,8 @@ public class TestSysInfoWindows {
         tester.getNumVCoresUsed(), 0.0);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void refreshAndCpuUsage() throws InterruptedException {
     SysInfoWindowsMock tester = new SysInfoWindowsMock();
     tester.setSysinfoString(
@@ -108,7 +111,8 @@ public class TestSysInfoWindows {
                  tester.getNumVCoresUsed(), 0.0);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void refreshAndCpuUsageMulticore() throws InterruptedException {
     // test with 12 cores
     SysInfoWindowsMock tester = new SysInfoWindowsMock();
@@ -138,7 +142,8 @@ public class TestSysInfoWindows {
                  tester.getNumVCoresUsed(), 0.0);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void errorInGetSystemInfo() {
     SysInfoWindowsMock tester = new SysInfoWindowsMock();
     // info str derived from windows shell command is null

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestTime.java

@@ -18,11 +18,11 @@
 
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.text.SimpleDateFormat;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * A JUnit test to test {@link Time}.

+ 3 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java

@@ -17,9 +17,10 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestVersionUtil {
 

+ 19 - 19
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java

@@ -22,14 +22,14 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicLong;
 
-import org.assertj.core.api.Assertions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.fs.impl.WeakReferenceThreadMap;
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 
 import static org.apache.hadoop.test.LambdaTestUtils.intercept;
+import static org.assertj.core.api.Assertions.assertThat;
 
 /**
  * Test {@link WeakReferenceMap} and {@link WeakReferenceThreadMap}.
@@ -50,7 +50,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    */
   private List<Integer> lostReferences;
 
-  @Before
+  @BeforeEach
   public void setup() {
     lostReferences = new ArrayList<>();
     referenceMap = new WeakReferenceMap<>(
@@ -156,12 +156,12 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
         id -> "Entry for thread ID " + id + " (" + created.incrementAndGet() + ")",
         id -> lost.incrementAndGet());
 
-    Assertions.assertThat(threadMap.setForCurrentThread("hello"))
+    assertThat(threadMap.setForCurrentThread("hello"))
         .describedAs("current thread map value on first set")
         .isNull();
 
     // second attempt returns itself
-    Assertions.assertThat(threadMap.setForCurrentThread("hello"))
+    assertThat(threadMap.setForCurrentThread("hello"))
         .describedAs("current thread map value on second set")
         .isEqualTo("hello");
 
@@ -170,30 +170,30 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
         threadMap.setForCurrentThread(null));
 
     // the map is unchanged
-    Assertions.assertThat(threadMap.getForCurrentThread())
+    assertThat(threadMap.getForCurrentThread())
         .describedAs("current thread map value")
         .isEqualTo("hello");
 
     // remove the value and assert what the removed entry was
-    Assertions.assertThat(threadMap.removeForCurrentThread())
+    assertThat(threadMap.removeForCurrentThread())
         .describedAs("removed thread map value")
         .isEqualTo("hello");
 
     // remove the value again; this time the removed value is null
-    Assertions.assertThat(threadMap.removeForCurrentThread())
+    assertThat(threadMap.removeForCurrentThread())
         .describedAs("removed thread map value on second call")
         .isNull();
 
     // lookup will return a new instance created by the factory
     long c1 = created.get();
     String dynamicValue = threadMap.getForCurrentThread();
-    Assertions.assertThat(dynamicValue)
+    assertThat(dynamicValue)
         .describedAs("dynamically created thread map value")
         .startsWith("Entry for thread ID")
         .contains("(" + (c1 + 1) + ")");
 
     // and we can overwrite that
-    Assertions.assertThat(threadMap.setForCurrentThread("hello2"))
+    assertThat(threadMap.setForCurrentThread("hello2"))
         .describedAs("value before the thread entry is changed")
         .isEqualTo(dynamicValue);
 
@@ -201,10 +201,10 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
     long threadId = threadMap.currentThreadId();
     threadMap.put(threadId, null);
     String updated = threadMap.getForCurrentThread();
-    Assertions.assertThat(lost.get())
+    assertThat(lost.get())
         .describedAs("lost count")
         .isEqualTo(1);
-    Assertions.assertThat(updated)
+    assertThat(updated)
         .describedAs("dynamically created thread map value")
         .startsWith("Entry for thread ID")
         .contains("(" + (c1 + 2) + ")");
@@ -217,7 +217,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param val expected value
    */
   private void assertMapEntryEquals(int key, String val) {
-    Assertions.assertThat(referenceMap.get(key))
+    assertThat(referenceMap.get(key))
         .describedAs("map enty of key %d", key)
         .isEqualTo(val);
   }
@@ -227,7 +227,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param key key
    */
   private void assertMapContainsKey(int key) {
-    Assertions.assertThat(referenceMap.containsKey(key))
+    assertThat(referenceMap.containsKey(key))
         .describedAs("map entry of key %d should be present", key)
         .isTrue();
   }
@@ -237,7 +237,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param key key
    */
   private void assertMapDoesNotContainKey(int key) {
-    Assertions.assertThat(referenceMap.containsKey(key))
+    assertThat(referenceMap.containsKey(key))
         .describedAs("map enty of key %d should be absent", key)
         .isFalse();
   }
@@ -247,7 +247,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param size expected size.
    */
   private void assertMapSize(int size) {
-    Assertions.assertThat(referenceMap.size())
+    assertThat(referenceMap.size())
         .describedAs("size of map %s", referenceMap)
         .isEqualTo(size);
   }
@@ -257,7 +257,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param count expected count.
    */
   private void assertPruned(int count) {
-    Assertions.assertThat(referenceMap.prune())
+    assertThat(referenceMap.prune())
         .describedAs("number of entries pruned from map %s", referenceMap)
         .isEqualTo(count);
   }
@@ -267,7 +267,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase {
    * @param count expected count.
    */
   private void assertLostCount(int count) {
-    Assertions.assertThat(lostReferences)
+    assertThat(lostReferences)
         .describedAs("number of entries lost from map %s", referenceMap)
         .hasSize(count);
   }

+ 56 - 39
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java

@@ -19,7 +19,12 @@
 package org.apache.hadoop.util;
 
 import static org.apache.hadoop.test.PlatformAssumptions.assumeWindows;
-import static org.junit.Assert.*;
+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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -30,10 +35,10 @@ import java.io.IOException;
 import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.assertj.core.api.Assertions;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -48,17 +53,17 @@ public class TestWinUtils {
 
   String winutils;
 
-  @Before
+  @BeforeEach
   public void setUp() throws IOException {
     // Not supported on non-Windows platforms
     assumeWindows();
     TEST_DIR.mkdirs();
-    assertTrue("Failed to create Test directory " + TEST_DIR,
-        TEST_DIR.isDirectory() );
+    assertTrue(TEST_DIR.isDirectory(),
+        "Failed to create Test directory " + TEST_DIR);
     winutils = Shell.getWinUtilsPath();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws IOException {
     FileUtil.fullyDelete(TEST_DIR);
   }
@@ -87,7 +92,8 @@ public class TestWinUtils {
     return new String(b);
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testLs() throws IOException {
     requireWinutils();
     final String content = "6bytes";
@@ -117,7 +123,8 @@ public class TestWinUtils {
     assertFalse(testFile.exists());
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testGroups() throws IOException {
     requireWinutils();
     String currentUser = System.getProperty("user.name");
@@ -241,7 +248,8 @@ public class TestWinUtils {
     assertTrue(FileUtil.fullyDelete(a));
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testBasicChmod() throws IOException {
     requireWinutils();
     // - Create a file.
@@ -253,7 +261,7 @@ public class TestWinUtils {
 
     try {
       readFile(a);
-      assertFalse("readFile should have failed!", true);
+      assertFalse(true, "readFile should have failed!");
     } catch (IOException ex) {
       LOG.info("Expected: Failed read from a file with permissions 377");
     }
@@ -294,7 +302,8 @@ public class TestWinUtils {
   }
 
   /** Validate behavior of chmod commands on directories on Windows. */
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testBasicChmodOnDir() throws IOException {
     requireWinutils();
     // Validate that listing a directory with no read permission fails
@@ -306,7 +315,7 @@ public class TestWinUtils {
     // Remove read permissions on directory a
     chmod("300", a);
     String[] files = a.list();
-    assertNull("Listing a directory without read permission should fail", files);
+    assertNull(files, "Listing a directory without read permission should fail");
 
     // restore permissions
     chmod("700", a);
@@ -333,12 +342,13 @@ public class TestWinUtils {
     // Deleting a file will succeed even if write permissions are not present
     // on the parent dir. Check the following link for additional details:
     // http://support.microsoft.com/kb/238018
-    assertTrue("Special behavior: deleting a file will succeed on Windows "
-        + "even if a user does not have write permissions on the parent dir",
-        b.delete());
+    assertTrue(b.delete(),
+        "Special behavior: deleting a file will succeed on Windows "
+        + "even if a user does not have write permissions on the parent dir");
 
-    assertFalse("Renaming a file should fail on the dir where a user does "
-        + "not have write permissions", b.renameTo(new File(a, "d")));
+    assertFalse(b.renameTo(new File(a, "d")),
+        "Renaming a file should fail on the dir where a user does "
+        + "not have write permissions");
 
     // restore permissions
     chmod("700", a);
@@ -372,7 +382,8 @@ public class TestWinUtils {
     chmod("700", a);
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testChmod() throws IOException {
     requireWinutils();
     testChmodInternal("7", "-------rwx");
@@ -407,7 +418,8 @@ public class TestWinUtils {
         StringUtils.toLowerCase(args[3]));
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testChown() throws IOException {
     requireWinutils();
     File a = new File(TEST_DIR, "a");
@@ -433,7 +445,8 @@ public class TestWinUtils {
     assertFalse(a.exists());
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSymlinkRejectsForwardSlashesInLink() throws IOException {
     requireWinutils();
     File newFile = new File(TEST_DIR, "file");
@@ -450,7 +463,8 @@ public class TestWinUtils {
     }
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSymlinkRejectsForwardSlashesInTarget() throws IOException {
     requireWinutils();
     File newFile = new File(TEST_DIR, "file");
@@ -467,7 +481,8 @@ public class TestWinUtils {
     }
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testReadLink() throws IOException {
     requireWinutils();
     // Create TEST_DIR\dir1\file1.txt
@@ -494,12 +509,12 @@ public class TestWinUtils {
     String readLinkOutput = Shell.execCommand(winutils,
         "readlink",
         dirLink.toString());
-    Assertions.assertThat(readLinkOutput).isEqualTo(dir1.toString());
+    assertThat(readLinkOutput).isEqualTo(dir1.toString());
 
     readLinkOutput = Shell.execCommand(winutils,
         "readlink",
         fileLink.toString());
-    Assertions.assertThat(readLinkOutput).isEqualTo(file1.toString());
+    assertThat(readLinkOutput).isEqualTo(file1.toString());
 
     // Try a few invalid inputs and verify we get an ExitCodeException for each.
     //
@@ -509,7 +524,7 @@ public class TestWinUtils {
       Shell.execCommand(winutils, "readlink", "");
       fail("Failed to get Shell.ExitCodeException when reading bad symlink");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
 
     try {
@@ -518,7 +533,7 @@ public class TestWinUtils {
       Shell.execCommand(winutils, "readlink", "ThereIsNoSuchLink");
       fail("Failed to get Shell.ExitCodeException when reading bad symlink");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
 
     try {
@@ -527,7 +542,7 @@ public class TestWinUtils {
       Shell.execCommand(winutils, "readlink", dir1.toString());
       fail("Failed to get Shell.ExitCodeException when reading bad symlink");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
 
     try {
@@ -536,7 +551,7 @@ public class TestWinUtils {
       Shell.execCommand(winutils, "readlink", file1.toString());
       fail("Failed to get Shell.ExitCodeException when reading bad symlink");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
 
     try {
@@ -545,11 +560,12 @@ public class TestWinUtils {
       Shell.execCommand(winutils, "readlink", "a", "b");
       fail("Failed to get Shell.ExitCodeException with bad parameters");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
   }
   
-  @Test(timeout=10000)
+  @Test
+  @Timeout(value = 10)
   public void testTaskCreate() throws IOException {
     requireWinutils();
     File batch = new File(TEST_DIR, "testTaskCreate.cmd");
@@ -568,10 +584,11 @@ public class TestWinUtils {
     
     String outNumber = FileUtils.readFileToString(proof);
 
-    Assertions.assertThat(outNumber).contains(testNumber);
+    assertThat(outNumber).contains(testNumber);
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testTaskCreateWithLimits() throws IOException {
     requireWinutils();
     // Generate a unique job id
@@ -601,7 +618,7 @@ public class TestWinUtils {
           + jobId, "java -Xmx256m -version");
       fail("Failed to get Shell.ExitCodeException with insufficient memory");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1);
+      assertThat(ece.getExitCode()).isEqualTo(1);
     }
 
     // Run tasks with wrong parameters
@@ -612,7 +629,7 @@ public class TestWinUtils {
           "-1", "foo", "job" + jobId, "cmd /c echo job" + jobId);
       fail("Failed to get Shell.ExitCodeException with bad parameters");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1639);
+      assertThat(ece.getExitCode()).isEqualTo(1639);
     }
 
     try {
@@ -621,7 +638,7 @@ public class TestWinUtils {
           "job" + jobId, "cmd /c echo job" + jobId);
       fail("Failed to get Shell.ExitCodeException with bad parameters");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1639);
+      assertThat(ece.getExitCode()).isEqualTo(1639);
     }
 
     try {
@@ -630,7 +647,7 @@ public class TestWinUtils {
           "job" + jobId, "cmd /c echo job" + jobId);
       fail("Failed to get Shell.ExitCodeException with bad parameters");
     } catch (Shell.ExitCodeException ece) {
-      Assertions.assertThat(ece.getExitCode()).isEqualTo(1639);
+      assertThat(ece.getExitCode()).isEqualTo(1639);
     }
   }
 }

+ 61 - 46
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java

@@ -33,37 +33,44 @@ import javax.xml.transform.stream.StreamSource;
 
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 
-import org.assertj.core.api.Assertions;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.helpers.DefaultHandler;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 public class TestXMLUtils extends AbstractHadoopTestBase {
 
   @Test
   public void testSecureDocumentBuilderFactory() throws Exception {
     DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder();
     Document doc = db.parse(new InputSource(new StringReader("<root/>")));
-    Assertions.assertThat(doc).describedAs("parsed document").isNotNull();
+    assertThat(doc).describedAs("parsed document").isNotNull();
   }
 
-  @Test(expected = SAXException.class)
+  @Test
   public void testExternalDtdWithSecureDocumentBuilderFactory() throws Exception {
-    DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder();
-    try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) {
-      Document doc = db.parse(stream);
-    }
+    assertThrows(SAXException.class, () -> {
+      DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder();
+      try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) {
+        Document doc = db.parse(stream);
+      }
+    });
   }
 
-  @Test(expected = SAXException.class)
+  @Test
   public void testEntityDtdWithSecureDocumentBuilderFactory() throws Exception {
-    DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder();
-    try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) {
-      Document doc = db.parse(stream);
-    }
+    assertThrows(SAXException.class, () -> {
+      DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder();
+      try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) {
+        Document doc = db.parse(stream);
+      }
+    });
   }
 
   @Test
@@ -72,20 +79,24 @@ public class TestXMLUtils extends AbstractHadoopTestBase {
     parser.parse(new InputSource(new StringReader("<root/>")), new DefaultHandler());
   }
 
-  @Test(expected = SAXException.class)
+  @Test
   public void testExternalDtdWithSecureSAXParserFactory() throws Exception {
-    SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser();
-    try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) {
-      parser.parse(stream, new DefaultHandler());
-    }
+    assertThrows(SAXException.class, () -> {
+      SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser();
+      try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) {
+        parser.parse(stream, new DefaultHandler());
+      }
+    });
   }
 
-  @Test(expected = SAXException.class)
+  @Test
   public void testEntityDtdWithSecureSAXParserFactory() throws Exception {
-    SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser();
-    try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) {
-      parser.parse(stream, new DefaultHandler());
-    }
+    assertThrows(SAXException.class, () -> {
+      SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser();
+      try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) {
+        parser.parse(stream, new DefaultHandler());
+      }
+    });
   }
 
   @Test
@@ -95,19 +106,21 @@ public class TestXMLUtils extends AbstractHadoopTestBase {
     Document doc = db.parse(new InputSource(new StringReader("<root/>")));
     try (StringWriter stringWriter = new StringWriter()) {
       transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
-      Assertions.assertThat(stringWriter.toString()).contains("<root");
+      assertThat(stringWriter.toString()).contains("<root");
     }
   }
 
-  @Test(expected = TransformerException.class)
+  @Test
   public void testExternalDtdWithSecureTransformerFactory() throws Exception {
-    Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer();
-    try (
-        InputStream stream = getResourceStream("/xml/external-dtd.xml");
-        StringWriter stringWriter = new StringWriter()
-    ) {
-      transformer.transform(new StreamSource(stream), new StreamResult(stringWriter));
-    }
+    assertThrows(TransformerException.class, () -> {
+      Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer();
+      try (
+          InputStream stream = getResourceStream("/xml/external-dtd.xml");
+          StringWriter stringWriter = new StringWriter()
+      ) {
+        transformer.transform(new StreamSource(stream), new StreamResult(stringWriter));
+      }
+    });
   }
 
   @Test
@@ -117,19 +130,21 @@ public class TestXMLUtils extends AbstractHadoopTestBase {
     Document doc = db.parse(new InputSource(new StringReader("<root/>")));
     try (StringWriter stringWriter = new StringWriter()) {
       transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
-      Assertions.assertThat(stringWriter.toString()).contains("<root");
+      assertThat(stringWriter.toString()).contains("<root");
     }
   }
 
-  @Test(expected = TransformerException.class)
+  @Test
   public void testExternalDtdWithSecureSAXTransformerFactory() throws Exception {
-    Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer();
-    try (
-        InputStream stream = getResourceStream("/xml/external-dtd.xml");
-        StringWriter stringWriter = new StringWriter()
-    ) {
-      transformer.transform(new StreamSource(stream), new StreamResult(stringWriter));
-    }
+    assertThrows(TransformerException.class, () -> {
+      Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer();
+      try (
+          InputStream stream = getResourceStream("/xml/external-dtd.xml");
+          StringWriter stringWriter = new StringWriter()
+      ) {
+        transformer.transform(new StreamSource(stream), new StreamResult(stringWriter));
+      }
+    });
   }
 
   @Test
@@ -137,14 +152,14 @@ public class TestXMLUtils extends AbstractHadoopTestBase {
     TransformerFactory factory = TransformerFactory.newInstance();
     AtomicBoolean flag1 = new AtomicBoolean(true);
     XMLUtils.bestEffortSetAttribute(factory, flag1, "unsupportedAttribute false", "abc");
-    Assert.assertFalse("unexpected attribute results in return of false?", flag1.get());
+    assertFalse(flag1.get(), "unexpected attribute results in return of false?");
     AtomicBoolean flag2 = new AtomicBoolean(true);
     XMLUtils.bestEffortSetAttribute(factory, flag2, XMLConstants.ACCESS_EXTERNAL_DTD, "");
-    Assert.assertTrue("expected attribute results in return of true?", flag2.get());
+    assertTrue(flag2.get(), "expected attribute results in return of true?");
     AtomicBoolean flag3 = new AtomicBoolean(false);
     XMLUtils.bestEffortSetAttribute(factory, flag3, XMLConstants.ACCESS_EXTERNAL_DTD, "");
-    Assert.assertFalse("expected attribute results in return of false if input flag is false?",
-            flag3.get());
+    assertFalse(flag3.get(),
+        "expected attribute results in return of false if input flag is false?");
   }
 
   private static InputStream getResourceStream(final String filename) {

+ 6 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java

@@ -17,7 +17,10 @@
  */
 package org.apache.hadoop.util;
 
-import static org.junit.Assert.*;
+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;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -30,7 +33,7 @@ import org.apache.hadoop.util.ZKUtil.BadAclFormatException;
 import org.apache.hadoop.util.ZKUtil.ZKAuthInfo;
 import org.apache.zookeeper.ZooDefs.Perms;
 import org.apache.zookeeper.data.ACL;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.thirdparty.com.google.common.io.Files;
 
@@ -80,7 +83,7 @@ public class TestZKUtil {
     int perms = Perms.ALL;
     int remove = Perms.CREATE;
     int newPerms = ZKUtil.removeSpecificPerms(perms, remove);
-    assertEquals("Removal failed", 0, newPerms & Perms.CREATE);
+    assertEquals(0, newPerms & Perms.CREATE, "Removal failed");
   }
 
   @Test

+ 54 - 54
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java

@@ -18,8 +18,9 @@
 
 package org.apache.hadoop.util.bloom;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 import java.util.AbstractCollection;
@@ -27,7 +28,6 @@ import java.util.Collection;
 import java.util.Iterator;
 import java.util.Random;
 
-import org.junit.Assert;
 import org.apache.hadoop.io.DataInputBuffer;
 import org.apache.hadoop.io.DataOutputBuffer;
 import org.apache.hadoop.util.hash.Hash;
@@ -83,7 +83,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         }
         default: {
           // fail fast with unknown hash error !!!
-          Assert.assertFalse("unknown hash error", true);
+          assertFalse(true, "unknown hash error");
           return ImmutableSet.of();
         }
         }
@@ -134,7 +134,7 @@ public class BloomFilterCommonTester<T extends Filter> {
       return new DynamicBloomFilter(bitSetSize, hashFunctionNumber, hashType, 3);
     } else {
       //fail fast
-      assertFalse("unexpected filterClass", true);
+      assertFalse(true, "unexpected filterClass");
       return null;
     } 
   }
@@ -152,17 +152,17 @@ public class BloomFilterCommonTester<T extends Filter> {
 
         filter.add(keys);
 
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("100".getBytes())));
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("200".getBytes())));
+        assertTrue(filter.membershipTest(new Key("100".getBytes())),
+            " might contain key error ");
+        assertTrue(filter.membershipTest(new Key("200".getBytes())),
+            " might contain key error ");
 
         filter.add(keys.toArray(new Key[] {}));
 
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("100".getBytes())));
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("200".getBytes())));
+        assertTrue(filter.membershipTest(new Key("100".getBytes())),
+            " might contain key error ");
+        assertTrue(filter.membershipTest(new Key("200".getBytes())),
+            " might contain key error ");
 
         filter.add(new AbstractCollection<Key>() {
 
@@ -178,10 +178,10 @@ public class BloomFilterCommonTester<T extends Filter> {
 
         });
 
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("100".getBytes())));
-        assertTrue(" might contain key error ",
-            filter.membershipTest(new Key("200".getBytes())));
+        assertTrue(filter.membershipTest(new Key("100".getBytes())),
+            " might contain key error ");
+        assertTrue(filter.membershipTest(new Key("200".getBytes())),
+            " might contain key error ");
       }
     }),
 
@@ -191,28 +191,28 @@ public class BloomFilterCommonTester<T extends Filter> {
         String line = "werabsdbe";
 
         Key key = new Key(line.getBytes());
-        assertTrue("default key weight error ", key.getWeight() == 1d);
+        assertTrue(key.getWeight() == 1d, "default key weight error ");
 
         key.set(line.getBytes(), 2d);
-        assertTrue(" setted key weight error ", key.getWeight() == 2d);
+        assertTrue(key.getWeight() == 2d, " setted key weight error ");
 
         Key sKey = new Key(line.getBytes(), 2d);
-        assertTrue("equals error", key.equals(sKey));
-        assertTrue("hashcode error", key.hashCode() == sKey.hashCode());
+        assertTrue(key.equals(sKey), "equals error");
+        assertTrue(key.hashCode() == sKey.hashCode(), "hashcode error");
 
         sKey = new Key(line.concat("a").getBytes(), 2d);
-        assertFalse("equals error", key.equals(sKey));
-        assertFalse("hashcode error", key.hashCode() == sKey.hashCode());
+        assertFalse(key.equals(sKey), "equals error");
+        assertFalse(key.hashCode() == sKey.hashCode(), "hashcode error");
 
         sKey = new Key(line.getBytes(), 3d);
-        assertFalse("equals error", key.equals(sKey));
-        assertFalse("hashcode error", key.hashCode() == sKey.hashCode());
+        assertFalse(key.equals(sKey), "equals error");
+        assertFalse(key.hashCode() == sKey.hashCode(), "hashcode error");
 
         key.incrementWeight();
-        assertTrue("weight error", key.getWeight() == 3d);
+        assertTrue(key.getWeight() == 3d, "weight error");
 
         key.incrementWeight(2d);
-        assertTrue("weight error", key.getWeight() == 5d);
+        assertTrue(key.getWeight() == 5d, "weight error");
       }
 
       private void checkOnReadWrite() {
@@ -224,12 +224,12 @@ public class BloomFilterCommonTester<T extends Filter> {
           originKey.write(out);
           in.reset(out.getData(), out.getData().length);
           Key restoredKey = new Key(new byte[] { 0 });
-          assertFalse("checkOnReadWrite equals error", restoredKey.equals(originKey));
+          assertFalse(restoredKey.equals(originKey), "checkOnReadWrite equals error");
           restoredKey.readFields(in);
-          assertTrue("checkOnReadWrite equals error", restoredKey.equals(originKey));
+          assertTrue(restoredKey.equals(originKey), "checkOnReadWrite equals error");
           out.reset();
         } catch (Exception ioe) {
-          Assert.fail("checkOnReadWrite ex error");
+          fail("checkOnReadWrite ex error");
         }
       }
 
@@ -240,7 +240,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           // expected
         } catch (Exception e) {
-          Assert.fail("checkSetOnIAE ex error");
+          fail("checkSetOnIAE ex error");
         }
       }
 
@@ -272,7 +272,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           //
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
         try {
@@ -281,7 +281,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           //
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
         try {
@@ -290,7 +290,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           //
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
         try {
@@ -298,7 +298,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           // expected
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
         try {
@@ -306,7 +306,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (IllegalArgumentException ex) {
           // expected
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
         try {
@@ -316,7 +316,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (UnsupportedOperationException unex) {
           //
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
 
       }
@@ -328,7 +328,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (NullPointerException ex) {
           // expected
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
       }
 
@@ -339,7 +339,7 @@ public class BloomFilterCommonTester<T extends Filter> {
         } catch (NullPointerException ex) {
           // expected
         } catch (Exception e) {
-          Assert.fail("" + e);
+          fail("" + e);
         }
       }
     }),
@@ -357,15 +357,15 @@ public class BloomFilterCommonTester<T extends Filter> {
 
         // check on present even key
         for (int i = 0; i < numInsertions; i += 2) {
-          Assert.assertTrue(" filter might contains " + i,
-              filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+          assertTrue(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+              " filter might contains " + i);
         }
 
         // check on absent odd in event
         for (int i = 1; i < numInsertions; i += 2) {
           if (!falsePositives.contains(i)) {
-            assertFalse(" filter should not contain " + i,
-                filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+            assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+                " filter should not contain " + i);
           }
         }
       }
@@ -402,12 +402,12 @@ public class BloomFilterCommonTester<T extends Filter> {
           tempFilter.readFields(in);
 
           for (Integer slot : list) {
-            assertTrue("read/write mask check filter error on " + slot,
-                filter.membershipTest(new Key(String.valueOf(slot).getBytes())));
+            assertTrue(filter.membershipTest(new Key(String.valueOf(slot).getBytes())),
+                "read/write mask check filter error on " + slot);
           }
 
         } catch (IOException ex) {
-          Assert.fail("error ex !!!" + ex);
+          fail("error ex !!!" + ex);
         }
       }
     }),
@@ -424,8 +424,8 @@ public class BloomFilterCommonTester<T extends Filter> {
           filter.xor(symmetricFilter);
           // check on present all key
           for (int i = 0; i < numInsertions; i++) {
-            Assert.assertFalse(" filter might contains " + i,
-                filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+            assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+                " filter might contains " + i);
           }
 
           // add all even keys
@@ -442,8 +442,8 @@ public class BloomFilterCommonTester<T extends Filter> {
           // 1 xor 1 -> 0
           // check on absent all key
           for (int i = 0; i < numInsertions; i++) {
-            Assert.assertFalse(" filter might not contains " + i,
-                filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+            assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+                " filter might not contains " + i);
           }
 
         } catch (UnsupportedOperationException ex) {
@@ -478,8 +478,8 @@ public class BloomFilterCommonTester<T extends Filter> {
 
         for (int i = 0; i < numInsertions; i++) {
           if (i >= startIntersection && i <= endIntersection) {
-            Assert.assertTrue(" filter might contains " + i,
-                filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+            assertTrue(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+                " filter might contains " + i);
           }
         }        
       }
@@ -508,8 +508,8 @@ public class BloomFilterCommonTester<T extends Filter> {
 
         // check on present all key
         for (int i = 0; i < numInsertions; i++) {
-          Assert.assertTrue(" filter might contains " + i,
-              filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+          assertTrue(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+              " filter might contains " + i);
         }        
       }
     });

+ 16 - 23
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java

@@ -18,9 +18,10 @@
 
 package org.apache.hadoop.util.bloom;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.util.AbstractCollection;
 import java.util.BitSet;
@@ -28,8 +29,7 @@ import java.util.Iterator;
 
 import org.apache.hadoop.util.bloom.BloomFilterCommonTester.BloomFilterTestStrategy;
 import org.apache.hadoop.util.hash.Hash;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableList;
 import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableMap;
@@ -112,24 +112,18 @@ public class TestBloomFilters {
     Key key = new Key(new byte[] { 48, 48 });
 
     filter.add(key);
-    assertTrue("CountingBloomFilter.membership error ",
-        filter.membershipTest(key));
-    assertTrue("CountingBloomFilter.approximateCount error",
-        filter.approximateCount(key) == 1);
+    assertTrue(filter.membershipTest(key), "CountingBloomFilter.membership error ");
+    assertTrue(filter.approximateCount(key) == 1, "CountingBloomFilter.approximateCount error");
 
     filter.add(key);
-    assertTrue("CountingBloomFilter.approximateCount error",
-        filter.approximateCount(key) == 2);
+    assertTrue(filter.approximateCount(key) == 2, "CountingBloomFilter.approximateCount error");
 
     filter.delete(key);
-    assertTrue("CountingBloomFilter.membership error ",
-        filter.membershipTest(key));
+    assertTrue(filter.membershipTest(key), "CountingBloomFilter.membership error ");
 
     filter.delete(key);
-    assertFalse("CountingBloomFilter.membership error ",
-        filter.membershipTest(key));
-    assertTrue("CountingBloomFilter.approximateCount error",
-        filter.approximateCount(key) == 0);
+    assertFalse(filter.membershipTest(key), "CountingBloomFilter.membership error ");
+    assertTrue(filter.approximateCount(key) == 0, "CountingBloomFilter.approximateCount error");
 
     BloomFilterCommonTester.of(hashId, numInsertions)
         .withFilterInstance(filter)
@@ -186,8 +180,7 @@ public class TestBloomFilters {
         .get(hashId);
 
     if (falsePositives == null)
-      Assert.fail(String.format("false positives for hash %d not founded",
-          hashId));
+      fail(String.format("false positives for hash %d not founded", hashId));
 
     filter.addFalsePositive(falsePositives);
 
@@ -200,8 +193,8 @@ public class TestBloomFilters {
     }
 
     for (int i = 1 - digits.getStart(); i < numInsertions; i += 2) {
-      assertFalse(" testRetouchedBloomFilterAddFalsePositive error " + i,
-          filter.membershipTest(new Key(Integer.toString(i).getBytes())));
+      assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())),
+          " testRetouchedBloomFilterAddFalsePositive error " + i);
     }
   }
 
@@ -257,7 +250,7 @@ public class TestBloomFilters {
     bf.bits = BitSet.valueOf(new byte[] { (byte) 0x95 });
     BitSet origBitSet = (BitSet) bf.bits.clone();
     bf.not();
-    assertFalse("BloomFilter#not should have inverted all bits",
-                bf.bits.intersects(origBitSet));
+    assertFalse(bf.bits.intersects(origBitSet),
+        "BloomFilter#not should have inverted all bits");
   }
 }

+ 40 - 35
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java

@@ -23,9 +23,9 @@ import java.util.HashMap;
 import java.util.Map;
 
 import org.apache.hadoop.security.SecurityUtil;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import org.apache.curator.test.InstanceSpec;
 import org.apache.curator.test.TestingServer;
@@ -38,7 +38,7 @@ import org.apache.zookeeper.common.ClientX509Util;
 import org.apache.zookeeper.server.NettyServerCnxnFactory;
 
 import static org.apache.hadoop.fs.FileContext.LOG;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 /**
  * Test the manager for ZooKeeper Curator when SSL/TLS is enabled for the ZK server-client
@@ -59,7 +59,7 @@ public class TestSecureZKCuratorManager {
   public static final int ELECTION_PORT = -1;
   public static final int QUORUM_PORT = -1;
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     // inject values to the ZK configuration file for secure connection
     Map<String, Object> customConfiguration = new HashMap<>();
@@ -132,7 +132,7 @@ public class TestSecureZKCuratorManager {
     return conf;
   }
 
-  @After
+  @AfterEach
   public void teardown() throws Exception {
     this.curator.close();
     if (this.server != null) {
@@ -159,21 +159,26 @@ public class TestSecureZKCuratorManager {
       String truststoreLocation, String truststorePassword, ZooKeeper zk) {
     try (ClientX509Util x509Util = new ClientX509Util()) {
       //testing if custom values are set properly
-      assertEquals("Validate that expected clientConfig is set in ZK config", keystoreLocation,
-          zk.getClientConfig().getProperty(x509Util.getSslKeystoreLocationProperty()));
-      assertEquals("Validate that expected clientConfig is set in ZK config", keystorePassword,
-          zk.getClientConfig().getProperty(x509Util.getSslKeystorePasswdProperty()));
-      assertEquals("Validate that expected clientConfig is set in ZK config", truststoreLocation,
-          zk.getClientConfig().getProperty(x509Util.getSslTruststoreLocationProperty()));
-      assertEquals("Validate that expected clientConfig is set in ZK config", truststorePassword,
-          zk.getClientConfig().getProperty(x509Util.getSslTruststorePasswdProperty()));
+      assertEquals(keystoreLocation,
+           zk.getClientConfig().getProperty(x509Util.getSslKeystoreLocationProperty()),
+          "Validate that expected clientConfig is set in ZK config");
+      assertEquals(keystorePassword,
+          zk.getClientConfig().getProperty(x509Util.getSslKeystorePasswdProperty()),
+          "Validate that expected clientConfig is set in ZK config");
+      assertEquals(truststoreLocation,
+          zk.getClientConfig().getProperty(x509Util.getSslTruststoreLocationProperty()),
+          "Validate that expected clientConfig is set in ZK config");
+      assertEquals(truststorePassword,
+          zk.getClientConfig().getProperty(x509Util.getSslTruststorePasswdProperty()),
+          "Validate that expected clientConfig is set in ZK config");
     }
     //testing if constant values hardcoded into the code are set properly
-    assertEquals("Validate that expected clientConfig is set in ZK config", Boolean.TRUE.toString(),
-        zk.getClientConfig().getProperty(ZKClientConfig.SECURE_CLIENT));
-    assertEquals("Validate that expected clientConfig is set in ZK config",
-        ClientCnxnSocketNetty.class.getCanonicalName(),
-        zk.getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET));
+    assertEquals(Boolean.TRUE.toString(),
+        zk.getClientConfig().getProperty(ZKClientConfig.SECURE_CLIENT),
+        "Validate that expected clientConfig is set in ZK config");
+    assertEquals(ClientCnxnSocketNetty.class.getCanonicalName(),
+        zk.getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET),
+        "Validate that expected clientConfig is set in ZK config");
   }
 
   @Test
@@ -187,14 +192,14 @@ public class TestSecureZKCuratorManager {
     SecurityUtil.TruststoreKeystore truststoreKeystore =
         new SecurityUtil.TruststoreKeystore(conf);
 
-    assertEquals("Validate that null value is converted to empty string.", "",
-        truststoreKeystore.getKeystoreLocation());
-    assertEquals("Validate that null value is converted to empty string.", "",
-        truststoreKeystore.getKeystorePassword());
-    assertEquals("Validate that null value is converted to empty string.", "",
-        truststoreKeystore.getTruststoreLocation());
-    assertEquals("Validate that null value is converted to empty string.", "",
-        truststoreKeystore.getTruststorePassword());
+    assertEquals("", truststoreKeystore.getKeystoreLocation(),
+        "Validate that null value is converted to empty string.");
+    assertEquals("", truststoreKeystore.getKeystorePassword(),
+        "Validate that null value is converted to empty string.");
+    assertEquals("", truststoreKeystore.getTruststoreLocation(),
+        "Validate that null value is converted to empty string.");
+    assertEquals("", truststoreKeystore.getTruststorePassword(),
+        "Validate that null value is converted to empty string.");
 
     //Validate that non-null values will remain intact
     conf.set(CommonConfigurationKeys.ZK_SSL_KEYSTORE_LOCATION, "/keystore.jks");
@@ -203,13 +208,13 @@ public class TestSecureZKCuratorManager {
     conf.set(CommonConfigurationKeys.ZK_SSL_TRUSTSTORE_PASSWORD, "truststorePassword");
     SecurityUtil.TruststoreKeystore truststoreKeystore1 =
         new SecurityUtil.TruststoreKeystore(conf);
-    assertEquals("Validate that non-null value kept intact.", "/keystore.jks",
-        truststoreKeystore1.getKeystoreLocation());
-    assertEquals("Validate that null value is converted to empty string.", "keystorePassword",
-        truststoreKeystore1.getKeystorePassword());
-    assertEquals("Validate that null value is converted to empty string.", "/truststore.jks",
-        truststoreKeystore1.getTruststoreLocation());
-    assertEquals("Validate that null value is converted to empty string.", "truststorePassword",
-        truststoreKeystore1.getTruststorePassword());
+    assertEquals("/keystore.jks", truststoreKeystore1.getKeystoreLocation(),
+        "Validate that non-null value kept intact.");
+    assertEquals("keystorePassword", truststoreKeystore1.getKeystorePassword(),
+        "Validate that null value is converted to empty string.");
+    assertEquals("/truststore.jks", truststoreKeystore1.getTruststoreLocation(),
+        "Validate that null value is converted to empty string.");
+    assertEquals("truststorePassword", truststoreKeystore1.getTruststorePassword(),
+        "Validate that null value is converted to empty string.");
   }
 }

+ 16 - 15
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java

@@ -17,10 +17,10 @@
  */
 package org.apache.hadoop.util.curator;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
@@ -43,9 +43,9 @@ import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Stat;
-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;
 
 /**
  * Test the manager for ZooKeeper Curator.
@@ -55,7 +55,7 @@ public class TestZKCuratorManager {
   private TestingServer server;
   private ZKCuratorManager curator;
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     this.server = new TestingServer();
 
@@ -66,7 +66,7 @@ public class TestZKCuratorManager {
     this.curator.start(zkHostPort);
   }
 
-  @After
+  @AfterEach
   public void teardown() throws Exception {
     this.curator.close();
     if (this.server != null) {
@@ -231,14 +231,15 @@ public class TestZKCuratorManager {
 
   private void validateJaasConfiguration(String clientConfig, String principal, String keytab,
       ZooKeeper zk) {
-    assertEquals("Validate that expected clientConfig is set in ZK config", clientConfig,
-        zk.getClientConfig().getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY));
+    assertEquals(clientConfig,
+        zk.getClientConfig().getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY),
+        "Validate that expected clientConfig is set in ZK config");
 
     AppConfigurationEntry[] entries = javax.security.auth.login.Configuration.getConfiguration()
         .getAppConfigurationEntry(clientConfig);
-    assertEquals("Validate that expected principal is set in Jaas config", principal,
-        entries[0].getOptions().get("principal"));
-    assertEquals("Validate that expected keytab is set in Jaas config", keytab,
-        entries[0].getOptions().get("keyTab"));
+    assertEquals(principal, entries[0].getOptions().get("principal"),
+        "Validate that expected principal is set in Jaas config");
+    assertEquals(keytab, entries[0].getOptions().get("keyTab"),
+        "Validate that expected keytab is set in Jaas config");
   }
 }

+ 16 - 15
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java

@@ -21,12 +21,14 @@ package org.apache.hadoop.util.dynamic;
 
 import java.util.concurrent.Callable;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 
 import static org.apache.hadoop.test.LambdaTestUtils.intercept;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Derived from {@code org.apache.parquet.util} test suites.
@@ -76,8 +78,8 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
         .buildChecked();
 
     Concatenator dashCat = sepCtor.newInstanceChecked("-");
-    Assert.assertEquals("Should construct with the 1-arg version",
-        "a-b", dashCat.concat("a", "b"));
+    assertEquals("a-b", dashCat.concat("a", "b"),
+        "Should construct with the 1-arg version");
 
     intercept(IllegalArgumentException.class, () ->
         sepCtor.newInstanceChecked("/", "-"));
@@ -92,8 +94,8 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
         .buildChecked();
 
     Concatenator cat = defaultCtor.newInstanceChecked();
-    Assert.assertEquals("Should construct with the no-arg version",
-        "ab", cat.concat("a", "b"));
+    assertEquals("ab", cat.concat("a", "b"),
+        "Should construct with the no-arg version");
   }
 
   @Test
@@ -116,7 +118,7 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
         .impl(Concatenator.class.getName(), String.class)
         .buildChecked();
 
-    Assert.assertNotNull("Should find 1-arg constructor", sepCtor.newInstance("-"));
+    assertNotNull(sepCtor.newInstance("-"), "Should find 1-arg constructor");
   }
 
   @Test
@@ -130,12 +132,12 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
         .hiddenImpl(Concatenator.class.getName(), char.class)
         .buildChecked();
 
-    Assert.assertNotNull("Should find hidden ctor with hiddenImpl", sepCtor);
+    assertNotNull(sepCtor, "Should find hidden ctor with hiddenImpl");
 
     Concatenator slashCat = sepCtor.newInstanceChecked('/');
 
-    Assert.assertEquals("Should use separator /",
-        "a/b", slashCat.concat("a", "b"));
+    assertEquals("a/b", slashCat.concat("a", "b"),
+        "Should use separator /");
   }
 
   @Test
@@ -144,7 +146,7 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
         .impl(Concatenator.class.getName())
         .buildChecked();
 
-    Assert.assertTrue("Should always be static", ctor.isStatic());
+    assertTrue(ctor.isStatic(), "Should always be static");
 
     intercept(IllegalStateException.class, () ->
         ctor.bind(null));
@@ -162,9 +164,8 @@ public class TestDynConstructors extends AbstractHadoopTestBase {
     intercept(IllegalArgumentException.class, () ->
         ctor.invoke("a"));
 
-    Assert.assertNotNull("Should allow invokeChecked(null, ...)",
-        ctor.invokeChecked(null));
-    Assert.assertNotNull("Should allow invoke(null, ...)",
-        ctor.invoke(null));
+    assertNotNull(ctor.invokeChecked(null),
+        "Should allow invokeChecked(null, ...)");
+    assertNotNull(ctor.invoke(null), "Should allow invoke(null, ...)");
   }
 }

+ 57 - 60
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java

@@ -21,12 +21,16 @@ package org.apache.hadoop.util.dynamic;
 
 import java.util.concurrent.Callable;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 
 import static org.apache.hadoop.test.LambdaTestUtils.intercept;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Copied from {@code org.apache.parquet.util} test suites.
@@ -78,11 +82,11 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, String.class, String.class, String.class)
         .buildChecked();
 
-    Assert.assertEquals("Should call the 2-arg version successfully",
-        "a-b", cat2.invoke(obj, "a", "b"));
+    assertEquals("a-b", cat2.invoke(obj, "a", "b"),
+        "Should call the 2-arg version successfully");
 
-    Assert.assertEquals("Should ignore extra arguments",
-        "a-b", cat2.invoke(obj, "a", "b", "c"));
+    assertEquals("a-b", cat2.invoke(obj, "a", "b", "c"),
+        "Should ignore extra arguments");
 
     DynMethods.UnboundMethod cat3 = new DynMethods.Builder("concat")
         .impl("not.a.RealClass", String.class, String.class)
@@ -90,11 +94,11 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, String.class, String.class)
         .build();
 
-    Assert.assertEquals("Should call the 3-arg version successfully",
-        "a-b-c", cat3.invoke(obj, "a", "b", "c"));
+    assertEquals("a-b-c", cat3.invoke(obj, "a", "b", "c"),
+        "Should call the 3-arg version successfully");
 
-    Assert.assertEquals("Should call the 3-arg version null padding",
-        "a-b-null", cat3.invoke(obj, "a", "b"));
+    assertEquals("a-b-null", cat3.invoke(obj, "a", "b"),
+        "Should call the 3-arg version null padding");
   }
 
   @Test
@@ -103,14 +107,14 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, String[].class)
         .buildChecked();
 
-    Assert.assertEquals("Should use the varargs version", "abcde",
-        cat.invokeChecked(
-            new Concatenator(),
-            (Object) new String[]{"a", "b", "c", "d", "e"}));
+    assertEquals("abcde",
+        cat.invokeChecked(new Concatenator(), (Object) new String[]{"a", "b", "c", "d", "e"}),
+        "Should use the varargs version");
 
-    Assert.assertEquals("Should use the varargs version", "abcde",
+    assertEquals("abcde",
         cat.bind(new Concatenator())
-            .invokeChecked((Object) new String[]{"a", "b", "c", "d", "e"}));
+        .invokeChecked((Object) new String[]{"a", "b", "c", "d", "e"}),
+        "Should use the varargs version");
   }
 
   @Test
@@ -151,8 +155,8 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, "concat", String.class, String.class)
         .buildChecked();
 
-    Assert.assertEquals("Should find 2-arg concat method",
-        "a-b", cat.invoke(obj, "a", "b"));
+    assertEquals("a-b", cat.invoke(obj, "a", "b"),
+        "Should find 2-arg concat method");
   }
 
   @Test
@@ -162,8 +166,8 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class.getName(), String.class, String.class)
         .buildChecked();
 
-    Assert.assertEquals("Should find 2-arg concat method",
-        "a-b", cat.invoke(obj, "a", "b"));
+    assertEquals("a-b", cat.invoke(obj, "a", "b"),
+        "Should find 2-arg concat method");
   }
 
   @Test
@@ -179,13 +183,12 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .hiddenImpl(Concatenator.class, String.class)
         .buildChecked();
 
-    Assert.assertNotNull("Should find hidden method with hiddenImpl",
-        changeSep);
+    assertNotNull(changeSep, "Should find hidden method with hiddenImpl");
 
     changeSep.invokeChecked(obj, "/");
 
-    Assert.assertEquals("Should use separator / instead of -",
-        "a/b", obj.concat("a", "b"));
+    assertEquals("a/b", obj.concat("a", "b"),
+        "Should use separator / instead of -");
   }
 
   @Test
@@ -198,17 +201,17 @@ public class TestDynMethods extends AbstractHadoopTestBase {
     DynMethods.BoundMethod dashCat = cat.bind(new Concatenator("-"));
     DynMethods.BoundMethod underCat = cat.bind(new Concatenator("_"));
 
-    Assert.assertEquals("Should use '-' object without passing",
-        "a-b", dashCat.invoke("a", "b"));
-    Assert.assertEquals("Should use '_' object without passing",
-        "a_b", underCat.invoke("a", "b"));
+    assertEquals("a-b", dashCat.invoke("a", "b"),
+        "Should use '-' object without passing");
+    assertEquals("a_b", underCat.invoke("a", "b"),
+        "Should use '_' object without passing");
 
     DynMethods.BoundMethod slashCat = new DynMethods.Builder("concat")
         .impl(Concatenator.class, String.class, String.class)
         .buildChecked(new Concatenator("/"));
 
-    Assert.assertEquals("Should use bound object from builder without passing",
-        "a/b", slashCat.invoke("a", "b"));
+    assertEquals("a/b", slashCat.invoke("a", "b"),
+        "Should use bound object from builder without passing");
   }
 
   @Test
@@ -223,7 +226,7 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         builder.build(new Concatenator()));
 
     final DynMethods.UnboundMethod staticCat = builder.buildChecked();
-    Assert.assertTrue("Should be static", staticCat.isStatic());
+    assertTrue(staticCat.isStatic(), "Should be static");
 
     intercept(IllegalStateException.class, () ->
         staticCat.bind(new Concatenator()));
@@ -235,9 +238,9 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, String[].class)
         .buildStaticChecked();
 
-    Assert.assertEquals("Should call varargs static method cat(String...)",
-        "abcde", staticCat.invokeChecked(
-            (Object) new String[]{"a", "b", "c", "d", "e"}));
+    assertEquals("abcde", staticCat.invokeChecked(
+        (Object) new String[]{"a", "b", "c", "d", "e"}),
+        "Should call varargs static method cat(String...)");
   }
 
   @Test
@@ -250,8 +253,8 @@ public class TestDynMethods extends AbstractHadoopTestBase {
     intercept(IllegalStateException.class, builder::buildStaticChecked);
 
     final DynMethods.UnboundMethod cat2 = builder.buildChecked();
-    Assert.assertFalse("concat(String,String) should not be static",
-        cat2.isStatic());
+    assertFalse(cat2.isStatic(),
+        "concat(String,String) should not be static");
 
     intercept(IllegalStateException.class, cat2::asStatic);
   }
@@ -263,12 +266,11 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .impl(Concatenator.class, String.class);
 
     DynMethods.UnboundMethod newConcatenator = builder.buildChecked();
-    Assert.assertTrue("Should find constructor implementation",
-        newConcatenator instanceof DynConstructors.Ctor);
-    Assert.assertTrue("Constructor should be a static method",
-        newConcatenator.isStatic());
-    Assert.assertFalse("Constructor should not be NOOP",
-        newConcatenator.isNoop());
+    assertTrue(newConcatenator instanceof DynConstructors.Ctor,
+        "Should find constructor implementation");
+    assertTrue(newConcatenator.isStatic(),
+        "Constructor should be a static method");
+    assertFalse(newConcatenator.isNoop(), "Constructor should not be NOOP");
 
     // constructors cannot be bound
     intercept(IllegalStateException.class, () ->
@@ -277,12 +279,12 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         builder.build(new Concatenator()));
 
     Concatenator concatenator = newConcatenator.asStatic().invoke("*");
-    Assert.assertEquals("Should function as a concatenator",
-        "a*b", concatenator.concat("a", "b"));
+    assertEquals("a*b", concatenator.concat("a", "b"),
+        "Should function as a concatenator");
 
     concatenator = newConcatenator.asStatic().invokeChecked("@");
-    Assert.assertEquals("Should function as a concatenator",
-        "a@b", concatenator.concat("a", "b"));
+    assertEquals("a@b", concatenator.concat("a", "b"),
+        "Should function as a concatenator");
   }
 
   @Test
@@ -292,8 +294,8 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .ctorImpl(Concatenator.class, String.class)
         .buildChecked();
 
-    Assert.assertFalse("Should find factory method before constructor method",
-        newConcatenator instanceof DynConstructors.Ctor);
+    assertFalse(newConcatenator instanceof DynConstructors.Ctor,
+        "Should find factory method before constructor method");
   }
 
   @Test
@@ -304,17 +306,12 @@ public class TestDynMethods extends AbstractHadoopTestBase {
         .orNoop()
         .buildChecked();
 
-    Assert.assertTrue("No implementation found, should return NOOP",
-        noop.isNoop());
-    Assert.assertNull("NOOP should always return null",
-        noop.invoke(new Concatenator(), "a"));
-    Assert.assertNull("NOOP can be called with null",
-        noop.invoke(null, "a"));
-    Assert.assertNull("NOOP can be bound",
-        noop.bind(new Concatenator()).invoke("a"));
-    Assert.assertNull("NOOP can be bound to null",
-        noop.bind(null).invoke("a"));
-    Assert.assertNull("NOOP can be static",
-        noop.asStatic().invoke("a"));
+    assertTrue(noop.isNoop(), "No implementation found, should return NOOP");
+    assertNull(noop.invoke(new Concatenator(), "a"),
+        "NOOP should always return null");
+    assertNull(noop.invoke(null, "a"), "NOOP can be called with null");
+    assertNull(noop.bind(new Concatenator()).invoke("a"), "NOOP can be bound");
+    assertNull(noop.bind(null).invoke("a"), "NOOP can be bound to null");
+    assertNull(noop.asStatic().invoke("a"), "NOOP can be static");
   }
 }

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java

@@ -24,7 +24,7 @@ import java.io.UncheckedIOException;
 import java.util.function.Function;
 
 import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java

@@ -24,7 +24,7 @@ import java.net.UnknownHostException;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.test.AbstractHadoopTestBase;
 

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java

@@ -26,7 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.hadoop.util.Preconditions;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 27 - 34
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java

@@ -17,9 +17,10 @@
  */
 package org.apache.hadoop.util.hash;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestHash {
   static final String LINE = "34563@45kjkksdf/ljfdb9d8fbusd*89uggjsk<dfgjsdfh@sddc2q3esc";
@@ -27,63 +28,55 @@ public class TestHash {
   @Test
   public void testHash() {
     int iterations = 30;
-    assertTrue("testHash jenkins error !!!",
-        Hash.JENKINS_HASH == Hash.parseHashType("jenkins"));
-    assertTrue("testHash murmur error !!!",
-        Hash.MURMUR_HASH == Hash.parseHashType("murmur"));
-    assertTrue("testHash undefined",
-        Hash.INVALID_HASH == Hash.parseHashType("undefined"));
+    assertTrue(Hash.JENKINS_HASH == Hash.parseHashType("jenkins"),
+        "testHash jenkins error !!!");
+    assertTrue(Hash.MURMUR_HASH == Hash.parseHashType("murmur"),
+        "testHash murmur error !!!");
+    assertTrue(Hash.INVALID_HASH == Hash.parseHashType("undefined"), "testHash undefined");
 
     Configuration cfg = new Configuration();
     cfg.set("hadoop.util.hash.type", "murmur");
-    assertTrue("testHash", MurmurHash.getInstance() == Hash.getInstance(cfg));
+    assertTrue(MurmurHash.getInstance() == Hash.getInstance(cfg), "testHash");
 
     cfg = new Configuration();
     cfg.set("hadoop.util.hash.type", "jenkins");
-    assertTrue("testHash jenkins configuration error !!!",
-        JenkinsHash.getInstance() == Hash.getInstance(cfg));
+    assertTrue(JenkinsHash.getInstance() == Hash.getInstance(cfg),
+        "testHash jenkins configuration error !!!");
 
     cfg = new Configuration();
-    assertTrue("testHash undefine configuration error !!!",
-        MurmurHash.getInstance() == Hash.getInstance(cfg));
+    assertTrue(MurmurHash.getInstance() == Hash.getInstance(cfg),
+        "testHash undefine configuration error !!!");
 
-    assertTrue("testHash error jenkin getInstance !!!",
-        JenkinsHash.getInstance() == Hash.getInstance(Hash.JENKINS_HASH));
-    assertTrue("testHash error murmur getInstance !!!",
-        MurmurHash.getInstance() == Hash.getInstance(Hash.MURMUR_HASH));
+    assertTrue(JenkinsHash.getInstance() == Hash.getInstance(Hash.JENKINS_HASH),
+        "testHash error jenkin getInstance !!!");
+    assertTrue(MurmurHash.getInstance() == Hash.getInstance(Hash.MURMUR_HASH),
+        "testHash error murmur getInstance !!!");
 
-    assertNull("testHash error invalid getInstance !!!",
-        Hash.getInstance(Hash.INVALID_HASH));
+    assertNull(Hash.getInstance(Hash.INVALID_HASH),
+        "testHash error invalid getInstance !!!");
 
     int murmurHash = Hash.getInstance(Hash.MURMUR_HASH).hash(LINE.getBytes());
     for (int i = 0; i < iterations; i++) {
-      assertTrue("multiple evaluation murmur hash error !!!",
-          murmurHash == Hash.getInstance(Hash.MURMUR_HASH)
-              .hash(LINE.getBytes()));
+      assertTrue(murmurHash == Hash.getInstance(Hash.MURMUR_HASH)
+          .hash(LINE.getBytes()), "multiple evaluation murmur hash error !!!");
     }
 
     murmurHash = Hash.getInstance(Hash.MURMUR_HASH).hash(LINE.getBytes(), 67);
     for (int i = 0; i < iterations; i++) {
-      assertTrue(
-          "multiple evaluation murmur hash error !!!",
-          murmurHash == Hash.getInstance(Hash.MURMUR_HASH).hash(
-              LINE.getBytes(), 67));
+      assertTrue(murmurHash == Hash.getInstance(Hash.MURMUR_HASH).hash(
+          LINE.getBytes(), 67), "multiple evaluation murmur hash error !!!");
     }
 
     int jenkinsHash = Hash.getInstance(Hash.JENKINS_HASH).hash(LINE.getBytes());
     for (int i = 0; i < iterations; i++) {
-      assertTrue(
-          "multiple evaluation jenkins hash error !!!",
-          jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash(
-              LINE.getBytes()));
+      assertTrue(jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash(
+          LINE.getBytes()), "multiple evaluation jenkins hash error !!!");
     }
 
     jenkinsHash = Hash.getInstance(Hash.JENKINS_HASH).hash(LINE.getBytes(), 67);
     for (int i = 0; i < iterations; i++) {
-      assertTrue(
-          "multiple evaluation jenkins hash error !!!",
-          jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash(
-              LINE.getBytes(), 67));
+      assertTrue(jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash(
+          LINE.getBytes(), 67), "multiple evaluation jenkins hash error !!!");
     }   
   } 
 }