From c61d50def2edc2c040fe8111ddc95a4979a9ae6f Mon Sep 17 00:00:00 2001 From: fanshilun Date: Thu, 6 Feb 2025 08:26:37 +0800 Subject: [PATCH 1/5] HADOOP-19415. [JDK17] Upgrade JUnit from 4 to 5 in hadoop-common Part5. --- .../util/TestApplicationClassLoader.java | 32 ++--- .../hadoop/util/TestAsyncDiskService.java | 8 +- .../hadoop/util/TestAutoCloseableLock.java | 8 +- .../hadoop/util/TestBasicDiskValidator.java | 4 +- .../hadoop/util/TestCacheableIPList.java | 68 +++++------ .../hadoop/util/TestChunkedArrayList.java | 48 ++++---- .../org/apache/hadoop/util/TestClassUtil.java | 9 +- .../org/apache/hadoop/util/TestClasspath.java | 12 +- .../org/apache/hadoop/util/TestConfTest.java | 4 +- .../hadoop/util/TestConfigurationHelper.java | 2 +- .../hadoop/util/TestCpuTimeTracker.java | 16 +-- .../apache/hadoop/util/TestCrcComposer.java | 8 +- .../org/apache/hadoop/util/TestCrcUtil.java | 12 +- .../apache/hadoop/util/TestDataChecksum.java | 4 +- .../hadoop/util/TestDirectBufferPool.java | 8 +- .../apache/hadoop/util/TestDiskChecker.java | 59 +++++---- .../util/TestDiskCheckerWithDiskIo.java | 33 ++--- .../hadoop/util/TestDiskValidatorFactory.java | 23 ++-- .../apache/hadoop/util/TestDurationInfo.java | 24 ++-- .../org/apache/hadoop/util/TestExitUtil.java | 98 +++++++-------- .../hadoop/util/TestFastNumberFormat.java | 12 +- .../hadoop/util/TestFileBasedIPList.java | 96 +++++++-------- .../org/apache/hadoop/util/TestFindClass.java | 6 +- .../java/org/apache/hadoop/util/TestGSet.java | 64 +++++----- .../hadoop/util/TestGenericOptionsParser.java | 48 ++++---- .../apache/hadoop/util/TestGenericsUtil.java | 26 ++-- .../hadoop/util/TestHostsFileReader.java | 61 +++++----- .../hadoop/util/TestHttpExceptionUtils.java | 20 ++-- .../hadoop/util/TestIdentityHashStore.java | 60 +++++----- .../apache/hadoop/util/TestIndexedSort.java | 40 +++---- .../hadoop/util/TestInstrumentedLock.java | 17 ++- .../util/TestInstrumentedReadWriteLock.java | 27 +++-- .../org/apache/hadoop/util/TestJarFinder.java | 12 +- .../hadoop/util/TestLightWeightCache.java | 30 ++--- .../hadoop/util/TestLightWeightGSet.java | 15 ++- .../util/TestLightWeightResizableGSet.java | 9 +- .../apache/hadoop/util/TestLineReader.java | 26 ++-- .../org/apache/hadoop/util/TestLists.java | 61 +++++----- .../apache/hadoop/util/TestMachineList.java | 25 ++-- .../hadoop/util/TestNativeCodeLoader.java | 4 +- .../apache/hadoop/util/TestNativeCrc32.java | 12 +- .../hadoop/util/TestNativeLibraryChecker.java | 4 +- .../org/apache/hadoop/util/TestOptions.java | 20 ++-- .../apache/hadoop/util/TestPreconditions.java | 2 +- .../org/apache/hadoop/util/TestProgress.java | 14 +-- .../org/apache/hadoop/util/TestProtoUtil.java | 6 +- .../apache/hadoop/util/TestPureJavaCrc32.java | 6 +- .../hadoop/util/TestPureJavaCrc32C.java | 6 +- .../util/TestReadWriteDiskValidator.java | 32 ++--- .../hadoop/util/TestReflectionUtils.java | 18 +-- .../org/apache/hadoop/util/TestRunJar.java | 50 ++++---- .../org/apache/hadoop/util/TestShell.java | 31 +++-- .../hadoop/util/TestShutdownHookManager.java | 86 +++++++------ .../util/TestShutdownThreadsHelper.java | 18 +-- .../apache/hadoop/util/TestSignalLogger.java | 10 +- .../org/apache/hadoop/util/TestStopWatch.java | 18 +-- .../hadoop/util/TestStringInterner.java | 4 +- .../apache/hadoop/util/TestStringUtils.java | 83 +++++++------ .../apache/hadoop/util/TestSysInfoLinux.java | 6 +- .../hadoop/util/TestSysInfoWindows.java | 17 ++- .../java/org/apache/hadoop/util/TestTime.java | 4 +- .../apache/hadoop/util/TestVersionUtil.java | 4 +- .../hadoop/util/TestWeakReferenceMap.java | 6 +- .../org/apache/hadoop/util/TestWinUtils.java | 64 ++++++---- .../org/apache/hadoop/util/TestXMLUtils.java | 106 +++++++++------- .../org/apache/hadoop/util/TestZKUtil.java | 6 +- .../util/bloom/BloomFilterCommonTester.java | 108 ++++++++--------- .../hadoop/util/bloom/TestBloomFilters.java | 44 +++---- .../curator/TestSecureZKCuratorManager.java | 34 +++--- .../util/curator/TestZKCuratorManager.java | 30 ++--- .../util/dynamic/TestDynConstructors.java | 24 ++-- .../hadoop/util/dynamic/TestDynMethods.java | 113 +++++++++--------- .../util/functional/TestFunctionalIO.java | 2 +- .../util/functional/TestLazyReferences.java | 2 +- .../util/functional/TestRemoteIterators.java | 2 +- .../org/apache/hadoop/util/hash/TestHash.java | 62 +++++----- 76 files changed, 1150 insertions(+), 1043 deletions(-) diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java index 803e428373ba5..e0b439bbd1d50 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java @@ -20,11 +20,11 @@ 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 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 void setUp() { @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 void testGetResource() throws IOException { 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)); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java index f36c586e56ed5..4f9f5267413b2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java @@ -17,8 +17,8 @@ */ 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.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,8 +70,8 @@ public void testAsyncDiskService() throws Throwable { } 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)) { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAutoCloseableLock.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAutoCloseableLock.java index cd5447d52a02c..90beb58aee449 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAutoCloseableLock.java +++ b/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. */ diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestBasicDiskValidator.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestBasicDiskValidator.java index d6964a40d213f..f69a80273f750 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestBasicDiskValidator.java +++ b/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 @@ protected void checkDirs(boolean isDir, String perm, boolean success) 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java index 88f3b695ecfe5..e6fb8d1ddd597 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java @@ -18,9 +18,9 @@ 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.*; public class TestCacheableIPList { @@ -44,10 +44,10 @@ public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc 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 +56,10 @@ public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc 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 +85,10 @@ public void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte 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 +96,10 @@ public void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte 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 +124,10 @@ public void testAddWithRefresh() throws IOException, InterruptedException { 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 +136,10 @@ public void testAddWithRefresh() throws IOException, InterruptedException { 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 +165,10 @@ public void testRemovalWithRefresh() throws IOException, InterruptedException { 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 +176,10 @@ public void testRemovalWithRefresh() throws IOException, InterruptedException { 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"); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java index a007f85c244c2..aa79c5cc57660 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java @@ -17,14 +17,14 @@ */ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; 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.Assertions; +import org.junit.jupiter.api.Test; public class TestChunkedArrayList { @@ -103,41 +103,41 @@ public void testRemovals() throws Exception { // Iterate through all list elements. Iterator iter = list.iterator(); for (int i = 0; i < NUM_ELEMS; i++) { - Assert.assertTrue(iter.hasNext()); + Assertions.assertTrue(iter.hasNext()); Integer val = iter.next(); - Assert.assertEquals(Integer.valueOf(i), val); + Assertions.assertEquals(Integer.valueOf(i), val); } - Assert.assertFalse(iter.hasNext()); - Assert.assertEquals(NUM_ELEMS, list.size()); + Assertions.assertFalse(iter.hasNext()); + Assertions.assertEquals(NUM_ELEMS, list.size()); // Remove even elements. iter = list.iterator(); for (int i = 0; i < NUM_ELEMS; i++) { - Assert.assertTrue(iter.hasNext()); + Assertions.assertTrue(iter.hasNext()); Integer val = iter.next(); - Assert.assertEquals(Integer.valueOf(i), val); + Assertions.assertEquals(Integer.valueOf(i), val); if (i % 2 == 0) { iter.remove(); } } - Assert.assertFalse(iter.hasNext()); - Assert.assertEquals(NUM_ELEMS / 2, list.size()); + Assertions.assertFalse(iter.hasNext()); + Assertions.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()); + Assertions.assertTrue(iter.hasNext()); Integer val = iter.next(); - Assert.assertEquals(Integer.valueOf(1 + (2 * i)), val); + Assertions.assertEquals(Integer.valueOf(1 + (2 * i)), val); iter.remove(); } - Assert.assertFalse(iter.hasNext()); + Assertions.assertFalse(iter.hasNext()); // Check that list is now empty. - Assert.assertEquals(0, list.size()); - Assert.assertTrue(list.isEmpty()); + Assertions.assertEquals(0, list.size()); + Assertions.assertTrue(list.isEmpty()); iter = list.iterator(); - Assert.assertFalse(iter.hasNext()); + Assertions.assertFalse(iter.hasNext()); } @Test @@ -148,15 +148,15 @@ public void testGet() throws Exception { 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)); + Assertions.assertEquals(Integer.valueOf(100), list.get(100)); + Assertions.assertEquals(Integer.valueOf(1000), list.get(1000)); + Assertions.assertEquals(Integer.valueOf(10000), list.get(10000)); + Assertions.assertEquals(Integer.valueOf(100000), list.get(100000)); Iterator iter = list.iterator(); iter.next(); iter.remove(); - Assert.assertEquals(Integer.valueOf(1), list.get(0)); + Assertions.assertEquals(Integer.valueOf(1), list.get(0)); iter = list.iterator(); for (int i = 0; i < 500; i++) { @@ -164,7 +164,7 @@ public void testGet() throws Exception { } iter.remove(); - Assert.assertEquals(Integer.valueOf(502), list.get(500)); - Assert.assertEquals(Integer.valueOf(602), list.get(600)); + Assertions.assertEquals(Integer.valueOf(502), list.get(500)); + Assertions.assertEquals(Integer.valueOf(602), list.get(600)); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java index 3a7e12e8f0375..b6774b0e28f47 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java @@ -23,11 +23,13 @@ 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; public class TestClassUtil { - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testFindContainingJar() { String containingJar = ClassUtil.findContainingJar(Assertions.class); Assertions @@ -45,7 +47,8 @@ public void testFindContainingJar() { .matches("assertj-core.*[.]jar"); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testFindContainingClass() { String classFileLocation = ClassUtil.findClassLocation(ViewFileSystem.class); Assertions diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java index 716dfe0c36d56..6b2cd68bcd2b9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java @@ -17,7 +17,7 @@ */ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayOutputStream; import java.io.File; @@ -32,9 +32,9 @@ 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 +57,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 +73,7 @@ public void setUp() { System.setErr(printStderr); } - @After + @AfterEach public void tearDown() { System.setOut(oldStdout); System.setErr(oldStderr); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java index f6cc7c3283852..5982e5e17661f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java @@ -18,12 +18,12 @@ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayInputStream; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestConfTest { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java index 529d231572dda..82cdc6a7a6d88 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java @@ -22,7 +22,7 @@ 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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java index 6246672f0eb6f..5340b41313f1f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java +++ b/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 @@ -30,23 +30,23 @@ public void test() throws InterruptedException { System.currentTimeMillis()); float val1 = tracker.getCpuTrackerUsagePercent(); assertTrue( - "Not invalid CPU usage", - val1 == -1.0); + + 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); + + 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); + + val3 == 0.0, "Not positive CPU usage"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java index cf437f3854721..40c0e311525b8 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java @@ -25,12 +25,12 @@ import java.util.concurrent.TimeUnit; import org.apache.hadoop.test.LambdaTestUtils; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.rules.Timeout; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Unittests for CrcComposer. @@ -55,7 +55,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); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java index af96fdf541600..b1b22fcb7fe93 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java @@ -23,10 +23,10 @@ import org.apache.hadoop.test.LambdaTestUtils; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.rules.Timeout; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Unittests for CrcUtil. @@ -133,12 +133,12 @@ private static void doTestComposeCrc( compositeCrc, partialCrc, partialChunkSize, crcPolynomial); } assertEquals( - String.format( + + 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), - fullCrc, - compositeCrc); + type, crcPolynomial, chunkSize, fullCrc, compositeCrc)); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java index 8841809202f82..d877b4cada3bc 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java @@ -22,9 +22,9 @@ 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.*; public class TestDataChecksum { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDirectBufferPool.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDirectBufferPool.java index 592f40aa16c2d..51eb776d6eb83 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDirectBufferPool.java +++ b/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(); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java index e92c9edb4fd01..15a08a6c9bab5 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java @@ -21,10 +21,11 @@ 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.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -47,34 +48,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 +111,32 @@ private void _mkdirs(boolean exists, FsPermission before, FsPermission after) } } - @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 +171,7 @@ private void _checkDirs(boolean isDir, FsPermission perm, boolean success) 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 +185,32 @@ private void _checkDirs(boolean isDir, FsPermission perm, boolean success) * 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 +222,7 @@ protected void checkDirs(boolean isDir, String perm, boolean success) 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! diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java index 552d1319312c6..0811a98c37ad8 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java @@ -21,7 +21,7 @@ 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.jupiter.api.Test; import org.junit.rules.Timeout; import java.io.File; @@ -33,7 +33,8 @@ 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; /** @@ -57,11 +58,13 @@ public final void testDiskIoIgnoresTransientCreateErrors() throws Throwable { /** * 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 +80,13 @@ public final void testDiskIoIgnoresTransientWriteErrors() throws Throwable { /** * 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); + }); } /** @@ -94,14 +99,14 @@ public void testDiskIoFileNaming() { 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]+$")); + + 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-]+$")); + + guidFile.toString().matches("^.*\\.[A-Za-z0-9-]+$"), "File name does not match expected pattern: " + guidFile); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java index 1c02b7aa351f0..bfb1ef44b4ab7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java @@ -17,13 +17,12 @@ */ package org.apache.hadoop.util; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; import org.apache.hadoop.util.DiskChecker.DiskErrorException; +import static org.junit.jupiter.api.Assertions.*; + /** * The class to test DiskValidatorFactory. */ @@ -38,13 +37,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 +51,10 @@ public void testGetInstance() throws DiskErrorException { * 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"); + }); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java index b6abde8762902..7bed6ca6ed8ea 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java @@ -17,11 +17,13 @@ */ package org.apache.hadoop.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * The class to test DurationInfo. */ @@ -31,17 +33,17 @@ public class TestDurationInfo { @Test public void testDurationInfoCreation() throws Exception { DurationInfo info = new DurationInfo(log, "test"); - Assert.assertTrue(info.value() >= 0); + Assertions.assertTrue(info.value() >= 0); Thread.sleep(1000); info.finished(); - Assert.assertTrue(info.value() > 0); + Assertions.assertTrue(info.value() > 0); info = new DurationInfo(log, true, "test format %s", "value"); - Assert.assertEquals("test format value: duration 0:00.000s", + Assertions.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", + Assertions.assertEquals("test format value: duration 0:00.000s", info.toString()); } @@ -51,12 +53,14 @@ public void testDurationInfoWithMultipleClose() throws Exception { Thread.sleep(1000); info.close(); info.close(); - Assert.assertTrue(info.value() > 0); + Assertions.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(); + }); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java index 58a1997e9bc59..034df78c6a923 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java +++ b/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 @@ public class TestExitUtil extends AbstractHadoopTestBase { - @Before + @BeforeEach public void before() { ExitUtil.disableSystemExit(); ExitUtil.disableSystemHalt(); @@ -41,7 +41,7 @@ public void before() { ExitUtil.resetFirstHaltException(); } - @After + @AfterEach public void after() { ExitUtil.resetFirstExitException(); ExitUtil.resetFirstHaltException(); @@ -53,36 +53,36 @@ public void testGetSetExitExceptions() throws Throwable { 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 +94,34 @@ public void testGetSetHaltExceptions() throws Throwable { 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java index c8935dde3a5ba..c04cfc5150162 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java @@ -17,8 +17,9 @@ */ package org.apache.hadoop.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.text.NumberFormat; @@ -28,7 +29,8 @@ 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 +41,8 @@ public void testLongWithPadding() throws Exception { 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); + Assertions.assertEquals( + numberFormat.format(l), fastNumberStr, "Number formats should be equal"); } } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java index 1bb595cc2c8c0..59b8a3bc1b9a9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java @@ -22,13 +22,13 @@ 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.*; public class TestFileBasedIPList { - @After + @AfterEach public void tearDown() { removeFile("ips.txt"); } @@ -47,23 +47,23 @@ public void testSubnetsAndIPs() throws IOException { 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 +79,8 @@ public void testNullIP() throws IOException { 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 +98,25 @@ public void testWithMultipleSubnetAndIPs() throws IOException { 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 +129,8 @@ public void testFileNotSpecified() { 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 +143,8 @@ public void testFileMissing() { 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 +159,8 @@ public void testWithEmptyList() throws IOException { 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"); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java index 8ba930b7acb0a..d89ef2110c506 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java @@ -19,17 +19,17 @@ 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); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java index 14dde6a0c7cba..e034ddb2fff95 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java @@ -23,8 +23,10 @@ import java.util.Random; import org.apache.hadoop.HadoopIllegalArgumentException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class TestGSet { private static final Random ran = new Random(); @@ -53,7 +55,7 @@ private void testExceptionCases(boolean resizable) { try { //test contains with a null element gset.contains(null); - Assert.fail(); + Assertions.fail(); } catch(NullPointerException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -66,7 +68,7 @@ private void testExceptionCases(boolean resizable) { try { //test get with a null element gset.get(null); - Assert.fail(); + Assertions.fail(); } catch(NullPointerException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -79,14 +81,14 @@ private void testExceptionCases(boolean resizable) { try { //test put with a null element gset.put(null); - Assert.fail(); + Assertions.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(); + Assertions.fail(); } catch(IllegalArgumentException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -117,7 +119,7 @@ private void testExceptionCases(boolean resizable) { gset.remove(data[1]); } } - Assert.fail(); + Assertions.fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -132,7 +134,7 @@ private void testExceptionCases(boolean resizable) { gset.put(data[0]); } } - Assert.fail(); + Assertions.fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -147,7 +149,7 @@ private void testExceptionCases(boolean resizable) { gset.put(data[3]); } } - Assert.fail(); + Assertions.fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -261,7 +263,7 @@ private static void check(final GSetTestCase test) { for(int i = 0; i < test.data.size(); i++) { test.remove(test.data.get(i)); } - Assert.assertEquals(0, test.gset.size()); + Assertions.assertEquals(0, test.gset.size()); println("DONE " + test.stat()); //check remove and add again @@ -313,12 +315,12 @@ private static class GSetTestCase implements GSet { gset = resizable ? new LightWeightResizableGSet() : new LightWeightGSet(tablelength); - Assert.assertEquals(0, gset.size()); + Assertions.assertEquals(0, gset.size()); } private boolean containsTest(IntElement key) { final boolean e = expected.contains(key); - Assert.assertEquals(e, gset.contains(key)); + Assertions.assertEquals(e, gset.contains(key)); return e; } @Override @@ -330,7 +332,7 @@ public boolean contains(IntElement key) { private IntElement getTest(IntElement key) { final IntElement e = expected.get(key); - Assert.assertEquals(e.id, gset.get(key).id); + Assertions.assertEquals(e.id, gset.get(key).id); return e; } @Override @@ -343,9 +345,9 @@ public IntElement get(IntElement key) { private IntElement putTest(IntElement element) { final IntElement e = expected.put(element); if (e == null) { - Assert.assertEquals(null, gset.put(element)); + Assertions.assertEquals(null, gset.put(element)); } else { - Assert.assertEquals(e.id, gset.put(element).id); + Assertions.assertEquals(e.id, gset.put(element).id); } return e; } @@ -359,9 +361,9 @@ public IntElement put(IntElement element) { private IntElement removeTest(IntElement key) { final IntElement e = expected.remove(key); if (e == null) { - Assert.assertEquals(null, gset.remove(key)); + Assertions.assertEquals(null, gset.remove(key)); } else { - Assert.assertEquals(e.id, gset.remove(key).id); + Assertions.assertEquals(e.id, gset.remove(key).id); } return e; } @@ -374,7 +376,7 @@ public IntElement remove(IntElement key) { private int sizeTest() { final int s = expected.size(); - Assert.assertEquals(s, gset.size()); + Assertions.assertEquals(s, gset.size()); return s; } @Override @@ -427,7 +429,7 @@ String stat() { public void clear() { expected.clear(); gset.clear(); - Assert.assertEquals(0, size()); + Assertions.assertEquals(0, size()); } @Override @@ -504,27 +506,33 @@ public void setNext(LightWeightGSet.LinkedElement e) { * 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 +553,16 @@ private static void testCapacity(long maxMemory, double percent) { LightWeightGSet.LOG.info("Validating - total memory " + maxMemory + " percent " + percent + " returned capacity " + capacity); // Returned capacity is zero or power of two - Assert.assertTrue(isPowerOfTwo(capacity)); + Assertions.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); + Assertions.assertTrue(getPercent(maxMemory, capacity * 2) > percent); } else { - Assert.assertTrue(getPercent(maxMemory, capacity / 2) < percent); + Assertions.assertTrue(getPercent(maxMemory, capacity / 2) < percent); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java index 84893a2eff050..f203ed9d6f962 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java +++ b/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.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,7 +69,7 @@ public void testFilesOption() throws Exception { args[1] = tmpFile.toURI().toString(); new GenericOptionsParser(conf, args); String files = conf.get("tmpfiles"); - assertNotNull("files is null", files); + assertNotNull(files, "files is null"); assertEquals("files option does not match", localFs.makeQualified(tmpPath).toString(), files); @@ -80,7 +80,7 @@ public void testFilesOption() throws Exception { args[1] = tmpURI.toString(); new GenericOptionsParser(conf1, args); files = conf1.get("tmpfiles"); - assertNotNull("files is null", files); + assertNotNull(files, "files is null"); assertEquals("files option does not match", localFs.makeQualified(new Path(tmpURI)).toString(), files); @@ -95,11 +95,11 @@ public void testFilesOption() throws Exception { } 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,7 +116,7 @@ public void testLibjarsOption() throws Exception { args[1] = tmpJar.toURI().toString(); new GenericOptionsParser(conf, args); String libjars = conf.get("tmpjars"); - assertNotNull("libjars is null", libjars); + assertNotNull(libjars, "libjars is null"); assertEquals("libjars does not match", localFs.makeQualified(tmpJarPath).toString(), libjars); @@ -124,7 +124,7 @@ public void testLibjarsOption() throws Exception { args[1] = testDir.toURI().toString() + "*"; new GenericOptionsParser(conf, args); libjars = conf.get("tmpjars"); - assertNotNull("libjars is null", libjars); + assertNotNull(libjars, "libjars is null"); assertEquals("libjars does not match", localFs.makeQualified(tmpJarPath).toString(), libjars); } @@ -229,7 +229,7 @@ public void testConfWithMultipleOpts() throws Exception { "bar", g.getCommandLine().getOptionValues("conf")[1]); } - @Before + @BeforeEach public void setUp() throws Exception { conf = new Configuration(); localFs = FileSystem.getLocal(conf); @@ -238,7 +238,7 @@ public void setUp() throws Exception { 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 void testTokenCacheOption() throws IOException { 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,7 +284,7 @@ public void testTokenCacheOption() throws IOException { new GenericOptionsParser(conf, args); String fileName = conf.get("mapreduce.job.credentials.binary"); - assertNotNull("files is null", fileName); + assertNotNull(fileName, "files is null"); assertEquals("files option does not match", tmpPath.toString(), fileName); Credentials ugiCreds = @@ -380,8 +380,8 @@ private void assertDOptionParsing(String[] args, } assertArrayEquals( - Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs), - expectedRemainingArgs, remainingArgs); + + expectedRemainingArgs, remainingArgs, Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs)); } /** Test passing null as args. Some classes still call diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java index e47c3e57ba76e..6aa6b549d5150 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java @@ -21,8 +21,8 @@ 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.*; import org.apache.hadoop.conf.Configuration; @@ -42,8 +42,8 @@ public void testToArray() { for (int i = 0; i < arr.length; i++) { assertEquals( - "Array has identical elements as input list", - list.get(i), arr[i]); + + list.get(i), arr[i], "Array has identical elements as input list"); } } @@ -66,8 +66,8 @@ public void testWithEmptyList2() { //this method should not throw IndexOutOfBoundsException String[] arr = GenericsUtil.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 */ @@ -128,20 +128,20 @@ public void testGetClass() { //test with Integer Integer x = new Integer(42); Class 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 GenericClass testSubject = new GenericClass(); Class> 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java index 60dda981d4a1a..0c2e357f4ef7f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java @@ -25,9 +25,12 @@ 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.*; /* * Test for HostsFileReader.java @@ -43,11 +46,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 +139,7 @@ public void testCreateHostFileReaderWithNonexistentFile() throws Exception { 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 +161,7 @@ public void testRefreshHostFileReaderWithNonexistentFile() throws Exception { assertTrue(INCLUDES_FILE.delete()); try { hfp.refresh(); - Assert.fail("Should throw NoSuchFileException"); + fail("Should throw NoSuchFileException"); } catch (NoSuchFileException ex) { // Exception as expected } @@ -376,34 +379,36 @@ public void testLazyRefresh() throws IOException { 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(IllegalArgumentException.class, () -> { + FileWriter efw = new FileWriter(excludesFile); + FileWriter ifw = new FileWriter(includesFile); + efw.close(); + ifw.close(); + + HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile); + hfp.finishRefresh(); + }); } } \ No newline at end of file diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java index b6d5fef31c989..db4ea1a6bdad5 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hadoop.test.LambdaTestUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletResponse; @@ -53,11 +53,11 @@ public void testCreateServletException() throws IOException { ObjectMapper mapper = new ObjectMapper(); Map json = mapper.readValue(writer.toString(), Map.class); json = (Map) json.get(HttpExceptionUtils.ERROR_JSON); - Assert.assertEquals(IOException.class.getName(), + Assertions.assertEquals(IOException.class.getName(), json.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON)); - Assert.assertEquals(IOException.class.getSimpleName(), + Assertions.assertEquals(IOException.class.getSimpleName(), json.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON)); - Assert.assertEquals("Hello IOEX", + Assertions.assertEquals("Hello IOEX", json.get(HttpExceptionUtils.ERROR_MESSAGE_JSON)); } @@ -66,18 +66,18 @@ public void testCreateJerseyException() throws IOException { Exception ex = new IOException("Hello IOEX"); Response response = HttpExceptionUtils.createJerseyExceptionResponse( Response.Status.INTERNAL_SERVER_ERROR, ex); - Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + Assertions.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); - Assert.assertArrayEquals( + Assertions.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(), + Assertions.assertEquals(IOException.class.getName(), entity.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON)); - Assert.assertEquals(IOException.class.getSimpleName(), + Assertions.assertEquals(IOException.class.getSimpleName(), entity.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON)); - Assert.assertEquals("Hello IOEX", + Assertions.assertEquals("Hello IOEX", entity.get(HttpExceptionUtils.ERROR_MESSAGE_JSON)); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java index 2c27b762c45ce..7b64941edd5b9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java @@ -21,11 +21,12 @@ import java.util.LinkedList; import java.util.List; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; 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; @@ -55,43 +56,45 @@ public boolean equals(Object o) { } } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testStartingWithZeroCapacity() { IdentityHashStore store = new IdentityHashStore(0); store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assert.fail("found key " + k + " in empty IdentityHashStore."); + Assertions.fail("found key " + k + " in empty IdentityHashStore."); } }); - Assert.assertTrue(store.isEmpty()); + Assertions.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)); + Assertions.assertTrue(!store.isEmpty()); + Assertions.assertEquals(value1, store.get(key1)); store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assert.assertEquals(key1, k); + Assertions.assertEquals(key1, k); } }); - Assert.assertEquals(value1, store.remove(key1)); - Assert.assertTrue(store.isEmpty()); + Assertions.assertEquals(value1, store.remove(key1)); + Assertions.assertTrue(store.isEmpty()); } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testDuplicateInserts() { IdentityHashStore store = new IdentityHashStore(4); store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assert.fail("found key " + k + " in empty IdentityHashStore."); + Assertions.fail("found key " + k + " in empty IdentityHashStore."); } }); - Assert.assertTrue(store.isEmpty()); + Assertions.assertTrue(store.isEmpty()); Key key1 = new Key("key1"); Integer value1 = new Integer(100); Integer value2 = new Integer(200); @@ -100,10 +103,10 @@ public void accept(Key k, Integer v) { Key equalToKey1 = new Key("key1"); // IdentityHashStore compares by object equality, not equals() - Assert.assertNull(store.get(equalToKey1)); + Assertions.assertNull(store.get(equalToKey1)); - Assert.assertTrue(!store.isEmpty()); - Assert.assertEquals(value1, store.get(key1)); + Assertions.assertTrue(!store.isEmpty()); + Assertions.assertEquals(value1, store.get(key1)); store.put(key1, value2); store.put(key1, value3); final List allValues = new LinkedList(); @@ -113,16 +116,17 @@ public void accept(Key k, Integer v) { allValues.add(v); } }); - Assert.assertEquals(3, allValues.size()); + Assertions.assertEquals(3, allValues.size()); for (int i = 0; i < 3; i++) { Integer value = store.remove(key1); - Assert.assertTrue(allValues.remove(value)); + Assertions.assertTrue(allValues.remove(value)); } - Assert.assertNull(store.remove(key1)); - Assert.assertTrue(store.isEmpty()); + Assertions.assertNull(store.remove(key1)); + Assertions.assertTrue(store.isEmpty()); } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testAdditionsAndRemovals() { IdentityHashStore store = new IdentityHashStore(0); @@ -138,23 +142,23 @@ public void testAdditionsAndRemovals() { store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assert.assertTrue(keys.contains(k)); + Assertions.assertTrue(keys.contains(k)); } }); for (int i = 0; i < NUM_KEYS; i++) { - Assert.assertEquals(Integer.valueOf(i), + Assertions.assertEquals(Integer.valueOf(i), store.remove(keys.get(i))); } store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assert.fail("expected all entries to be removed"); + Assertions.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()); + Assertions.assertTrue( + store.isEmpty(), "expected the store to be " + + "empty, but found " + store.numElements() + " elements."); + Assertions.assertEquals(1024, store.capacity()); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java index 3de08544957d5..69828b958bb83 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java @@ -21,8 +21,8 @@ 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.*; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; @@ -38,8 +38,8 @@ public void sortAllEqual(IndexedSorter sorter) throws Exception { 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 +54,8 @@ public void sortAllEqual(IndexedSorter sorter) throws Exception { 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 +73,8 @@ public void sortSorted(IndexedSorter sorter) throws Exception { 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 +86,8 @@ public void sortSequential(IndexedSorter sorter) throws Exception { 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 +96,8 @@ public void sortSingleRecord(IndexedSorter sorter) throws Exception { 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 +110,8 @@ public void sortRandom(IndexedSorter sorter) throws Exception { 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 +124,8 @@ public void sortWritable(IndexedSorter sorter) throws Exception { 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 +267,15 @@ public MeasuredSortable(IndexedSortable s, int maxcmp, int maxswp) { @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); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java index c47ff0712d201..a972b80a057e4 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java @@ -26,10 +26,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.rules.TestName; import static org.mockito.Mockito.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * A test class for InstrumentedLock. @@ -44,7 +45,8 @@ public class TestInstrumentedLock { * Test exclusive access of the lock. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testMultipleThread() throws Exception { String testname = name.getMethodName(); InstrumentedLock lock = new InstrumentedLock(testname, LOG, 0, 300); @@ -67,7 +69,8 @@ public void run() { * Test the correctness with try-with-resource syntax. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testTryWithResourceSyntax() throws Exception { String testname = name.getMethodName(); final AtomicReference lockThread = new AtomicReference<>(null); @@ -105,7 +108,8 @@ public void run() { * and not log warning otherwise. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testLockLongHoldingReport() throws Exception { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); @@ -172,7 +176,8 @@ void logWarning(long lockHeldTime, SuppressedSnapshot stats) { * threshold and not log warning otherwise. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testLockLongWaitReport() throws Exception { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java index 4d0f8d2e04f20..a0138bb88a397 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java @@ -17,15 +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.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +46,8 @@ public class TestInstrumentedReadWriteLock { * Tests exclusive access of the write lock. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testWriteLock() throws Exception { String testname = name.getMethodName(); final ThreadLocal locked = new ThreadLocal(); @@ -95,7 +97,8 @@ public void run() { * Tests the read lock. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testReadLock() throws Exception { String testname = name.getMethodName(); InstrumentedReadWriteLock readWriteLock = new InstrumentedReadWriteLock( @@ -129,7 +132,8 @@ public void run() { * Tests the warning when the read lock is held longer than threshold. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testReadLockLongHoldingReport() throws Exception { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); @@ -184,7 +188,8 @@ protected void logWarning( * Tests the warning when the write lock is held longer than threshold. * @throws Exception */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testWriteLockLongHoldingReport() throws Exception { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); @@ -238,7 +243,8 @@ protected void logWarning(long lockHeldTime, SuppressedSnapshot stats) { /** * Tests the warning when the write lock is held longer than threshold. */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testWriteLockLongHoldingReportWithReentrant() { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); @@ -298,7 +304,8 @@ protected void logWarning(long lockHeldTime, SuppressedSnapshot stats) { /** * Tests the warning when the read lock is held longer than threshold. */ - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testReadLockLongHoldingReportWithReentrant() { String testname = name.getMethodName(); final AtomicLong time = new AtomicLong(0); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java index 109cb191b485f..a6d1a926def25 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java @@ -19,8 +19,8 @@ package org.apache.hadoop.util; import org.apache.hadoop.test.GenericTestUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; @@ -44,7 +44,7 @@ public void testJar() throws Exception { //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()); + Assertions.assertTrue(new File(jar).exists()); } private static void delete(File file) throws IOException { @@ -75,7 +75,7 @@ public void testExpandedClasspath() throws Exception { //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()); + Assertions.assertTrue(new File(jar).exists()); } @Test @@ -102,7 +102,7 @@ public void testExistingManifest() throws Exception { JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); - Assert.assertNotNull(jis.getManifest()); + Assertions.assertNotNull(jis.getManifest()); jis.close(); } @@ -121,7 +121,7 @@ public void testNoManifest() throws Exception { JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); - Assert.assertNotNull(jis.getManifest()); + Assertions.assertNotNull(jis.getManifest()); jis.close(); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java index de6181810db08..cf9e64f15a969 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java @@ -22,8 +22,8 @@ import java.util.Iterator; import java.util.Random; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** Testing {@link LightWeightCache} */ public class TestLightWeightCache { @@ -81,7 +81,7 @@ private static void checkSizeLimit(final int sizeLimit, final int datasize, 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); + Assertions.assertTrue(test.cache.size() <= sizeLimit); } println("DONE " + test.stat()); } @@ -169,7 +169,7 @@ private static void check(final LightWeightCacheTestCase test) { for(int i = 0; i < test.data.size(); i++) { test.remove(test.data.get(i)); } - Assert.assertEquals(0, test.cache.size()); + Assertions.assertEquals(0, test.cache.size()); println("DONE " + test.stat()); //check remove and put again @@ -232,17 +232,17 @@ private static class LightWeightCacheTestCase implements GSet(tablelength, sizeLimit, creationExpirationPeriod, 0, fakeTimer); - Assert.assertEquals(0, cache.size()); + Assertions.assertEquals(0, cache.size()); } private boolean containsTest(IntEntry key) { final boolean c = cache.contains(key); if (c) { - Assert.assertTrue(hashMap.contains(key)); + Assertions.assertTrue(hashMap.contains(key)); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -257,11 +257,11 @@ public boolean contains(IntEntry key) { private IntEntry getTest(IntEntry key) { final IntEntry c = cache.get(key); if (c != null) { - Assert.assertEquals(hashMap.get(key).id, c.id); + Assertions.assertEquals(hashMap.get(key).id, c.id); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -276,12 +276,12 @@ public IntEntry get(IntEntry key) { private IntEntry putTest(IntEntry entry) { final IntEntry c = cache.put(entry); if (c != null) { - Assert.assertEquals(hashMap.put(entry).id, c.id); + Assertions.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())); + Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -296,11 +296,11 @@ public IntEntry put(IntEntry entry) { private IntEntry removeTest(IntEntry key) { final IntEntry c = cache.remove(key); if (c != null) { - Assert.assertEquals(c.id, hashMap.remove(key).id); + Assertions.assertEquals(c.id, hashMap.remove(key).id); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -314,7 +314,7 @@ public IntEntry remove(IntEntry key) { private int sizeTest() { final int c = cache.size(); - Assert.assertTrue(hashMap.size() >= c); + Assertions.assertTrue(hashMap.size() >= c); return c; } @Override @@ -373,7 +373,7 @@ String stat() { public void clear() { hashMap.clear(); cache.clear(); - Assert.assertEquals(0, size()); + Assertions.assertEquals(0, size()); } @Override diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java index 3751253062c9e..a1458ae20ba8b 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java @@ -22,8 +22,9 @@ import java.util.Random; import org.apache.hadoop.util.LightWeightGSet.LinkedElement; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -65,7 +66,8 @@ public LinkedElement getNext() { } } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testRemoveAllViaIterator() { ArrayList list = getRandomList(100, 123); LightWeightGSet set = @@ -78,10 +80,11 @@ public void testRemoveAllViaIterator() { iter.next(); iter.remove(); } - Assert.assertEquals(0, set.size()); + Assertions.assertEquals(0, set.size()); } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testRemoveSomeViaIterator() { ArrayList list = getRandomList(100, 123); LightWeightGSet set = @@ -105,7 +108,7 @@ public void testRemoveSomeViaIterator() { } for (Iterator iter = set.iterator(); iter.hasNext(); ) { - Assert.assertTrue(iter.next().getVal() <= mode); + Assertions.assertTrue(iter.next().getVal() <= mode); } } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java index c043d1e590e5d..1044ab99409a7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightResizableGSet.java @@ -23,7 +23,8 @@ 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 LightWeightResizableGSet.LinkedElement getNext() { } } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testBasicOperations() { TestElement[] elements = generateElements(1 << 16); final LightWeightResizableGSet set = @@ -191,7 +193,8 @@ public void testBasicOperations() { assertThat(set.size()).isZero(); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testRemoveAll() { TestElement[] elements = generateElements(1 << 16); final LightWeightResizableGSet set = diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java index c14b3cb145b20..3efce8ae7df89 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java @@ -23,8 +23,8 @@ import java.util.Arrays; import org.apache.hadoop.io.Text; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TestLineReader { @@ -90,10 +90,10 @@ public void testCustomDelimiter1() throws Exception { lineReader.readLine(line); lineReader.close(); - Assert.assertEquals(fillerString.toString(), line.toString()); + Assertions.assertEquals(fillerString.toString(), line.toString()); lineReader.readLine(line); - Assert.assertEquals(expected, line.toString()); + Assertions.assertEquals(expected, line.toString()); } /** @@ -122,23 +122,23 @@ public void testCustomDelimiter2() throws Exception { final Text line = new Text(); lineReader.readLine(line); - Assert.assertEquals("", line.toString()); + Assertions.assertEquals("", line.toString()); lineReader.readLine(line); - Assert.assertEquals("Kerala ", line.toString()); + Assertions.assertEquals("Kerala ", line.toString()); lineReader.readLine(line); - Assert.assertEquals("Bangalore", line.toString()); + Assertions.assertEquals("Bangalore", line.toString()); lineReader.readLine(line); - Assert.assertEquals(" North Korea", line.toString()); + Assertions.assertEquals(" North Korea", line.toString()); lineReader.readLine(line); - Assert.assertEquals("", line.toString()); + Assertions.assertEquals("", line.toString()); lineReader.readLine(line); - Assert.assertEquals("Guantanamo", line.toString()); + Assertions.assertEquals("Guantanamo", line.toString()); lineReader.readLine(line); - Assert.assertEquals(("ecord" + "recor" + "core"), line.toString()); + Assertions.assertEquals(("ecord" + "recor" + "core"), line.toString()); lineReader.close(); } @@ -157,9 +157,9 @@ public void testCustomDelimiter3() throws Exception { final Text line = new Text(); lineReader.readLine(line); - Assert.assertEquals("a", line.toString()); + Assertions.assertEquals("a", line.toString()); lineReader.readLine(line); - Assert.assertEquals("ccc", line.toString()); + Assertions.assertEquals("ccc", line.toString()); lineReader.close(); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java index 53241da695c63..53281925a6fee 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java +++ b/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.Assertions; +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; + /** * Simple tests for utility class Lists. */ @@ -36,27 +37,27 @@ public class TestLists { public void testAddToEmptyArrayList() { List list = Lists.newArrayList(); list.add("record1"); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("record1", list.get(0)); + Assertions.assertEquals(1, list.size()); + Assertions.assertEquals("record1", list.get(0)); } @Test public void testAddToEmptyLinkedList() { List list = Lists.newLinkedList(); list.add("record1"); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("record1", list.get(0)); + Assertions.assertEquals(1, list.size()); + Assertions.assertEquals("record1", list.get(0)); } @Test public void testVarArgArrayLists() { List 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)); + Assertions.assertEquals(4, list.size()); + Assertions.assertEquals("record1", list.get(0)); + Assertions.assertEquals("record2", list.get(1)); + Assertions.assertEquals("record3", list.get(2)); + Assertions.assertEquals("record4", list.get(3)); } @Test @@ -67,7 +68,7 @@ public void testItrArrayLists() { set.add("record3"); List list = Lists.newArrayList(set); list.add("record4"); - Assert.assertEquals(4, list.size()); + Assertions.assertEquals(4, list.size()); } @Test @@ -78,7 +79,7 @@ public void testItrLinkedLists() { set.add("record3"); List list = Lists.newLinkedList(set); list.add("record4"); - Assert.assertEquals(4, list.size()); + Assertions.assertEquals(4, list.size()); } @Test @@ -91,34 +92,34 @@ public void testListsPartition() { list.add("e"); List> 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> 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> 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 void testArrayListWithSize() { 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)); + Assertions.assertEquals(3, list.size()); + Assertions.assertEquals("record1", list.get(0)); + Assertions.assertEquals("record2", list.get(1)); + Assertions.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)); + Assertions.assertEquals(3, list.size()); + Assertions.assertEquals("record1", list.get(0)); + Assertions.assertEquals("record2", list.get(1)); + Assertions.assertEquals("record3", list.get(2)); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java index e54656a1cc62a..ab0063c804d6f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java @@ -17,11 +17,6 @@ */ 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 java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; @@ -29,7 +24,9 @@ import java.util.Map; import org.apache.hadoop.thirdparty.com.google.common.net.InetAddresses; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class TestMachineList { private static String IP_LIST = "10.119.103.110,10.119.103.112,10.119.103.114"; @@ -186,14 +183,16 @@ public void testCIDRs() { 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java index 98b75bba4793a..0fca11f20bdd9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java @@ -17,8 +17,8 @@ */ 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.*; import org.apache.hadoop.crypto.OpensslCipher; import org.apache.hadoop.io.compress.zlib.ZlibFactory; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java index b2d9e7420649e..3c128d47c3156 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java @@ -17,7 +17,7 @@ */ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.junit.Assume.*; import java.nio.ByteBuffer; @@ -27,8 +27,8 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ChecksumException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @@ -61,12 +61,12 @@ public TestNativeCrc32(DataChecksum.Type checksumType) { this.checksumType = checksumType; } - @Before + @BeforeEach public void setup() { assumeTrue(NativeCrc32.isAvailable()); assertEquals( - "These tests assume they can write a checksum value as a 4-byte int.", 4, - checksumType.size); + 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); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java index e4792dc757b28..8359aec8a8a25 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java @@ -19,8 +19,8 @@ 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.*; import org.apache.hadoop.util.ExitUtil.ExitException; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java index 65a2babae2008..612073119bb66 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java @@ -18,21 +18,21 @@ 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.*; 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java index 62e033e1e0452..0006637e617e0 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPreconditions.java @@ -20,7 +20,7 @@ import java.util.function.Supplier; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.apache.hadoop.test.LambdaTestUtils; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java index 20f537b2fa5c2..835d5ff0e203d 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java @@ -18,8 +18,8 @@ package org.apache.hadoop.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TestProgress { @@ -27,18 +27,18 @@ public class TestProgress { public void testSet(){ Progress progress = new Progress(); progress.set(Float.NaN); - Assert.assertEquals(0, progress.getProgress(), 0.0); + Assertions.assertEquals(0, progress.getProgress(), 0.0); progress.set(Float.NEGATIVE_INFINITY); - Assert.assertEquals(0,progress.getProgress(),0.0); + Assertions.assertEquals(0,progress.getProgress(),0.0); progress.set(-1); - Assert.assertEquals(0,progress.getProgress(),0.0); + Assertions.assertEquals(0,progress.getProgress(),0.0); progress.set((float) 1.1); - Assert.assertEquals(1,progress.getProgress(),0.0); + Assertions.assertEquals(1,progress.getProgress(),0.0); progress.set(Float.POSITIVE_INFINITY); - Assert.assertEquals(1,progress.getProgress(),0.0); + Assertions.assertEquals(1,progress.getProgress(),0.0); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProtoUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProtoUtil.java index 4792fd49b98cf..9427532064334 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProtoUtil.java +++ b/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.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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java index bf3e58793bb24..8d27fea37c795 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java @@ -29,8 +29,8 @@ import java.util.zip.CRC32; import java.util.zip.Checksum; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit test to verify that the pure-Java CRC32 algorithm gives @@ -96,7 +96,7 @@ private void checkOnBytes(byte[] bytes, boolean print) { } private void checkSame() { - Assert.assertEquals(theirs.getValue(), ours.getValue()); + Assertions.assertEquals(theirs.getValue(), ours.getValue()); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java index b085bbf2ac928..18d6d14192661 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32C.java @@ -19,9 +19,9 @@ 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 void testChecksumInit() { 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java index b50a73f85a0e3..a30f61b49f72f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java +++ b/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,9 @@ 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 org.junit.jupiter.api.Assertions; import java.io.File; import java.nio.file.Files; @@ -44,7 +44,7 @@ public class TestReadWriteDiskValidator { private MetricsSystem ms; - @Before + @BeforeEach public void setUp() { ms = DefaultMetricsSystem.instance(); } @@ -64,14 +64,14 @@ public void 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); + Assertions.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); + Assertions.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 +154,8 @@ public void testCheckFailures() throws Throwable { "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(); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java index 1d1ce893a97a2..b81c2bf2305c7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java @@ -25,13 +25,13 @@ import java.util.HashMap; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; 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 +40,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 +116,7 @@ public void testCacheDoesntLeak() throws Exception { assertEquals(cl, o.getClass()); } System.gc(); - assertTrue(cacheSize()+" too big", cacheSize() hooks = mgr.getShutdownHooksInOrder(); @@ -124,34 +124,34 @@ public void shutdownHookManager() { // 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 +161,8 @@ public void testShutdownTimeoutConfiguration() throws Throwable { 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 +176,8 @@ public void testShutdownTimeoutBadConfiguration() throws Throwable { 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 +195,37 @@ public void testDuplicateRegistration() throws Throwable { mgr.addShutdownHook(hook, 5); List 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()); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownThreadsHelper.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownThreadsHelper.java index e22e134388c2f..6bad38b0e1b48 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownThreadsHelper.java +++ b/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 void run() { } }; - @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 void testShutdownThreadPool() throws InterruptedException { 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java index f6b272e1c6172..aab71abc7f756 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java @@ -19,9 +19,10 @@ package org.apache.hadoop.util; import org.apache.commons.lang3.SystemUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; 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; @@ -29,13 +30,14 @@ 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); SignalLogger.INSTANCE.register(LOG); try { SignalLogger.INSTANCE.register(LOG); - Assert.fail("expected IllegalStateException from double registration"); + Assertions.fail("expected IllegalStateException from double registration"); } catch (IllegalStateException e) { // fall through } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java index 6f577b08d241c..465a29f71a9b3 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java @@ -17,19 +17,19 @@ */ package org.apache.hadoop.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TestStopWatch { @Test public void testStartAndStop() throws Exception { try (StopWatch sw = new StopWatch()) { - Assert.assertFalse(sw.isRunning()); + Assertions.assertFalse(sw.isRunning()); sw.start(); - Assert.assertTrue(sw.isRunning()); + Assertions.assertTrue(sw.isRunning()); sw.stop(); - Assert.assertFalse(sw.isRunning()); + Assertions.assertFalse(sw.isRunning()); } } @@ -46,16 +46,16 @@ public void testExceptions() throws Exception { try { sw.stop(); } catch (Exception e) { - Assert.assertTrue("IllegalStateException is expected", - e instanceof IllegalStateException); + Assertions.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); + Assertions.assertTrue( + e instanceof IllegalStateException, "IllegalStateException is expected"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java index e43da49d75d96..fffec2bb8afad 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java @@ -18,10 +18,10 @@ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.apache.hadoop.util.StringInterner.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java index e6dcc5e8de0f0..ee9b45cbd6ab2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java @@ -24,12 +24,12 @@ 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.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; @@ -49,7 +49,8 @@ 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 void testEscapeString() throws Exception { 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 void testSplit() throws Exception { 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,14 @@ public void testSimpleSplit() throws Exception { "/", "////"}; 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 +163,8 @@ public void testUnescapeString() throws Exception { 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 +247,19 @@ public void testTraditionalBinaryPrefix() throws Exception { { // 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 +290,8 @@ public void testTraditionalBinaryPrefix() throws Exception { assertEquals("0.5430%", StringUtils.formatPercent(0.00543, 4)); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testJoin() { List s = new ArrayList(); s.add("a"); @@ -300,7 +307,8 @@ public void testJoin() { 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 +330,8 @@ public void testGetTrimmedStrings() throws Exception { assertArrayEquals(emptyArray, estring); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testCamelize() { // common use cases assertEquals("Map", StringUtils.camelize("MAP")); @@ -358,7 +367,8 @@ public void testCamelize() { assertEquals("Zz", StringUtils.camelize("zZ")); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testStringToURI() { String[] str = new String[] { "file://" }; try { @@ -369,7 +379,8 @@ public void testStringToURI() { } } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testSimpleHostName() { assertEquals("Should return hostname when FQDN is specified", "hadoop01", @@ -382,7 +393,8 @@ public void testSimpleHostName() { StringUtils.simpleHostname("10.10.5.68")); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testReplaceTokensShellEnvVars() { Pattern pattern = StringUtils.SHELL_ENV_VAR_PATTERN; Map replacements = new HashMap(); @@ -403,7 +415,8 @@ public void testReplaceTokensShellEnvVars() { replacements)); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testReplaceTokensWinEnvVars() { Pattern pattern = StringUtils.WIN_ENV_VAR_PATTERN; Map replacements = new HashMap(); @@ -471,8 +484,8 @@ public void run() { 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 +500,16 @@ public void testFormatTimeSortable() { 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 +517,8 @@ public void testEscapeHTML() { String htmlStr = "

Hello. How are you?

"; String escapedStr = "<p>Hello. How are you?</p>"; - assertEquals("Incorrect escaped HTML string returned", - escapedStr, StringUtils.escapeHTML(htmlStr)); + assertEquals( + escapedStr, StringUtils.escapeHTML(htmlStr), "Incorrect escaped HTML string returned"); } @Test diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java index f8ef7f2aa3ba5..75a56c4576b61 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoLinux.java @@ -24,10 +24,10 @@ 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} diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java index fc99aeb976f91..abefb9828d241 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java +++ b/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.*; public class TestSysInfoWindows { @@ -43,7 +44,8 @@ long now() { } } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void parseSystemInfoString() { SysInfoWindowsMock tester = new SysInfoWindowsMock(); tester.setSysinfoString( @@ -69,7 +71,8 @@ public void parseSystemInfoString() { 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 void refreshAndCpuUsage() throws InterruptedException { 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 void refreshAndCpuUsageMulticore() throws InterruptedException { 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestTime.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestTime.java index 360e5f8b10715..beb736886feac 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestTime.java +++ b/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}. diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java index b1737dcb525d0..bf6339656d0d7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java @@ -17,9 +17,9 @@ */ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestVersionUtil { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java index 3203de8a96488..1c95f1535d107 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java @@ -23,8 +23,8 @@ 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; @@ -50,7 +50,7 @@ public class TestWeakReferenceMap extends AbstractHadoopTestBase { */ private List lostReferences; - @Before + @BeforeEach public void setup() { lostReferences = new ArrayList<>(); referenceMap = new WeakReferenceMap<>( diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java index 00e36ee8fa941..8b829261880b3 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java @@ -19,7 +19,7 @@ package org.apache.hadoop.util; import static org.apache.hadoop.test.PlatformAssumptions.assumeWindows; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.FileInputStream; @@ -31,9 +31,10 @@ 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 +49,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 +88,8 @@ private String readFile(File file) throws IOException { return new String(b); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testLs() throws IOException { requireWinutils(); final String content = "6bytes"; @@ -117,7 +119,8 @@ public void testLs() throws IOException { assertFalse(testFile.exists()); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testGroups() throws IOException { requireWinutils(); String currentUser = System.getProperty("user.name"); @@ -241,7 +244,8 @@ private void testChmodInternalR(String mode, String expectedPerm, assertTrue(FileUtil.fullyDelete(a)); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testBasicChmod() throws IOException { requireWinutils(); // - Create a file. @@ -253,7 +257,7 @@ public void testBasicChmod() throws IOException { 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 +298,8 @@ public void testBasicChmod() throws IOException { } /** 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 +311,7 @@ public void testBasicChmodOnDir() throws IOException { // 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 +338,12 @@ public void testBasicChmodOnDir() throws IOException { // 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 +377,8 @@ public void testBasicChmodOnDir() throws IOException { chmod("700", a); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testChmod() throws IOException { requireWinutils(); testChmodInternal("7", "-------rwx"); @@ -407,7 +413,8 @@ private void assertOwners(File file, String expectedUser, 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 +440,8 @@ public void testChown() throws IOException { 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 +458,8 @@ public void testSymlinkRejectsForwardSlashesInLink() throws IOException { } } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testSymlinkRejectsForwardSlashesInTarget() throws IOException { requireWinutils(); File newFile = new File(TEST_DIR, "file"); @@ -467,7 +476,8 @@ public void testSymlinkRejectsForwardSlashesInTarget() throws IOException { } } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testReadLink() throws IOException { requireWinutils(); // Create TEST_DIR\dir1\file1.txt @@ -549,7 +559,8 @@ public void testReadLink() throws IOException { } } - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testTaskCreate() throws IOException { requireWinutils(); File batch = new File(TEST_DIR, "testTaskCreate.cmd"); @@ -571,7 +582,8 @@ public void testTaskCreate() throws IOException { Assertions.assertThat(outNumber).contains(testNumber); } - @Test (timeout = 30000) + @Test + @Timeout(value = 30) public void testTaskCreateWithLimits() throws IOException { requireWinutils(); // Generate a unique job id diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java index 6db16b6c0c598..d2768c8c94935 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java @@ -33,37 +33,43 @@ 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.Assertions; +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.assertThrows; + public class TestXMLUtils extends AbstractHadoopTestBase { @Test public void testSecureDocumentBuilderFactory() throws Exception { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(""))); - 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 +78,24 @@ public void testSecureSAXParserFactory() throws Exception { parser.parse(new InputSource(new StringReader("")), 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 +105,21 @@ public void testSecureTransformerFactory() throws Exception { Document doc = db.parse(new InputSource(new StringReader(""))); try (StringWriter stringWriter = new StringWriter()) { transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); - Assertions.assertThat(stringWriter.toString()).contains(" { + 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 +129,21 @@ public void testSecureSAXTransformerFactory() throws Exception { Document doc = db.parse(new InputSource(new StringReader(""))); try (StringWriter stringWriter = new StringWriter()) { transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); - Assertions.assertThat(stringWriter.toString()).contains(" { + 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 +151,14 @@ public void testBestEffortSetAttribute() throws Exception { 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()); + Assertions.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()); + Assertions.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()); + Assertions.assertFalse( + flag3.get(), "expected attribute results in return of false if input flag is false?"); } private static InputStream getResourceStream(final String filename) { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java index d12fff2732cd6..53031270c4af7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java @@ -17,7 +17,7 @@ */ package org.apache.hadoop.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.FileNotFoundException; @@ -30,7 +30,7 @@ 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 +80,7 @@ public void testRemoveSpecificPerms() { 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java index f43930dd07a5e..7bff7ee6060ab 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java @@ -18,8 +18,8 @@ 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 java.io.IOException; import java.util.AbstractCollection; @@ -27,7 +27,7 @@ import java.util.Iterator; import java.util.Random; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.util.hash.Hash; @@ -83,7 +83,7 @@ public ImmutableSet falsePositives(int hashId) { } default: { // fail fast with unknown hash error !!! - Assert.assertFalse("unknown hash error", true); + Assertions.assertFalse(true, "unknown hash error"); return ImmutableSet.of(); } } @@ -134,7 +134,7 @@ private static Filter getSymmetricFilter(Class filterClass, 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 void assertWhat(Filter filter, int numInsertions, int hashId, 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() { @@ -178,10 +178,10 @@ public int size() { }); - 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 @@ private void checkOnKeyMethods() { 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 @@ private void checkOnReadWrite() { 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"); + Assertions.fail("checkOnReadWrite ex error"); } } @@ -240,7 +240,7 @@ private void checkSetOnIAE() { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assert.fail("checkSetOnIAE ex error"); + Assertions.fail("checkSetOnIAE ex error"); } } @@ -272,7 +272,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } try { @@ -281,7 +281,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } try { @@ -290,7 +290,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } try { @@ -298,7 +298,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } try { @@ -306,7 +306,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } try { @@ -316,7 +316,7 @@ private void checkAndOnIAE(Filter filter) { } catch (UnsupportedOperationException unex) { // } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } } @@ -328,7 +328,7 @@ private void checkTestMembershipOnNPE(Filter filter) { } catch (NullPointerException ex) { // expected } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } } @@ -339,7 +339,7 @@ private void checkAddOnNPE(Filter filter) { } catch (NullPointerException ex) { // expected } catch (Exception e) { - Assert.fail("" + e); + Assertions.fail("" + e); } } }), @@ -357,15 +357,15 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // 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()))); + Assertions.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 void assertWhat(Filter filter, int numInsertions, int hashId, 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); + Assertions.fail("error ex !!!" + ex); } } }), @@ -424,8 +424,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, 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()))); + Assertions.assertFalse( + filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } // add all even keys @@ -442,8 +442,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // 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()))); + Assertions.assertFalse( + filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might not contains " + i); } } catch (UnsupportedOperationException ex) { @@ -478,8 +478,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, 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()))); + Assertions.assertTrue( + filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } } } @@ -508,8 +508,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // 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()))); + Assertions.assertTrue( + filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } } }); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java index cfd9628885d4f..f3a379e9a6e07 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java @@ -18,9 +18,9 @@ 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 java.util.AbstractCollection; import java.util.BitSet; @@ -28,8 +28,8 @@ 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.Assertions; +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,24 @@ public void testCountingBloomFilter() { 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,7 +186,7 @@ private void checkOnAbsentFalsePositive(int hashId, int numInsertions, .get(hashId); if (falsePositives == null) - Assert.fail(String.format("false positives for hash %d not founded", + Assertions.fail(String.format("false positives for hash %d not founded", hashId)); filter.addFalsePositive(falsePositives); @@ -200,8 +200,8 @@ private void checkOnAbsentFalsePositive(int hashId, int numInsertions, } 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 +257,7 @@ public void testNot() { 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java index 7720534dc7ed4..51c01aa4f014e 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java @@ -23,9 +23,9 @@ 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.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 customConfiguration = new HashMap<>(); @@ -132,7 +132,7 @@ public static Configuration setUpSecureConfig(Configuration conf, String testDat return conf; } - @After + @AfterEach public void teardown() throws Exception { this.curator.close(); if (this.server != null) { @@ -159,21 +159,21 @@ private void validateSSLConfiguration(String keystoreLocation, String keystorePa 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( + ClientCnxnSocketNetty.class.getCanonicalName() +, zk.getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET), "Validate that expected clientConfig is set in ZK config"); } @Test diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java index 354be1d94da52..edf00a0da5521 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java +++ b/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.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 void setup() throws Exception { this.curator.start(zkHostPort); } - @After + @AfterEach public void teardown() throws Exception { this.curator.close(); if (this.server != null) { @@ -231,14 +231,14 @@ public void testCuratorFrameworkFactory() throws Exception{ 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"); } } \ No newline at end of file diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java index 4d7a2db641703..de6376319dd33 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java @@ -21,8 +21,8 @@ import java.util.concurrent.Callable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.apache.hadoop.test.AbstractHadoopTestBase; @@ -76,7 +76,7 @@ public void testFirstImplReturned() throws Exception { .buildChecked(); Concatenator dashCat = sepCtor.newInstanceChecked("-"); - Assert.assertEquals("Should construct with the 1-arg version", + Assertions.assertEquals("Should construct with the 1-arg version", "a-b", dashCat.concat("a", "b")); intercept(IllegalArgumentException.class, () -> @@ -92,7 +92,7 @@ public void testFirstImplReturned() throws Exception { .buildChecked(); Concatenator cat = defaultCtor.newInstanceChecked(); - Assert.assertEquals("Should construct with the no-arg version", + Assertions.assertEquals("Should construct with the no-arg version", "ab", cat.concat("a", "b")); } @@ -116,7 +116,7 @@ public void testStringClassname() throws Exception { .impl(Concatenator.class.getName(), String.class) .buildChecked(); - Assert.assertNotNull("Should find 1-arg constructor", sepCtor.newInstance("-")); + Assertions.assertNotNull(sepCtor.newInstance("-"), "Should find 1-arg constructor"); } @Test @@ -130,11 +130,11 @@ public void testHiddenMethod() throws Exception { .hiddenImpl(Concatenator.class.getName(), char.class) .buildChecked(); - Assert.assertNotNull("Should find hidden ctor with hiddenImpl", sepCtor); + Assertions.assertNotNull(sepCtor, "Should find hidden ctor with hiddenImpl"); Concatenator slashCat = sepCtor.newInstanceChecked('/'); - Assert.assertEquals("Should use separator /", + Assertions.assertEquals("Should use separator /", "a/b", slashCat.concat("a", "b")); } @@ -144,7 +144,7 @@ public void testBind() throws Exception { .impl(Concatenator.class.getName()) .buildChecked(); - Assert.assertTrue("Should always be static", ctor.isStatic()); + Assertions.assertTrue(ctor.isStatic(), "Should always be static"); intercept(IllegalStateException.class, () -> ctor.bind(null)); @@ -162,9 +162,9 @@ public void testInvoke() throws Exception { intercept(IllegalArgumentException.class, () -> ctor.invoke("a")); - Assert.assertNotNull("Should allow invokeChecked(null, ...)", - ctor.invokeChecked(null)); - Assert.assertNotNull("Should allow invoke(null, ...)", - ctor.invoke(null)); + Assertions.assertNotNull( + ctor.invokeChecked(null), "Should allow invokeChecked(null, ...)"); + Assertions.assertNotNull( + ctor.invoke(null), "Should allow invoke(null, ...)"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java index b774a95f8563b..c205a769eb5e1 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java @@ -21,8 +21,8 @@ import java.util.concurrent.Callable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.apache.hadoop.test.AbstractHadoopTestBase; @@ -78,11 +78,11 @@ public void testFirstImplReturned() throws Exception { .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")); + Assertions.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")); + Assertions.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 +90,11 @@ public void testFirstImplReturned() throws Exception { .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")); + Assertions.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")); + Assertions.assertEquals("a-b-null", cat3.invoke(obj, "a", "b"), + "Should call the 3-arg version null padding"); } @Test @@ -103,14 +103,13 @@ public void testVarArgs() throws Exception { .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"})); + Assertions.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", + Assertions.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 +150,8 @@ public void testNameChange() throws Exception { .impl(Concatenator.class, "concat", String.class, String.class) .buildChecked(); - Assert.assertEquals("Should find 2-arg concat method", - "a-b", cat.invoke(obj, "a", "b")); + Assertions.assertEquals("a-b", cat.invoke(obj, "a", "b"), + "Should find 2-arg concat method"); } @Test @@ -162,8 +161,8 @@ public void testStringClassname() throws Exception { .impl(Concatenator.class.getName(), String.class, String.class) .buildChecked(); - Assert.assertEquals("Should find 2-arg concat method", - "a-b", cat.invoke(obj, "a", "b")); + Assertions.assertEquals("a-b", cat.invoke(obj, "a", "b"), + "Should find 2-arg concat method"); } @Test @@ -179,12 +178,12 @@ public void testHiddenMethod() throws Exception { .hiddenImpl(Concatenator.class, String.class) .buildChecked(); - Assert.assertNotNull("Should find hidden method with hiddenImpl", - changeSep); + Assertions.assertNotNull( + changeSep, "Should find hidden method with hiddenImpl"); changeSep.invokeChecked(obj, "/"); - Assert.assertEquals("Should use separator / instead of -", + Assertions.assertEquals("Should use separator / instead of -", "a/b", obj.concat("a", "b")); } @@ -198,17 +197,17 @@ public void testBoundMethod() throws Exception { 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")); + Assertions.assertEquals("a-b", dashCat.invoke("a", "b"), + "Should use '-' object without passing"); + Assertions.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")); + Assertions.assertEquals("a/b", slashCat.invoke("a", "b"), + "Should use bound object from builder without passing"); } @Test @@ -223,7 +222,7 @@ public void testBindStaticMethod() throws Exception { builder.build(new Concatenator())); final DynMethods.UnboundMethod staticCat = builder.buildChecked(); - Assert.assertTrue("Should be static", staticCat.isStatic()); + Assertions.assertTrue(staticCat.isStatic(), "Should be static"); intercept(IllegalStateException.class, () -> staticCat.bind(new Concatenator())); @@ -235,9 +234,9 @@ public void testStaticMethod() throws Exception { .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"})); + Assertions.assertEquals("abcde", staticCat.invokeChecked( + (Object) new String[]{"a", "b", "c", "d", "e"}), + "Should call varargs static method cat(String...)"); } @Test @@ -250,8 +249,8 @@ public void testNonStaticMethod() throws Exception { intercept(IllegalStateException.class, builder::buildStaticChecked); final DynMethods.UnboundMethod cat2 = builder.buildChecked(); - Assert.assertFalse("concat(String,String) should not be static", - cat2.isStatic()); + Assertions.assertFalse( + cat2.isStatic(), "concat(String,String) should not be static"); intercept(IllegalStateException.class, cat2::asStatic); } @@ -263,12 +262,12 @@ public void testConstructorImpl() throws Exception { .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()); + Assertions.assertTrue( + newConcatenator instanceof DynConstructors.Ctor, "Should find constructor implementation"); + Assertions.assertTrue( + newConcatenator.isStatic(), "Constructor should be a static method"); + Assertions.assertFalse( + newConcatenator.isNoop(), "Constructor should not be NOOP"); // constructors cannot be bound intercept(IllegalStateException.class, () -> @@ -277,11 +276,11 @@ public void testConstructorImpl() throws Exception { builder.build(new Concatenator())); Concatenator concatenator = newConcatenator.asStatic().invoke("*"); - Assert.assertEquals("Should function as a concatenator", + Assertions.assertEquals("Should function as a concatenator", "a*b", concatenator.concat("a", "b")); concatenator = newConcatenator.asStatic().invokeChecked("@"); - Assert.assertEquals("Should function as a concatenator", + Assertions.assertEquals("Should function as a concatenator", "a@b", concatenator.concat("a", "b")); } @@ -292,8 +291,8 @@ public void testConstructorImplAfterFactoryMethod() throws Exception { .ctorImpl(Concatenator.class, String.class) .buildChecked(); - Assert.assertFalse("Should find factory method before constructor method", - newConcatenator instanceof DynConstructors.Ctor); + Assertions.assertFalse( + newConcatenator instanceof DynConstructors.Ctor, "Should find factory method before constructor method"); } @Test @@ -304,17 +303,17 @@ public void testNoop() throws Exception { .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")); + Assertions.assertTrue( + noop.isNoop(), "No implementation found, should return NOOP"); + Assertions.assertNull( + noop.invoke(new Concatenator(), "a"), "NOOP should always return null"); + Assertions.assertNull( + noop.invoke(null, "a"), "NOOP can be called with null"); + Assertions.assertNull( + noop.bind(new Concatenator()).invoke("a"), "NOOP can be bound"); + Assertions.assertNull( + noop.bind(null).invoke("a"), "NOOP can be bound to null"); + Assertions.assertNull( + noop.asStatic().invoke("a"), "NOOP can be static"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java index 186483ed106e4..cf07b1f2ee38c 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestFunctionalIO.java @@ -24,7 +24,7 @@ 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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java index 4d1dae184b7d1..c2ddbc98bcc88 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestLazyReferences.java @@ -24,7 +24,7 @@ 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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java index 4f83b510c37d9..da6e0144c21af 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestRemoteIterators.java @@ -26,7 +26,7 @@ import org.apache.hadoop.util.Preconditions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java index a65658873687c..46b4a0ee56ce6 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java @@ -17,9 +17,9 @@ */ package org.apache.hadoop.util.hash; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; 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 Date: Thu, 6 Feb 2025 20:36:30 +0800 Subject: [PATCH 2/5] HADOOP-19415. Fix CheckStyle & Fix Unit Test. --- .../util/TestApplicationClassLoader.java | 4 +- .../hadoop/util/TestAsyncDiskService.java | 4 +- .../hadoop/util/TestCacheableIPList.java | 51 +++------ .../hadoop/util/TestChunkedArrayList.java | 47 ++++---- .../org/apache/hadoop/util/TestClassUtil.java | 20 ++-- .../org/apache/hadoop/util/TestClasspath.java | 6 +- .../org/apache/hadoop/util/TestConfTest.java | 3 +- .../hadoop/util/TestCpuTimeTracker.java | 12 +- .../apache/hadoop/util/TestCrcComposer.java | 11 +- .../org/apache/hadoop/util/TestCrcUtil.java | 20 ++-- .../apache/hadoop/util/TestDataChecksum.java | 5 +- .../apache/hadoop/util/TestDiskChecker.java | 6 +- .../util/TestDiskCheckerWithDiskIo.java | 16 +-- .../hadoop/util/TestDiskValidatorFactory.java | 12 +- .../apache/hadoop/util/TestDurationInfo.java | 13 ++- .../org/apache/hadoop/util/TestExitUtil.java | 58 +++++----- .../hadoop/util/TestFastNumberFormat.java | 7 +- .../hadoop/util/TestFileBasedIPList.java | 73 +++++-------- .../java/org/apache/hadoop/util/TestGSet.java | 48 ++++---- .../hadoop/util/TestGenericOptionsParser.java | 43 ++++---- .../apache/hadoop/util/TestGenericsUtil.java | 34 +++--- .../hadoop/util/TestHostsFileReader.java | 36 +++--- .../hadoop/util/TestHttpExceptionUtils.java | 79 +++++++------- .../hadoop/util/TestIdentityHashStore.java | 50 +++++---- .../apache/hadoop/util/TestIndexedSort.java | 32 +++--- .../hadoop/util/TestInstrumentedLock.java | 28 ++--- .../util/TestInstrumentedReadWriteLock.java | 30 +++-- .../org/apache/hadoop/util/TestJarFinder.java | 12 +- .../hadoop/util/TestLightWeightCache.java | 30 ++--- .../hadoop/util/TestLightWeightGSet.java | 8 +- .../apache/hadoop/util/TestLineReader.java | 25 +++-- .../org/apache/hadoop/util/TestLists.java | 40 +++---- .../apache/hadoop/util/TestMachineList.java | 10 +- .../hadoop/util/TestNativeCodeLoader.java | 3 +- .../apache/hadoop/util/TestNativeCrc32.java | 103 +++++++++++------- 35 files changed, 499 insertions(+), 480 deletions(-) diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java index e0b439bbd1d50..f62dadd187c70 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java @@ -130,8 +130,8 @@ public void testGetResource() throws IOException { ClassLoader appClassloader = new ApplicationClassLoader( new URL[] { testJar }, currentClassLoader, null); - assertNull( - currentClassLoader.getResourceAsStream("resource.txt"), "Resource should be null for current classloader"); + assertNull(currentClassLoader.getResourceAsStream("resource.txt"), + "Resource should be null for current classloader"); InputStream in = appClassloader.getResourceAsStream("resource.txt"); assertNotNull(in, "Resource should not be null for app classloader"); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java index 4f9f5267413b2..7b0aaa357aa65 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestAsyncDiskService.java @@ -18,7 +18,9 @@ package org.apache.hadoop.util; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java index e6fb8d1ddd597..95400bb7f2734 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java @@ -20,7 +20,8 @@ import java.io.IOException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestCacheableIPList { @@ -44,10 +45,8 @@ public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc CacheableIPList cipl = new CacheableIPList( new FileBasedIPList("ips.txt"),100); - 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"); + 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 void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2); Thread.sleep(101); - 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"); + 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 void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte CacheableIPList cipl = new CacheableIPList( new FileBasedIPList("ips.txt"),100); - 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"); + 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 void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2); Thread.sleep(1005); - 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"); + 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 void testAddWithRefresh() throws IOException, InterruptedException { CacheableIPList cipl = new CacheableIPList( new FileBasedIPList("ips.txt"),100); - 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"); + 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 void testAddWithRefresh() throws IOException, InterruptedException { TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2); cipl.refresh(); - 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"); + 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 void testRemovalWithRefresh() throws IOException, InterruptedException { CacheableIPList cipl = new CacheableIPList( new FileBasedIPList("ips.txt"),100); - 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"); + 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 void testRemovalWithRefresh() throws IOException, InterruptedException { TestFileBasedIPList.createFileWithEntries ("ips.txt", ips2); cipl.refresh(); - 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"); + 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"); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java index aa79c5cc57660..e97b13b035c3d 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestChunkedArrayList.java @@ -17,13 +17,14 @@ */ package org.apache.hadoop.util; -import static org.junit.jupiter.api.Assertions.*; +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.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestChunkedArrayList { @@ -103,41 +104,41 @@ public void testRemovals() throws Exception { // Iterate through all list elements. Iterator iter = list.iterator(); for (int i = 0; i < NUM_ELEMS; i++) { - Assertions.assertTrue(iter.hasNext()); + assertTrue(iter.hasNext()); Integer val = iter.next(); - Assertions.assertEquals(Integer.valueOf(i), val); + assertEquals(Integer.valueOf(i), val); } - Assertions.assertFalse(iter.hasNext()); - Assertions.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++) { - Assertions.assertTrue(iter.hasNext()); + assertTrue(iter.hasNext()); Integer val = iter.next(); - Assertions.assertEquals(Integer.valueOf(i), val); + assertEquals(Integer.valueOf(i), val); if (i % 2 == 0) { iter.remove(); } } - Assertions.assertFalse(iter.hasNext()); - Assertions.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++) { - Assertions.assertTrue(iter.hasNext()); + assertTrue(iter.hasNext()); Integer val = iter.next(); - Assertions.assertEquals(Integer.valueOf(1 + (2 * i)), val); + assertEquals(Integer.valueOf(1 + (2 * i)), val); iter.remove(); } - Assertions.assertFalse(iter.hasNext()); + assertFalse(iter.hasNext()); // Check that list is now empty. - Assertions.assertEquals(0, list.size()); - Assertions.assertTrue(list.isEmpty()); + assertEquals(0, list.size()); + assertTrue(list.isEmpty()); iter = list.iterator(); - Assertions.assertFalse(iter.hasNext()); + assertFalse(iter.hasNext()); } @Test @@ -148,15 +149,15 @@ public void testGet() throws Exception { list.add(i); } - Assertions.assertEquals(Integer.valueOf(100), list.get(100)); - Assertions.assertEquals(Integer.valueOf(1000), list.get(1000)); - Assertions.assertEquals(Integer.valueOf(10000), list.get(10000)); - Assertions.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 iter = list.iterator(); iter.next(); iter.remove(); - Assertions.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 void testGet() throws Exception { } iter.remove(); - Assertions.assertEquals(Integer.valueOf(502), list.get(500)); - Assertions.assertEquals(Integer.valueOf(602), list.get(600)); + assertEquals(Integer.valueOf(502), list.get(500)); + assertEquals(Integer.valueOf(602), list.get(600)); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java index b6774b0e28f47..8942d0ff82d7c 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClassUtil.java @@ -26,23 +26,22 @@ 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(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"); } @@ -51,17 +50,14 @@ public void testFindContainingJar() { @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"); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java index 6b2cd68bcd2b9..9fbab67da184e 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestClasspath.java +++ b/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.jupiter.api.Assertions.*; +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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java index 5982e5e17661f..d1867e5bc80d4 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfTest.java @@ -18,7 +18,8 @@ package org.apache.hadoop.util; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.util.List; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java index 5340b41313f1f..7c3564c765915 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCpuTimeTracker.java @@ -29,24 +29,18 @@ public void test() throws InterruptedException { BigInteger.valueOf(100), System.currentTimeMillis()); float val1 = tracker.getCpuTrackerUsagePercent(); - assertTrue( - - val1 == -1.0, "Not invalid CPU usage"); + assertTrue(val1 == -1.0, "Not invalid CPU usage"); Thread.sleep(1000); tracker.updateElapsedJiffies( BigInteger.valueOf(200), System.currentTimeMillis()); float val2 = tracker.getCpuTrackerUsagePercent(); - assertTrue( - - val2 > 0, "Not positive CPU usage"); + assertTrue(val2 > 0, "Not positive CPU usage"); Thread.sleep(1000); tracker.updateElapsedJiffies( BigInteger.valueOf(0), System.currentTimeMillis()); float val3 = tracker.getCpuTrackerUsagePercent(); - assertTrue( - - val3 == 0.0, "Not positive CPU usage"); + assertTrue(val3 == 0.0, "Not positive CPU usage"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java index 40c0e311525b8..a5c11f3bd6a0c 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcComposer.java @@ -22,22 +22,21 @@ 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.jupiter.api.BeforeEach; -import org.junit.Rule; import org.junit.jupiter.api.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.Timeout; -import static org.junit.jupiter.api.Assertions.*; +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); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java index b1b22fcb7fe93..85ccb9b59aa1d 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCrcUtil.java @@ -19,21 +19,18 @@ 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.jupiter.api.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.Timeout; -import static org.junit.jupiter.api.Assertions.*; +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 @@ private static void doTestComposeCrc( compositeCrc = CrcUtil.compose( compositeCrc, partialCrc, partialChunkSize, crcPolynomial); } - 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)); + 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)); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java index d877b4cada3bc..d6fad9e250f8f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java @@ -24,7 +24,10 @@ import org.apache.hadoop.fs.ChecksumException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +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 { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java index 15a08a6c9bab5..f03dd72a813c9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskChecker.java @@ -25,9 +25,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import static org.junit.jupiter.api.Assertions.*; -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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java index 0811a98c37ad8..92d4268a38e12 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java @@ -20,9 +20,8 @@ import org.apache.hadoop.util.DiskChecker.DiskErrorException; import org.apache.hadoop.util.DiskChecker.FileIoProvider; -import org.junit.Rule; import org.junit.jupiter.api.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.Timeout; import java.io.File; import java.io.FileNotFoundException; @@ -41,9 +40,8 @@ * 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. @@ -98,15 +96,13 @@ public void testDiskIoFileNaming() { 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.toString().matches("^.*\\.[0-9]+$"), "File name does not match expected pattern: " + file); + 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( - - guidFile.toString().matches("^.*\\.[A-Za-z0-9-]+$"), "File name does not match expected pattern: " + guidFile); + assertTrue(guidFile.toString().matches("^.*\\.[A-Za-z0-9-]+$"), + "File name does not match expected pattern: " + guidFile); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java index bfb1ef44b4ab7..c82210b71ca73 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskValidatorFactory.java @@ -19,9 +19,11 @@ import org.junit.jupiter.api.Test; -import org.apache.hadoop.util.DiskChecker.DiskErrorException; +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 static org.junit.jupiter.api.Assertions.*; +import org.apache.hadoop.util.DiskChecker.DiskErrorException; /** * The class to test DiskValidatorFactory. @@ -39,8 +41,8 @@ public void testGetInstance() throws DiskErrorException { DiskValidator diskValidator = DiskValidatorFactory.getInstance("basic"); assertNotNull(diskValidator, "Fail to get the instance."); - assertEquals( - diskValidator.getClass(), BasicDiskValidator.class, "Fail to create the correct instance."); + assertEquals(diskValidator.getClass(), BasicDiskValidator.class, + "Fail to create the correct instance."); assertNotNull(DiskValidatorFactory.INSTANCES. get(BasicDiskValidator.class), "Fail to cache the object"); @@ -53,7 +55,7 @@ public void testGetInstance() throws DiskErrorException { */ @Test public void testGetInstanceOfNonExistClass() throws DiskErrorException { - assertThrows(DiskErrorException.class, ()->{ + assertThrows(DiskErrorException.class, () -> { DiskValidatorFactory.getInstance("non-exist"); }); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java index 7bed6ca6ed8ea..26e81756bfb33 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDurationInfo.java @@ -17,12 +17,13 @@ */ package org.apache.hadoop.util; -import org.junit.jupiter.api.Assertions; 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. @@ -33,17 +34,17 @@ public class TestDurationInfo { @Test public void testDurationInfoCreation() throws Exception { DurationInfo info = new DurationInfo(log, "test"); - Assertions.assertTrue(info.value() >= 0); + assertTrue(info.value() >= 0); Thread.sleep(1000); info.finished(); - Assertions.assertTrue(info.value() > 0); + assertTrue(info.value() > 0); info = new DurationInfo(log, true, "test format %s", "value"); - Assertions.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"); - Assertions.assertEquals("test format value: duration 0:00.000s", + assertEquals("test format value: duration 0:00.000s", info.toString()); } @@ -53,7 +54,7 @@ public void testDurationInfoWithMultipleClose() throws Exception { Thread.sleep(1000); info.close(); info.close(); - Assertions.assertTrue(info.value() > 0); + assertTrue(info.value() > 0); } @Test diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java index 034df78c6a923..208a57289f7a4 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestExitUtil.java @@ -53,35 +53,38 @@ public void testGetSetExitExceptions() throws Throwable { 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(), "ExitUtil.terminateCalled initial value should be false"); - assertNull( - ExitUtil.getFirstExitException(), "ExitUtil.getFirstExitException initial value should be null"); + 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(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"); + 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(ee2, ee, "ExitUtil.terminate should have rethrown its HaltException argument but it " + 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"); + 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(ee1, ExitUtil.getFirstExitException(), "ExitUtil.terminate when called twice should only remember 1st call's " + 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(), "ExitUtil.terminateCalled should be false after " + "ExitUtil.resetFirstExitException call"); - assertNull(ExitUtil.getFirstExitException(), "ExitUtil.getFirstExitException should be null after " + assertNull(ExitUtil.getFirstExitException(), + "ExitUtil.getFirstExitException should be null after " + "ExitUtil.resetFirstExitException call"); } @@ -94,34 +97,35 @@ public void testGetSetHaltExceptions() throws Throwable { HaltException he2 = new HaltException(2, "TestExitUtil forged 2nd HaltException"); // check proper initial settings - assertFalse( - ExitUtil.haltCalled(), "ExitUtil.haltCalled initial value should be false"); - assertNull( - ExitUtil.getFirstHaltException(), "ExitUtil.getFirstHaltException initial value should be null"); + 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(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"); + 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(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"); + + "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(), "ExitUtil.haltCalled should be false after " + "ExitUtil.resetFirstHaltException call"); - assertNull(ExitUtil.getFirstHaltException(), "ExitUtil.getFirstHaltException should be null after " + assertNull(ExitUtil.getFirstHaltException(), + "ExitUtil.getFirstHaltException should be null after " + "ExitUtil.resetFirstHaltException call"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java index c04cfc5150162..fafdf995f1aab 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java @@ -17,12 +17,13 @@ */ package org.apache.hadoop.util; -import org.junit.jupiter.api.Assertions; 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 */ @@ -41,8 +42,8 @@ public void testLongWithPadding() throws Exception { StringBuilder sb = new StringBuilder(); FastNumberFormat.format(sb, l, MIN_DIGITS); String fastNumberStr = sb.toString(); - Assertions.assertEquals( - numberFormat.format(l), fastNumberStr, "Number formats should be equal"); + assertEquals( + numberFormat.format(l), fastNumberStr, "Number formats should be equal"); } } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java index 59b8a3bc1b9a9..52aa7fa1eff75 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFileBasedIPList.java @@ -24,7 +24,10 @@ import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; + +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 { @@ -47,23 +50,15 @@ public void testSubnetsAndIPs() throws IOException { IPList ipList = new FileBasedIPList("ips.txt"); - 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"); + 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 void testNullIP() throws IOException { IPList ipList = new FileBasedIPList("ips.txt"); - assertFalse ( - ipList.isIn(null), "Null Ip is in the list"); + assertFalse(ipList.isIn(null), "Null Ip is in the list"); } /** @@ -98,25 +92,17 @@ public void testWithMultipleSubnetAndIPs() throws IOException { IPList ipList = new FileBasedIPList("ips.txt"); - 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"); + 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 void testFileNotSpecified() { IPList ipl = new FileBasedIPList(null); - assertFalse( - ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); + assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); } /** @@ -143,8 +128,7 @@ public void testFileMissing() { IPList ipl = new FileBasedIPList("missingips.txt"); - assertFalse( - ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); + assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); } /** @@ -159,8 +143,7 @@ public void testWithEmptyList() throws IOException { createFileWithEntries ("ips.txt", ips); IPList ipl = new FileBasedIPList("ips.txt"); - assertFalse( - ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); + assertFalse(ipl.isIn("110.113.221.222"), "110.113.221.222 is in the list"); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java index e034ddb2fff95..c36b837d22c2f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java @@ -23,10 +23,12 @@ import java.util.Random; import org.apache.hadoop.HadoopIllegalArgumentException; -import org.junit.jupiter.api.Assertions; 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(); @@ -55,7 +57,7 @@ private void testExceptionCases(boolean resizable) { try { //test contains with a null element gset.contains(null); - Assertions.fail(); + fail(); } catch(NullPointerException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -68,7 +70,7 @@ private void testExceptionCases(boolean resizable) { try { //test get with a null element gset.get(null); - Assertions.fail(); + fail(); } catch(NullPointerException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -81,14 +83,14 @@ private void testExceptionCases(boolean resizable) { try { //test put with a null element gset.put(null); - Assertions.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); - Assertions.fail(); + fail(); } catch(IllegalArgumentException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -119,7 +121,7 @@ private void testExceptionCases(boolean resizable) { gset.remove(data[1]); } } - Assertions.fail(); + fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -134,7 +136,7 @@ private void testExceptionCases(boolean resizable) { gset.put(data[0]); } } - Assertions.fail(); + fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -149,7 +151,7 @@ private void testExceptionCases(boolean resizable) { gset.put(data[3]); } } - Assertions.fail(); + fail(); } catch(ConcurrentModificationException e) { LightWeightGSet.LOG.info("GOOD: getting " + e, e); } @@ -263,7 +265,7 @@ private static void check(final GSetTestCase test) { for(int i = 0; i < test.data.size(); i++) { test.remove(test.data.get(i)); } - Assertions.assertEquals(0, test.gset.size()); + assertEquals(0, test.gset.size()); println("DONE " + test.stat()); //check remove and add again @@ -315,12 +317,12 @@ private static class GSetTestCase implements GSet { gset = resizable ? new LightWeightResizableGSet() : new LightWeightGSet(tablelength); - Assertions.assertEquals(0, gset.size()); + assertEquals(0, gset.size()); } private boolean containsTest(IntElement key) { final boolean e = expected.contains(key); - Assertions.assertEquals(e, gset.contains(key)); + assertEquals(e, gset.contains(key)); return e; } @Override @@ -332,7 +334,7 @@ public boolean contains(IntElement key) { private IntElement getTest(IntElement key) { final IntElement e = expected.get(key); - Assertions.assertEquals(e.id, gset.get(key).id); + assertEquals(e.id, gset.get(key).id); return e; } @Override @@ -345,9 +347,9 @@ public IntElement get(IntElement key) { private IntElement putTest(IntElement element) { final IntElement e = expected.put(element); if (e == null) { - Assertions.assertEquals(null, gset.put(element)); + assertEquals(null, gset.put(element)); } else { - Assertions.assertEquals(e.id, gset.put(element).id); + assertEquals(e.id, gset.put(element).id); } return e; } @@ -361,9 +363,9 @@ public IntElement put(IntElement element) { private IntElement removeTest(IntElement key) { final IntElement e = expected.remove(key); if (e == null) { - Assertions.assertEquals(null, gset.remove(key)); + assertEquals(null, gset.remove(key)); } else { - Assertions.assertEquals(e.id, gset.remove(key).id); + assertEquals(e.id, gset.remove(key).id); } return e; } @@ -376,7 +378,7 @@ public IntElement remove(IntElement key) { private int sizeTest() { final int s = expected.size(); - Assertions.assertEquals(s, gset.size()); + assertEquals(s, gset.size()); return s; } @Override @@ -429,7 +431,7 @@ String stat() { public void clear() { expected.clear(); gset.clear(); - Assertions.assertEquals(0, size()); + assertEquals(0, size()); } @Override @@ -519,7 +521,7 @@ public void testComputeCapacityNegativePercent() { */ @Test public void testComputeCapacityInvalidPercent() { - assertThrows(HadoopIllegalArgumentException.class, ()->{ + assertThrows(HadoopIllegalArgumentException.class, () -> { LightWeightGSet.computeCapacity(1024, 101.0, "testMap"); }); } @@ -530,7 +532,7 @@ public void testComputeCapacityInvalidPercent() { */ @Test public void testComputeCapacityInvalidMemory() { - assertThrows(HadoopIllegalArgumentException.class,()->{ + assertThrows(HadoopIllegalArgumentException.class, () -> { LightWeightGSet.computeCapacity(-1, 50.0, "testMap"); }); } @@ -553,16 +555,16 @@ private static void testCapacity(long maxMemory, double percent) { LightWeightGSet.LOG.info("Validating - total memory " + maxMemory + " percent " + percent + " returned capacity " + capacity); // Returned capacity is zero or power of two - Assertions.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) { - Assertions.assertTrue(getPercent(maxMemory, capacity * 2) > percent); + assertTrue(getPercent(maxMemory, capacity * 2) > percent); } else { - Assertions.assertTrue(getPercent(maxMemory, capacity / 2) < percent); + assertTrue(getPercent(maxMemory, capacity / 2) < percent); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java index f203ed9d6f962..3e8b5cebecb68 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericOptionsParser.java @@ -70,8 +70,8 @@ public void testFilesOption() throws Exception { new GenericOptionsParser(conf, args); String files = conf.get("tmpfiles"); assertNotNull(files, "files is null"); - assertEquals("files option does not match", - localFs.makeQualified(tmpPath).toString(), files); + assertEquals(localFs.makeQualified(tmpPath).toString(), files, + "files option does not match"); // pass file as uri Configuration conf1 = new Configuration(); @@ -81,8 +81,8 @@ public void testFilesOption() throws Exception { new GenericOptionsParser(conf1, args); files = conf1.get("tmpfiles"); assertNotNull(files, "files is null"); - assertEquals("files option does not match", - localFs.makeQualified(new Path(tmpURI)).toString(), files); + assertEquals(localFs.makeQualified(new Path(tmpURI)).toString(), files, + "files option does not match"); // pass a file that does not exist. // GenericOptionParser should throw exception @@ -96,8 +96,8 @@ public void testFilesOption() throws Exception { th = e; } assertNotNull(th, "throwable is null"); - assertTrue( - th instanceof FileNotFoundException, "FileNotFoundException is not thrown"); + assertTrue(th instanceof FileNotFoundException, + "FileNotFoundException is not thrown"); files = conf2.get("tmpfiles"); assertNull(files, "files is not null"); } @@ -117,16 +117,16 @@ public void testLibjarsOption() throws Exception { new GenericOptionsParser(conf, args); String libjars = conf.get("tmpjars"); assertNotNull(libjars, "libjars is null"); - assertEquals("libjars does not match", - localFs.makeQualified(tmpJarPath).toString(), libjars); + 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, "libjars is null"); - assertEquals("libjars does not match", - localFs.makeQualified(tmpJarPath).toString(), libjars); + assertEquals(localFs.makeQualified(tmpJarPath).toString(), libjars, + "libjars does not match"); } /** @@ -210,8 +210,8 @@ public void testCreateWithOptions() throws Exception { 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,10 +223,10 @@ public void testConfWithMultipleOpts() throws Exception { 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"); } @BeforeEach @@ -270,8 +270,8 @@ public void testTokenCacheOption() throws IOException { th = e; } assertNotNull(th); - assertTrue( - th instanceof FileNotFoundException, "FileNotFoundException is not thrown"); + assertTrue(th instanceof FileNotFoundException, + "FileNotFoundException is not thrown"); // create file Path tmpPath = localFs.makeQualified(new Path(tmpFile.toString())); @@ -285,7 +285,7 @@ public void testTokenCacheOption() throws IOException { new GenericOptionsParser(conf, args); String fileName = conf.get("mapreduce.job.credentials.binary"); assertNotNull(fileName, "files is null"); - assertEquals("files option does not match", tmpPath.toString(), fileName); + assertEquals(tmpPath.toString(), fileName, "files option does not match"); Credentials ugiCreds = UserGroupInformation.getCurrentUser().getCredentials(); @@ -379,9 +379,8 @@ private void assertDOptionParsing(String[] args, assertEquals(entry.getValue(), conf.get(entry.getKey())); } - assertArrayEquals( - - expectedRemainingArgs, remainingArgs, Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs)); + assertArrayEquals(expectedRemainingArgs, remainingArgs, + Arrays.toString(remainingArgs) + Arrays.toString(expectedRemainingArgs)); } /** Test passing null as args. Some classes still call diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java index 6aa6b549d5150..0cf6ac51f9dc3 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGenericsUtil.java @@ -22,7 +22,10 @@ import java.util.List; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +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 void testToArray() { Integer[] arr = GenericsUtil.toArray(list); for (int i = 0; i < arr.length; i++) { - assertEquals( - - list.get(i), arr[i], "Array has identical elements as input list"); + assertEquals(list.get(i), arr[i], + "Array has identical elements as input list"); } } @@ -66,8 +68,8 @@ public void testWithEmptyList2() { //this method should not throw IndexOutOfBoundsException String[] arr = GenericsUtil.toArray(String.class, list); - assertEquals( - 0, arr.length, "Assert list creation w/ no elements results in length 0"); + assertEquals(0, arr.length, + "Assert list creation w/ no elements results in length 0"); } /** This class uses generics */ @@ -117,9 +119,8 @@ public void testGenericOptionsParser() throws Exception { 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 void testGetClass() { //test with Integer Integer x = new Integer(42); Class c = GenericsUtil.getClass(x); - assertEquals( - Integer.class, c, "Correct generic type is acquired from object"); + assertEquals(Integer.class, c, + "Correct generic type is acquired from object"); //test with GenericClass GenericClass testSubject = new GenericClass(); Class> c2 = GenericsUtil.getClass(testSubject); - assertEquals( - GenericClass.class, c2, "Inner generics are acquired from object."); + assertEquals(GenericClass.class, c2, + "Inner generics are acquired from object."); } @Test public void testIsLog4jLogger() throws Exception { - assertFalse(GenericsUtil.isLog4jLogger((Class) null), "False if clazz is null"); - assertTrue( - GenericsUtil.isLog4jLogger(TestGenericsUtil.class), "The implementation is Log4j"); + assertFalse(GenericsUtil.isLog4jLogger((Class) null), + "False if clazz is null"); + assertTrue(GenericsUtil.isLog4jLogger(TestGenericsUtil.class), + "The implementation is Log4j"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java index 0c2e357f4ef7f..ce7d7c8ce3035 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java @@ -30,7 +30,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import static org.junit.jupiter.api.Assertions.*; +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 @@ -379,29 +384,28 @@ public void testLazyRefresh() throws IOException { HostDetails details = hfp.getHostDetails(); HostDetails lazyDetails = hfp.getLazyLoadedHostDetails(); - 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"); + 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(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"); + 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 public void testFinishRefreshWithoutLazyRefresh() throws IOException { - assertThrows(IllegalArgumentException.class, () -> { + assertThrows(IllegalStateException.class, () -> { FileWriter efw = new FileWriter(excludesFile); FileWriter ifw = new FileWriter(includesFile); efw.close(); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java index db4ea1a6bdad5..f3f0e43b39419 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHttpExceptionUtils.java @@ -19,9 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hadoop.test.LambdaTestUtils; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; @@ -37,27 +35,34 @@ 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); - Assertions.assertEquals(IOException.class.getName(), + assertEquals(IOException.class.getName(), json.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON)); - Assertions.assertEquals(IOException.class.getSimpleName(), + assertEquals(IOException.class.getSimpleName(), json.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON)); - Assertions.assertEquals("Hello IOEX", + assertEquals("Hello IOEX", json.get(HttpExceptionUtils.ERROR_MESSAGE_JSON)); } @@ -66,32 +71,32 @@ public void testCreateJerseyException() throws IOException { Exception ex = new IOException("Hello IOEX"); Response response = HttpExceptionUtils.createJerseyExceptionResponse( Response.Status.INTERNAL_SERVER_ERROR, ex); - Assertions.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); - Assertions.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); - Assertions.assertEquals(IOException.class.getName(), + assertEquals(IOException.class.getName(), entity.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON)); - Assertions.assertEquals(IOException.class.getSimpleName(), + assertEquals(IOException.class.getSimpleName(), entity.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON)); - Assertions.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 void testValidateResponseFailNoErrorMessage() throws Exception { 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 void testValidateResponseJsonErrorKnownException() throws Exception { 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 void testValidateResponseJsonErrorUnknownException() 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 void testValidateResponseJsonErrorNonException() throws Exception { 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)); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java index 7b64941edd5b9..487512aa9a752 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java @@ -21,8 +21,6 @@ import java.util.LinkedList; import java.util.List; -import org.junit.jupiter.api.Assertions; - import org.apache.hadoop.util.IdentityHashStore; import org.apache.hadoop.util.IdentityHashStore.Visitor; import org.junit.jupiter.api.Test; @@ -30,6 +28,11 @@ 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()); @@ -64,23 +67,23 @@ public void testStartingWithZeroCapacity() { store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assertions.fail("found key " + k + " in empty IdentityHashStore."); + fail("found key " + k + " in empty IdentityHashStore."); } }); - Assertions.assertTrue(store.isEmpty()); + assertTrue(store.isEmpty()); final Key key1 = new Key("key1"); Integer value1 = new Integer(100); store.put(key1, value1); - Assertions.assertTrue(!store.isEmpty()); - Assertions.assertEquals(value1, store.get(key1)); + assertTrue(!store.isEmpty()); + assertEquals(value1, store.get(key1)); store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assertions.assertEquals(key1, k); + assertEquals(key1, k); } }); - Assertions.assertEquals(value1, store.remove(key1)); - Assertions.assertTrue(store.isEmpty()); + assertEquals(value1, store.remove(key1)); + assertTrue(store.isEmpty()); } @Test @@ -91,10 +94,10 @@ public void testDuplicateInserts() { store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assertions.fail("found key " + k + " in empty IdentityHashStore."); + fail("found key " + k + " in empty IdentityHashStore."); } }); - Assertions.assertTrue(store.isEmpty()); + assertTrue(store.isEmpty()); Key key1 = new Key("key1"); Integer value1 = new Integer(100); Integer value2 = new Integer(200); @@ -103,10 +106,10 @@ public void accept(Key k, Integer v) { Key equalToKey1 = new Key("key1"); // IdentityHashStore compares by object equality, not equals() - Assertions.assertNull(store.get(equalToKey1)); + assertNull(store.get(equalToKey1)); - Assertions.assertTrue(!store.isEmpty()); - Assertions.assertEquals(value1, store.get(key1)); + assertTrue(!store.isEmpty()); + assertEquals(value1, store.get(key1)); store.put(key1, value2); store.put(key1, value3); final List allValues = new LinkedList(); @@ -116,13 +119,13 @@ public void accept(Key k, Integer v) { allValues.add(v); } }); - Assertions.assertEquals(3, allValues.size()); + assertEquals(3, allValues.size()); for (int i = 0; i < 3; i++) { Integer value = store.remove(key1); - Assertions.assertTrue(allValues.remove(value)); + assertTrue(allValues.remove(value)); } - Assertions.assertNull(store.remove(key1)); - Assertions.assertTrue(store.isEmpty()); + assertNull(store.remove(key1)); + assertTrue(store.isEmpty()); } @Test @@ -142,23 +145,22 @@ public void testAdditionsAndRemovals() { store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assertions.assertTrue(keys.contains(k)); + assertTrue(keys.contains(k)); } }); for (int i = 0; i < NUM_KEYS; i++) { - Assertions.assertEquals(Integer.valueOf(i), + assertEquals(Integer.valueOf(i), store.remove(keys.get(i))); } store.visitAll(new Visitor() { @Override public void accept(Key k, Integer v) { - Assertions.fail("expected all entries to be removed"); + fail("expected all entries to be removed"); } }); - Assertions.assertTrue( - store.isEmpty(), "expected the store to be " + + assertTrue(store.isEmpty(), "expected the store to be " + "empty, but found " + store.numElements() + " elements."); - Assertions.assertEquals(1024, store.capacity()); + assertEquals(1024, store.capacity()); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java index 69828b958bb83..36f79a9ed4813 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java @@ -22,7 +22,7 @@ import java.util.Random; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; @@ -38,7 +38,8 @@ public void sortAllEqual(IndexedSorter sorter) throws Exception { SampleSortable s = new SampleSortable(values); sorter.sort(s, 0, SAMPLE); int[] check = s.getSorted(); - assertTrue(Arrays.equals(values, check), Arrays.toString(values) + "\ndoesn't match\n" + + 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(); @@ -54,7 +55,8 @@ public void sortAllEqual(IndexedSorter sorter) throws Exception { Arrays.sort(values); assertTrue(check[0] == 9); assertTrue(check[SAMPLE - 1] == 11); - assertTrue(Arrays.equals(values, check), Arrays.toString(values) + "\ndoesn't match\n" + + assertTrue(Arrays.equals(values, check), + Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check)); } @@ -73,7 +75,8 @@ public void sortSorted(IndexedSorter sorter) throws Exception { SampleSortable s = new SampleSortable(values); sorter.sort(s, 0, SAMPLE); int[] check = s.getSorted(); - assertTrue(Arrays.equals(values, check), Arrays.toString(values) + "\ndoesn't match\n" + + assertTrue(Arrays.equals(values, check), + Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check)); } @@ -86,7 +89,8 @@ public void sortSequential(IndexedSorter sorter) throws Exception { SampleSortable s = new SampleSortable(values); sorter.sort(s, 0, SAMPLE); int[] check = s.getSorted(); - assertTrue(Arrays.equals(values, check), Arrays.toString(values) + "\ndoesn't match\n" + + assertTrue(Arrays.equals(values, check), + Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check)); } @@ -96,7 +100,8 @@ public void sortSingleRecord(IndexedSorter sorter) throws Exception { int[] values = s.getValues(); sorter.sort(s, 0, SAMPLE); int[] check = s.getSorted(); - assertTrue(Arrays.equals(values, check), Arrays.toString(values) + "\ndoesn't match\n" + + assertTrue(Arrays.equals(values, check), + Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check)); } @@ -110,8 +115,8 @@ public void sortRandom(IndexedSorter sorter) throws Exception { Arrays.sort(values); sorter.sort(s, 0, SAMPLE); int[] check = s.getSorted(); - assertTrue( - Arrays.equals(values, check), "seed: " + seed + "\ndoesn't match\n"); + assertTrue(Arrays.equals(values, check), + "seed: " + seed + "\ndoesn't match\n"); } public void sortWritable(IndexedSorter sorter) throws Exception { @@ -124,8 +129,8 @@ public void sortWritable(IndexedSorter sorter) throws Exception { Arrays.sort(values); sorter.sort(s, 0, SAMPLE); String[] check = s.getSorted(); - assertTrue( - Arrays.equals(values, check), "seed: " + seed + "\ndoesn't match"); + assertTrue(Arrays.equals(values, check), + "seed: " + seed + "\ndoesn't match"); } @@ -267,15 +272,14 @@ public MeasuredSortable(IndexedSortable s, int maxcmp, int maxswp) { @Override public int compare(int i, int j) { - assertTrue( - ++comparisions < maxcmp, "Expected fewer than " + maxcmp + " comparisons"); + assertTrue(++comparisions < maxcmp, + "Expected fewer than " + maxcmp + " comparisons"); return s.compare(i, j); } @Override public void swap(int i, int j) { - assertTrue( - ++swaps < maxswp, "Expected fewer than " + maxswp + " swaps"); + assertTrue(++swaps < maxswp, "Expected fewer than " + maxswp + " swaps"); s.swap(i, j); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java index a972b80a057e4..fb9e773c7d06e 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedLock.java @@ -23,14 +23,16 @@ 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.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import org.junit.rules.TestName; -import static org.mockito.Mockito.*; -import static org.junit.jupiter.api.Assertions.*; +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. @@ -39,16 +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(value = 10) - public void testMultipleThread() throws Exception { - String testname = name.getMethodName(); + public void testMultipleThread(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); InstrumentedLock lock = new InstrumentedLock(testname, LOG, 0, 300); lock.lock(); try { @@ -71,8 +71,8 @@ public void run() { */ @Test @Timeout(value = 10) - public void testTryWithResourceSyntax() throws Exception { - String testname = name.getMethodName(); + public void testTryWithResourceSyntax(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final AtomicReference lockThread = new AtomicReference<>(null); Lock lock = new InstrumentedLock(testname, LOG, 0, 300) { @Override @@ -110,8 +110,8 @@ public void run() { */ @Test @Timeout(value = 10) - public void testLockLongHoldingReport() throws Exception { - String testname = name.getMethodName(); + public void testLockLongHoldingReport(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override @@ -178,8 +178,8 @@ void logWarning(long lockHeldTime, SuppressedSnapshot stats) { */ @Test @Timeout(value = 10) - public void testLockLongWaitReport() throws Exception { - String testname = name.getMethodName(); + public void testLockLongWaitReport(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java index a0138bb88a397..6bb5d08e154df 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestInstrumentedReadWriteLock.java @@ -24,10 +24,9 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.junit.Rule; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; -import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,17 +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(value = 10) - public void testWriteLock() throws Exception { - String testname = name.getMethodName(); + public void testWriteLock(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final ThreadLocal locked = new ThreadLocal(); locked.set(Boolean.FALSE); InstrumentedReadWriteLock readWriteLock = new InstrumentedReadWriteLock( @@ -99,8 +95,8 @@ public void run() { */ @Test @Timeout(value = 10) - public void testReadLock() throws Exception { - String testname = name.getMethodName(); + 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( @@ -134,8 +130,8 @@ public void run() { */ @Test @Timeout(value = 10) - public void testReadLockLongHoldingReport() throws Exception { - String testname = name.getMethodName(); + public void testReadLockLongHoldingReport(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override @@ -190,8 +186,8 @@ protected void logWarning( */ @Test @Timeout(value = 10) - public void testWriteLockLongHoldingReport() throws Exception { - String testname = name.getMethodName(); + public void testWriteLockLongHoldingReport(TestInfo testInfo) throws Exception { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override @@ -245,8 +241,8 @@ protected void logWarning(long lockHeldTime, SuppressedSnapshot stats) { */ @Test @Timeout(value = 10) - public void testWriteLockLongHoldingReportWithReentrant() { - String testname = name.getMethodName(); + public void testWriteLockLongHoldingReportWithReentrant(TestInfo testInfo) { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override @@ -306,8 +302,8 @@ protected void logWarning(long lockHeldTime, SuppressedSnapshot stats) { */ @Test @Timeout(value = 10) - public void testReadLockLongHoldingReportWithReentrant() { - String testname = name.getMethodName(); + public void testReadLockLongHoldingReportWithReentrant(TestInfo testInfo) { + String testname = testInfo.getDisplayName(); final AtomicLong time = new AtomicLong(0); Timer mclock = new Timer() { @Override diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java index a6d1a926def25..09b6d05b2fb45 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestJarFinder.java @@ -19,7 +19,6 @@ package org.apache.hadoop.util; import org.apache.hadoop.test.GenericTestUtils; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; @@ -37,6 +36,9 @@ 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 void testJar() throws Exception { //picking a class that is for sure in a JAR in the classpath String jar = JarFinder.getJar(LoggerFactory.class); - Assertions.assertTrue(new File(jar).exists()); + assertTrue(new File(jar).exists()); } private static void delete(File file) throws IOException { @@ -75,7 +77,7 @@ public void testExpandedClasspath() throws Exception { //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); - Assertions.assertTrue(new File(jar).exists()); + assertTrue(new File(jar).exists()); } @Test @@ -102,7 +104,7 @@ public void testExistingManifest() throws Exception { JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); - Assertions.assertNotNull(jis.getManifest()); + assertNotNull(jis.getManifest()); jis.close(); } @@ -121,7 +123,7 @@ public void testNoManifest() throws Exception { JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); - Assertions.assertNotNull(jis.getManifest()); + assertNotNull(jis.getManifest()); jis.close(); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java index cf9e64f15a969..eb1c5f8a0489a 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java @@ -22,9 +22,11 @@ import java.util.Iterator; import java.util.Random; -import org.junit.jupiter.api.Assertions; 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 { private static final long starttime = Time.now(); @@ -81,7 +83,7 @@ private static void checkSizeLimit(final int sizeLimit, final int datasize, print(" check size ................. "); for(int i = 0; i < test.data.size(); i++) { test.cache.put(test.data.get(i)); - Assertions.assertTrue(test.cache.size() <= sizeLimit); + assertTrue(test.cache.size() <= sizeLimit); } println("DONE " + test.stat()); } @@ -169,7 +171,7 @@ private static void check(final LightWeightCacheTestCase test) { for(int i = 0; i < test.data.size(); i++) { test.remove(test.data.get(i)); } - Assertions.assertEquals(0, test.cache.size()); + assertEquals(0, test.cache.size()); println("DONE " + test.stat()); //check remove and put again @@ -232,17 +234,17 @@ private static class LightWeightCacheTestCase implements GSet(tablelength, sizeLimit, creationExpirationPeriod, 0, fakeTimer); - Assertions.assertEquals(0, cache.size()); + assertEquals(0, cache.size()); } private boolean containsTest(IntEntry key) { final boolean c = cache.contains(key); if (c) { - Assertions.assertTrue(hashMap.contains(key)); + assertTrue(hashMap.contains(key)); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -257,11 +259,11 @@ public boolean contains(IntEntry key) { private IntEntry getTest(IntEntry key) { final IntEntry c = cache.get(key); if (c != null) { - Assertions.assertEquals(hashMap.get(key).id, c.id); + assertEquals(hashMap.get(key).id, c.id); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -276,12 +278,12 @@ public IntEntry get(IntEntry key) { private IntEntry putTest(IntEntry entry) { final IntEntry c = cache.put(entry); if (c != null) { - Assertions.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 - Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -296,11 +298,11 @@ public IntEntry put(IntEntry entry) { private IntEntry removeTest(IntEntry key) { final IntEntry c = cache.remove(key); if (c != null) { - Assertions.assertEquals(c.id, hashMap.remove(key).id); + assertEquals(c.id, hashMap.remove(key).id); } else { final IntEntry h = hashMap.remove(key); if (h != null) { - Assertions.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); + assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos())); } } return c; @@ -314,7 +316,7 @@ public IntEntry remove(IntEntry key) { private int sizeTest() { final int c = cache.size(); - Assertions.assertTrue(hashMap.size() >= c); + assertTrue(hashMap.size() >= c); return c; } @Override @@ -373,7 +375,7 @@ String stat() { public void clear() { hashMap.clear(); cache.clear(); - Assertions.assertEquals(0, size()); + assertEquals(0, size()); } @Override diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java index a1458ae20ba8b..b8e68bf7b3b32 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightGSet.java @@ -22,12 +22,14 @@ import java.util.Random; import org.apache.hadoop.util.LightWeightGSet.LinkedElement; -import org.junit.jupiter.api.Assertions; 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 = @@ -80,7 +82,7 @@ public void testRemoveAllViaIterator() { iter.next(); iter.remove(); } - Assertions.assertEquals(0, set.size()); + assertEquals(0, set.size()); } @Test @@ -108,7 +110,7 @@ public void testRemoveSomeViaIterator() { } for (Iterator iter = set.iterator(); iter.hasNext(); ) { - Assertions.assertTrue(iter.next().getVal() <= mode); + assertTrue(iter.next().getVal() <= mode); } } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java index 3efce8ae7df89..dcb1d03a538da 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLineReader.java @@ -23,9 +23,10 @@ import java.util.Arrays; import org.apache.hadoop.io.Text; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class TestLineReader { /** @@ -90,10 +91,10 @@ public void testCustomDelimiter1() throws Exception { lineReader.readLine(line); lineReader.close(); - Assertions.assertEquals(fillerString.toString(), line.toString()); + assertEquals(fillerString.toString(), line.toString()); lineReader.readLine(line); - Assertions.assertEquals(expected, line.toString()); + assertEquals(expected, line.toString()); } /** @@ -122,23 +123,23 @@ public void testCustomDelimiter2() throws Exception { final Text line = new Text(); lineReader.readLine(line); - Assertions.assertEquals("", line.toString()); + assertEquals("", line.toString()); lineReader.readLine(line); - Assertions.assertEquals("Kerala ", line.toString()); + assertEquals("Kerala ", line.toString()); lineReader.readLine(line); - Assertions.assertEquals("Bangalore", line.toString()); + assertEquals("Bangalore", line.toString()); lineReader.readLine(line); - Assertions.assertEquals(" North Korea", line.toString()); + assertEquals(" North Korea", line.toString()); lineReader.readLine(line); - Assertions.assertEquals("", line.toString()); + assertEquals("", line.toString()); lineReader.readLine(line); - Assertions.assertEquals("Guantanamo", line.toString()); + assertEquals("Guantanamo", line.toString()); lineReader.readLine(line); - Assertions.assertEquals(("ecord" + "recor" + "core"), line.toString()); + assertEquals(("ecord" + "recor" + "core"), line.toString()); lineReader.close(); } @@ -157,9 +158,9 @@ public void testCustomDelimiter3() throws Exception { final Text line = new Text(); lineReader.readLine(line); - Assertions.assertEquals("a", line.toString()); + assertEquals("a", line.toString()); lineReader.readLine(line); - Assertions.assertEquals("ccc", line.toString()); + assertEquals("ccc", line.toString()); lineReader.close(); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java index 53281925a6fee..07c99580a6f57 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java @@ -18,7 +18,6 @@ package org.apache.hadoop.util; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -27,6 +26,7 @@ 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. @@ -37,27 +37,27 @@ public class TestLists { public void testAddToEmptyArrayList() { List list = Lists.newArrayList(); list.add("record1"); - Assertions.assertEquals(1, list.size()); - Assertions.assertEquals("record1", list.get(0)); + assertEquals(1, list.size()); + assertEquals("record1", list.get(0)); } @Test public void testAddToEmptyLinkedList() { List list = Lists.newLinkedList(); list.add("record1"); - Assertions.assertEquals(1, list.size()); - Assertions.assertEquals("record1", list.get(0)); + assertEquals(1, list.size()); + assertEquals("record1", list.get(0)); } @Test public void testVarArgArrayLists() { List list = Lists.newArrayList("record1", "record2", "record3"); list.add("record4"); - Assertions.assertEquals(4, list.size()); - Assertions.assertEquals("record1", list.get(0)); - Assertions.assertEquals("record2", list.get(1)); - Assertions.assertEquals("record3", list.get(2)); - Assertions.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 @@ -68,7 +68,7 @@ public void testItrArrayLists() { set.add("record3"); List list = Lists.newArrayList(set); list.add("record4"); - Assertions.assertEquals(4, list.size()); + assertEquals(4, list.size()); } @Test @@ -79,7 +79,7 @@ public void testItrLinkedLists() { set.add("record3"); List list = Lists.newLinkedList(set); list.add("record4"); - Assertions.assertEquals(4, list.size()); + assertEquals(4, list.size()); } @Test @@ -130,18 +130,18 @@ public void testArrayListWithSize() { list.add("record1"); list.add("record2"); list.add("record3"); - Assertions.assertEquals(3, list.size()); - Assertions.assertEquals("record1", list.get(0)); - Assertions.assertEquals("record2", list.get(1)); - Assertions.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"); - Assertions.assertEquals(3, list.size()); - Assertions.assertEquals("record1", list.get(0)); - Assertions.assertEquals("record2", list.get(1)); - Assertions.assertEquals("record3", list.get(2)); + assertEquals(3, list.size()); + assertEquals("record1", list.get(0)); + assertEquals("record2", list.get(1)); + assertEquals("record3", list.get(2)); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java index ab0063c804d6f..f5c3893789596 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestMachineList.java @@ -17,6 +17,12 @@ */ package org.apache.hadoop.util; +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; import java.util.Collection; @@ -26,8 +32,6 @@ import org.apache.hadoop.thirdparty.com.google.common.net.InetAddresses; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - public class TestMachineList { private static String IP_LIST = "10.119.103.110,10.119.103.112,10.119.103.114"; private static String IP_LIST_SPACES = @@ -185,7 +189,7 @@ public void testCIDRs() { @Test public void testNullIpAddress() { - assertThrows(IllegalArgumentException.class, ()->{ + assertThrows(IllegalArgumentException.class, () -> { //create MachineList with a list of ip ranges specified in CIDR format MachineList ml = new MachineList(CIDR_LIST, new TestAddressFactory()); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java index 0fca11f20bdd9..dd8bc45dc9dc2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCodeLoader.java @@ -18,7 +18,8 @@ package org.apache.hadoop.util; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java index 3c128d47c3156..ddb8ad5859084 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java +++ b/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.jupiter.api.Assertions.*; -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 org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ChecksumException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.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 data() { Collection params = new ArrayList(2); params.add(new Object[] { DataChecksum.Type.CRC32 }); @@ -57,16 +53,15 @@ public static Collection data() { return params; } - public TestNativeCrc32(DataChecksum.Type checksumType) { - this.checksumType = checksumType; + public void initTestNativeCrc32(DataChecksum.Type pChecksumType) { + this.checksumType = pChecksumType; + setup(); } - @BeforeEach public void setup() { assumeTrue(NativeCrc32.isAvailable()); - assertEquals( - 4 -, checksumType.size, "These tests assume they can write a checksum value as a 4-byte int."); + 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 void setup() { 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 void testVerifyChunkedSumsSuccessOddSize() throws ChecksumException { 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 void testVerifyChunkedSumsByteArraySuccess() throws ChecksumException { 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 void testVerifyChunkedSumsByteArrayFail() { 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 void testCalculateChunkedSumsByteArraySuccess() throws ChecksumException 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 void testCalculateChunkedSumsByteArrayFail() throws ChecksumException { 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 void testNativeVerifyChunkedSumsSuccess() throws ChecksumException { 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, From aca5c905830f0058d460091798cc48ddde2e2d8c Mon Sep 17 00:00:00 2001 From: fanshilun Date: Fri, 7 Feb 2025 13:10:31 +0800 Subject: [PATCH 3/5] HADOOP-19415. Fix JunitTest & CheckStyle. --- .../hadoop/test/UnitTestcaseTimeLimit.java | 9 +-- .../hadoop/util/TestIdentityHashStore.java | 2 +- .../hadoop/util/TestNativeLibraryChecker.java | 3 +- .../org/apache/hadoop/util/TestOptions.java | 17 +++-- .../org/apache/hadoop/util/TestProgress.java | 13 ++-- .../apache/hadoop/util/TestPureJavaCrc32.java | 5 +- .../util/TestReadWriteDiskValidator.java | 14 ++-- .../hadoop/util/TestReflectionUtils.java | 4 +- .../org/apache/hadoop/util/TestRunJar.java | 26 ++++--- .../org/apache/hadoop/util/TestShell.java | 38 +++++----- .../hadoop/util/TestShutdownHookManager.java | 32 ++++----- .../apache/hadoop/util/TestSignalLogger.java | 10 +-- .../org/apache/hadoop/util/TestStopWatch.java | 18 ++--- .../hadoop/util/TestStringInterner.java | 3 +- .../apache/hadoop/util/TestStringUtils.java | 45 +++++------- .../hadoop/util/TestSysInfoWindows.java | 2 +- .../apache/hadoop/util/TestVersionUtil.java | 3 +- .../hadoop/util/TestWeakReferenceMap.java | 32 ++++----- .../org/apache/hadoop/util/TestWinUtils.java | 32 +++++---- .../org/apache/hadoop/util/TestXMLUtils.java | 11 +-- .../org/apache/hadoop/util/TestZKUtil.java | 5 +- .../util/bloom/BloomFilterCommonTester.java | 36 +++++----- .../hadoop/util/bloom/TestBloomFilters.java | 31 ++++----- .../curator/TestSecureZKCuratorManager.java | 63 +++++++++-------- .../util/curator/TestZKCuratorManager.java | 13 ++-- .../util/dynamic/TestDynConstructors.java | 26 +++---- .../hadoop/util/dynamic/TestDynMethods.java | 69 ++++++++++--------- .../org/apache/hadoop/util/hash/TestHash.java | 57 +++++++-------- 28 files changed, 302 insertions(+), 317 deletions(-) diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java index 722d0072439a7..0ce55c10aee22 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java +++ b/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 @@ * 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); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java index 487512aa9a752..dc140224616fc 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIdentityHashStore.java @@ -106,7 +106,7 @@ public void accept(Key k, Integer v) { Key equalToKey1 = new Key("key1"); // IdentityHashStore compares by object equality, not equals() - assertNull(store.get(equalToKey1)); + assertNull(store.get(equalToKey1)); assertTrue(!store.isEmpty()); assertEquals(value1, store.get(key1)); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java index 8359aec8a8a25..8ddabed194867 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeLibraryChecker.java @@ -20,7 +20,8 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import org.apache.hadoop.util.ExitUtil.ExitException; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java index 612073119bb66..8430be9cc730c 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java @@ -19,20 +19,19 @@ package org.apache.hadoop.util; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +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( - 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"); + 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java index 835d5ff0e203d..38ea9c8e6c1db 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java @@ -18,27 +18,28 @@ package org.apache.hadoop.util; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class TestProgress { @Test public void testSet(){ Progress progress = new Progress(); progress.set(Float.NaN); - Assertions.assertEquals(0, progress.getProgress(), 0.0); + assertEquals(0, progress.getProgress(), 0.0); progress.set(Float.NEGATIVE_INFINITY); - Assertions.assertEquals(0,progress.getProgress(),0.0); + assertEquals(0,progress.getProgress(),0.0); progress.set(-1); - Assertions.assertEquals(0,progress.getProgress(),0.0); + assertEquals(0,progress.getProgress(),0.0); progress.set((float) 1.1); - Assertions.assertEquals(1,progress.getProgress(),0.0); + assertEquals(1,progress.getProgress(),0.0); progress.set(Float.POSITIVE_INFINITY); - Assertions.assertEquals(1,progress.getProgress(),0.0); + assertEquals(1,progress.getProgress(),0.0); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java index 8d27fea37c795..cee0fcef092f2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestPureJavaCrc32.java @@ -29,9 +29,10 @@ import java.util.zip.CRC32; import java.util.zip.Checksum; -import org.junit.jupiter.api.Assertions; 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 * the same results as the built-in implementation. @@ -96,7 +97,7 @@ private void checkOnBytes(byte[] bytes, boolean print) { } private void checkSame() { - Assertions.assertEquals(theirs.getValue(), ours.getValue()); + assertEquals(theirs.getValue(), ours.getValue()); } /** diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java index a30f61b49f72f..730282601511a 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReadWriteDiskValidator.java @@ -30,7 +30,6 @@ import org.apache.hadoop.util.DiskChecker.DiskErrorException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Assertions; import java.io.File; import java.nio.file.Files; @@ -64,13 +63,12 @@ public void testReadWriteDiskValidator() ReadWriteDiskValidatorMetrics metric = ReadWriteDiskValidatorMetrics.getMetric(testDir.toString()); - Assertions.assertEquals( - metric.getFileReadQuantiles()[0].getEstimator().getCount(), count, "The count number of estimator in MutableQuantiles" + assertEquals(metric.getFileReadQuantiles()[0].getEstimator().getCount(), count, + "The count number of estimator in MutableQuantiles" + "metrics of file read is not right"); - Assertions.assertEquals( - metric.getFileWriteQuantiles()[0].getEstimator().getCount() -, count, "The count number of estimator in MutableQuantiles" + 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( @@ -154,8 +152,8 @@ public void testCheckFailures() throws Throwable { "FailureCount", 2); Long lastFailureTime2 = (Long) MetricsRecords.getMetricValueByName( collector.getRecords().get(1), "LastFailureTime"); - assertTrue( - lastFailureTime1 < lastFailureTime2, "The first failure time should be less than the second one"); + assertTrue(lastFailureTime1 < lastFailureTime2, + "The first failure time should be less than the second one"); testDir.delete(); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java index b81c2bf2305c7..7d8bece0d675d 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestReflectionUtils.java @@ -25,7 +25,9 @@ import java.util.HashMap; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java index 8027c78e0d45a..03f906f0cc3c7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java @@ -47,7 +47,6 @@ import org.apache.hadoop.fs.Path; import org.apache.hadoop.test.GenericTestUtils; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -106,10 +105,10 @@ public void testUnJar() throws Exception { // Unjar everything RunJar.unJar(new File(TEST_ROOT_DIR, TEST_JAR_NAME), unjarDir, MATCH_ANY); - assertTrue( - new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(), "foobar unpacked"); - assertTrue( - new File(unjarDir, FOOBAZ_TXT).exists(), "foobaz unpacked"); + assertTrue(new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(), + "foobar unpacked"); + assertTrue(new File(unjarDir, FOOBAZ_TXT).exists(), + "foobaz unpacked"); } /** @@ -123,10 +122,9 @@ public void testUnJarWithPattern() throws Exception { RunJar.unJar(new File(TEST_ROOT_DIR, TEST_JAR_NAME), unjarDir, Pattern.compile(".*baz.*")); - assertFalse( - new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(), "foobar not unpacked"); - assertTrue( - new File(unjarDir, FOOBAZ_TXT).exists(), "foobaz unpacked"); + 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 @@ private File generateBigJar(File dir) throws Exception { public void testBigJar() throws Exception { Random r = new Random(System.currentTimeMillis()); File dir = new File(TEST_ROOT_DIR, Long.toHexString(r.nextLong())); - Assertions.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(".*")); } - Assertions.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)); - Assertions.assertEquals(756, f.length()); + assertEquals(756, f.length()); } } finally { // Clean up @@ -192,8 +190,8 @@ public void testUnJarDoesNotLooseLastModify() throws Exception { private File getUnjarDir(String dirName) { File unjarDir = new File(TEST_ROOT_DIR, dirName); - assertFalse( - new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(), "unjar dir shouldn't exist at test start"); + assertFalse(new File(unjarDir, TestRunJar.FOOBAR_TXT).exists(), + "unjar dir shouldn't exist at test start"); return unjarDir; } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java index c5b07585ca853..62cf6697fe10f 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java @@ -17,10 +17,13 @@ */ package org.apache.hadoop.util; -import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.apache.commons.io.FileUtils; +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; @@ -40,21 +43,12 @@ import org.apache.hadoop.test.GenericTestUtils; import static org.apache.hadoop.util.Shell.*; -import static org.junit.Assume.assumeTrue; - -import org.junit.Assume; -import org.junit.jupiter.api.BeforeEach; -import org.junit.Rule; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.rules.TestName; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; @Timeout(value = 30) public class TestShell extends Assertions { - @Rule - public TestName methodName = new TestName(); - private File rootTestDir = GenericTestUtils.getTestDir(); /** @@ -91,10 +85,10 @@ public int getRunCount() { } @BeforeEach - public void setup() { + public void setup(TestInfo testInfo) { rootTestDir.mkdirs(); assertTrue(rootTestDir.isDirectory(), "Not a directory " + rootTestDir); - methodDir = new File(rootTestDir, methodName.getMethodName()); + methodDir = new File(rootTestDir, testInfo.getDisplayName()); } @Test @@ -129,7 +123,7 @@ public void testShellCommandExecutorToString() throws Throwable { @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\""; @@ -152,13 +146,13 @@ public void testShellCommandTimeout() throws Throwable { @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); } @@ -242,7 +236,7 @@ public void testGetCheckProcessIsAliveCommand() throws Exception { expectedCommand = new String[] {"bash", "-c", "kill -0 '" + anyPid + "'" }; } - Assertions.assertArrayEquals(expectedCommand, checkProcessAliveCommand); + assertArrayEquals(expectedCommand, checkProcessAliveCommand); } @Test @@ -264,7 +258,7 @@ public void testGetSignalKillCommand() throws Exception { expectedCommand = new String[]{ "bash", "-c", "kill -9 '" + anyPid + "'"}; } - Assertions.assertArrayEquals(expectedCommand, checkProcessAliveCommand); + assertArrayEquals(expectedCommand, checkProcessAliveCommand); } private void testInterval(long interval) throws IOException { @@ -384,7 +378,7 @@ public void testBinWinUtilsNotAFile() throws Throwable { */ @Test public void testNoWinutilsOnUnix() throws Throwable { - Assume.assumeFalse(WINDOWS); + assumeFalse(WINDOWS); try { getWinUtilsFile(); } catch (FileNotFoundException ex) { @@ -476,7 +470,7 @@ public void testBashQuote() { @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()}; @@ -532,6 +526,6 @@ public void testIsJavaVersionAtLeast() { @Test public void testIsBashSupported() throws InterruptedIOException { - assumeTrue("Bash is not supported", Shell.checkIsBashSupported()); + assumeTrue(Shell.checkIsBashSupported(), "Bash is not supported"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java index 46810e20587a2..c9684c0a9f04a 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShutdownHookManager.java @@ -102,13 +102,11 @@ public void shutdownHookManager() { ShutdownHookManager.HookEntry hookEntry5 = mgr.getShutdownHooksInOrder() .get(0); assertEquals(hook5, hookEntry5.getHook()); - assertEquals( - ShutdownHookManager.getShutdownTimeout(new Configuration()) -, hookEntry5.getTimeout(), "default timeout not used"); + 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( - mgr.removeShutdownHook(hook5), "failed to remove " + hook5); + assertTrue(mgr.removeShutdownHook(hook5), "failed to remove " + hook5); // now execute the hook shutdown sequence @@ -131,8 +129,7 @@ public void shutdownHookManager() { // check the state of some of the invoked hooks // hook4 was invoked first, but it timed out. - assertEquals( - 1, hook4.invokedOrder, "Expected to be invoked first " + hook4); + assertEquals(1, hook4.invokedOrder, "Expected to be invoked first " + hook4); assertFalse(hook4.completed, "Expected to time out " + hook4); @@ -140,18 +137,17 @@ public void shutdownHookManager() { // is the longest. assertTrue(hook1.completed, "Expected to complete " + hook1); long invocationInterval = hook1.startTime - hook4.startTime; - assertTrue( - invocationInterval >= hook4timeout * 1000, "invocation difference too short " + invocationInterval); - assertTrue( - invocationInterval < hook4.sleepTime, "sleeping hook4 blocked other threads for " + invocationInterval); + 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( - 0 -, mgr.getShutdownHooksInOrder().size(), "shutdown hook list is not empty"); + assertEquals(0, mgr.getShutdownHooksInOrder().size(), + "shutdown hook list is not empty"); } @Test @@ -161,8 +157,8 @@ public void testShutdownTimeoutConfiguration() throws Throwable { long shutdownTimeout = 5; conf.setTimeDuration(SERVICE_SHUTDOWN_TIMEOUT, shutdownTimeout, TimeUnit.SECONDS); - assertEquals(shutdownTimeout, - ShutdownHookManager.getShutdownTimeout(conf), SERVICE_SHUTDOWN_TIMEOUT); + assertEquals(shutdownTimeout, ShutdownHookManager.getShutdownTimeout(conf), + SERVICE_SHUTDOWN_TIMEOUT); } /** @@ -223,8 +219,8 @@ public void testShutdownRemove() throws Throwable { mgr.addShutdownHook(hook1, 9); // create Hook1 with priority 9 assertTrue(mgr.hasShutdownHook(hook1), "No hook1"); // hook1 lookup works assertEquals(1, mgr.getShutdownHooksInOrder().size()); // 1 hook - assertFalse( - mgr.removeShutdownHook(hook2), "Delete hook2 should not be allowed"); + assertFalse(mgr.removeShutdownHook(hook2), + "Delete hook2 should not be allowed"); assertTrue(mgr.removeShutdownHook(hook1), "Can't delete hook1"); assertEquals(0, mgr.getShutdownHooksInOrder().size()); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java index aab71abc7f756..06e76f93272bd 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSignalLogger.java @@ -19,13 +19,15 @@ package org.apache.hadoop.util; import org.apache.commons.lang3.SystemUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.Assume; + 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); @@ -33,11 +35,11 @@ public class TestSignalLogger { @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); - Assertions.fail("expected IllegalStateException from double registration"); + fail("expected IllegalStateException from double registration"); } catch (IllegalStateException e) { // fall through } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java index 465a29f71a9b3..201c8a3eba5f9 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStopWatch.java +++ b/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.jupiter.api.Assertions; 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()) { - Assertions.assertFalse(sw.isRunning()); + assertFalse(sw.isRunning()); sw.start(); - Assertions.assertTrue(sw.isRunning()); + assertTrue(sw.isRunning()); sw.stop(); - Assertions.assertFalse(sw.isRunning()); + assertFalse(sw.isRunning()); } } @@ -46,16 +48,16 @@ public void testExceptions() throws Exception { try { sw.stop(); } catch (Exception e) { - Assertions.assertTrue( - e instanceof IllegalStateException, "IllegalStateException is expected"); + assertTrue(e instanceof IllegalStateException, + "IllegalStateException is expected"); } sw.reset(); sw.start(); try { sw.start(); } catch (Exception e) { - Assertions.assertTrue( - e instanceof IllegalStateException, "IllegalStateException is expected"); + assertTrue(e instanceof IllegalStateException, + "IllegalStateException is expected"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java index fffec2bb8afad..84ab997f2ffbc 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringInterner.java @@ -18,7 +18,8 @@ package org.apache.hadoop.util; -import static org.junit.jupiter.api.Assertions.*; +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.jupiter.api.Test; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java index ee9b45cbd6ab2..39c04787d22bd 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java @@ -24,6 +24,7 @@ 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.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; @@ -48,7 +49,6 @@ import org.apache.hadoop.test.UnitTestcaseTimeLimit; import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -382,15 +382,12 @@ public void testStringToURI() { @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 @@ -534,21 +531,18 @@ public void testCreateStartupShutdownMessage() { public void testStringCollectionSplitByEqualsSuccess() { Map 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"); @@ -556,8 +550,7 @@ public void testStringCollectionSplitByEqualsSuccess() { 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") @@ -571,8 +564,7 @@ public void testStringCollectionSplitByEqualsSuccess() { + " 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") @@ -585,8 +577,7 @@ public void testStringCollectionSplitByEqualsSuccess() { 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"); @@ -594,16 +585,14 @@ public void testStringCollectionSplitByEqualsSuccess() { 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); @@ -647,7 +636,7 @@ public void testForGetStackTrace() { } // 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++) { @@ -671,5 +660,5 @@ public static void main(String []args) { } } } - } + }*/ } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java index abefb9828d241..2f6664e4e9f93 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestSysInfoWindows.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestSysInfoWindows { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java index bf6339656d0d7..38e458be52788 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java @@ -17,7 +17,8 @@ */ package org.apache.hadoop.util; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java index 1c95f1535d107..36a059b5dee46 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWeakReferenceMap.java @@ -22,7 +22,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicLong; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,6 +29,7 @@ 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}. @@ -156,12 +156,12 @@ public void testWeakReferenceThreadMapAssignment() 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 void testWeakReferenceThreadMapAssignment() 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 void testWeakReferenceThreadMapAssignment() 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 void testWeakReferenceThreadMapAssignment() * @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 @@ private void assertMapEntryEquals(int key, String val) { * @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 @@ private void assertMapContainsKey(int key) { * @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 @@ private void assertMapDoesNotContainKey(int key) { * @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 @@ private void assertMapSize(int size) { * @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 @@ private void assertPruned(int count) { * @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); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java index 8b829261880b3..92fb32e65ff46 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java +++ b/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.jupiter.api.Assertions.*; +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,7 +35,6 @@ 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.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -504,12 +508,12 @@ public void testReadLink() throws IOException { 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. // @@ -519,7 +523,7 @@ public void testReadLink() throws IOException { 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 { @@ -528,7 +532,7 @@ public void testReadLink() throws IOException { 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 { @@ -537,7 +541,7 @@ public void testReadLink() throws IOException { 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 { @@ -546,7 +550,7 @@ public void testReadLink() throws IOException { 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 { @@ -555,7 +559,7 @@ public void testReadLink() throws IOException { 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); } } @@ -579,7 +583,7 @@ public void testTaskCreate() throws IOException { String outNumber = FileUtils.readFileToString(proof); - Assertions.assertThat(outNumber).contains(testNumber); + assertThat(outNumber).contains(testNumber); } @Test @@ -613,7 +617,7 @@ public void testTaskCreateWithLimits() throws IOException { + 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 @@ -624,7 +628,7 @@ public void testTaskCreateWithLimits() throws IOException { "-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 { @@ -633,7 +637,7 @@ public void testTaskCreateWithLimits() throws IOException { "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 { @@ -642,7 +646,7 @@ public void testTaskCreateWithLimits() throws IOException { "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); } } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java index d2768c8c94935..c99856debb64e 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java @@ -33,7 +33,6 @@ import org.apache.hadoop.test.AbstractHadoopTestBase; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; @@ -41,7 +40,9 @@ 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 { @@ -151,14 +152,14 @@ public void testBestEffortSetAttribute() throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); AtomicBoolean flag1 = new AtomicBoolean(true); XMLUtils.bestEffortSetAttribute(factory, flag1, "unsupportedAttribute false", "abc"); - Assertions.assertFalse(flag1.get(), "unexpected attribute results in return of false?"); + assertFalse(flag1.get(), "unexpected attribute results in return of false?"); AtomicBoolean flag2 = new AtomicBoolean(true); XMLUtils.bestEffortSetAttribute(factory, flag2, XMLConstants.ACCESS_EXTERNAL_DTD, ""); - Assertions.assertTrue(flag2.get(), "expected attribute results in return of true?"); + assertTrue(flag2.get(), "expected attribute results in return of true?"); AtomicBoolean flag3 = new AtomicBoolean(false); XMLUtils.bestEffortSetAttribute(factory, flag3, XMLConstants.ACCESS_EXTERNAL_DTD, ""); - Assertions.assertFalse( - flag3.get(), "expected attribute results in return of false if input flag is false?"); + assertFalse(flag3.get(), + "expected attribute results in return of false if input flag is false?"); } private static InputStream getResourceStream(final String filename) { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java index 53031270c4af7..411a32e34c8b7 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestZKUtil.java +++ b/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.jupiter.api.Assertions.*; +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; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java index 7bff7ee6060ab..8c9e28875a0dd 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java @@ -20,6 +20,7 @@ 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.Iterator; import java.util.Random; -import org.junit.jupiter.api.Assertions; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.util.hash.Hash; @@ -83,7 +83,7 @@ public ImmutableSet falsePositives(int hashId) { } default: { // fail fast with unknown hash error !!! - Assertions.assertFalse(true, "unknown hash error"); + assertFalse(true, "unknown hash error"); return ImmutableSet.of(); } } @@ -229,7 +229,7 @@ private void checkOnReadWrite() { assertTrue(restoredKey.equals(originKey), "checkOnReadWrite equals error"); out.reset(); } catch (Exception ioe) { - Assertions.fail("checkOnReadWrite ex error"); + fail("checkOnReadWrite ex error"); } } @@ -240,7 +240,7 @@ private void checkSetOnIAE() { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assertions.fail("checkSetOnIAE ex error"); + fail("checkSetOnIAE ex error"); } } @@ -272,7 +272,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } try { @@ -281,7 +281,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } try { @@ -290,7 +290,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } try { @@ -298,7 +298,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } try { @@ -306,7 +306,7 @@ private void checkAndOnIAE(Filter filter) { } catch (IllegalArgumentException ex) { // expected } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } try { @@ -316,7 +316,7 @@ private void checkAndOnIAE(Filter filter) { } catch (UnsupportedOperationException unex) { // } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } } @@ -328,7 +328,7 @@ private void checkTestMembershipOnNPE(Filter filter) { } catch (NullPointerException ex) { // expected } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } } @@ -339,7 +339,7 @@ private void checkAddOnNPE(Filter filter) { } catch (NullPointerException ex) { // expected } catch (Exception e) { - Assertions.fail("" + e); + fail("" + e); } } }), @@ -357,7 +357,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // check on present even key for (int i = 0; i < numInsertions; i += 2) { - Assertions.assertTrue( + assertTrue( filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } @@ -407,7 +407,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, } } catch (IOException ex) { - Assertions.fail("error ex !!!" + ex); + fail("error ex !!!" + ex); } } }), @@ -424,7 +424,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, filter.xor(symmetricFilter); // check on present all key for (int i = 0; i < numInsertions; i++) { - Assertions.assertFalse( + assertFalse( filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } @@ -442,7 +442,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // 1 xor 1 -> 0 // check on absent all key for (int i = 0; i < numInsertions; i++) { - Assertions.assertFalse( + assertFalse( filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might not contains " + i); } @@ -478,7 +478,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, for (int i = 0; i < numInsertions; i++) { if (i >= startIntersection && i <= endIntersection) { - Assertions.assertTrue( + assertTrue( filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } } @@ -508,7 +508,7 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // check on present all key for (int i = 0; i < numInsertions; i++) { - Assertions.assertTrue( + assertTrue( filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java index f3a379e9a6e07..98932aa3635e4 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/TestBloomFilters.java @@ -21,6 +21,7 @@ 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,7 +29,6 @@ import org.apache.hadoop.util.bloom.BloomFilterCommonTester.BloomFilterTestStrategy; import org.apache.hadoop.util.hash.Hash; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableList; @@ -112,24 +112,18 @@ public void testCountingBloomFilter() { Key key = new Key(new byte[] { 48, 48 }); filter.add(key); - assertTrue( - filter.membershipTest(key), "CountingBloomFilter.membership error "); - assertTrue( - filter.approximateCount(key) == 1, "CountingBloomFilter.approximateCount error"); + assertTrue(filter.membershipTest(key), "CountingBloomFilter.membership error "); + assertTrue(filter.approximateCount(key) == 1, "CountingBloomFilter.approximateCount error"); filter.add(key); - assertTrue( - filter.approximateCount(key) == 2, "CountingBloomFilter.approximateCount error"); + assertTrue(filter.approximateCount(key) == 2, "CountingBloomFilter.approximateCount error"); filter.delete(key); - assertTrue( - filter.membershipTest(key), "CountingBloomFilter.membership error "); + assertTrue(filter.membershipTest(key), "CountingBloomFilter.membership error "); filter.delete(key); - assertFalse( - filter.membershipTest(key), "CountingBloomFilter.membership error "); - assertTrue( - filter.approximateCount(key) == 0, "CountingBloomFilter.approximateCount error"); + 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 @@ private void checkOnAbsentFalsePositive(int hashId, int numInsertions, .get(hashId); if (falsePositives == null) - Assertions.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 @@ private void checkOnAbsentFalsePositive(int hashId, int numInsertions, } for (int i = 1 - digits.getStart(); i < numInsertions; i += 2) { - assertFalse( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " testRetouchedBloomFilterAddFalsePositive error " + i); + assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " testRetouchedBloomFilterAddFalsePositive error " + i); } } @@ -257,7 +250,7 @@ public void testNot() { bf.bits = BitSet.valueOf(new byte[] { (byte) 0x95 }); BitSet origBitSet = (BitSet) bf.bits.clone(); bf.not(); - assertFalse( - bf.bits.intersects(origBitSet), "BloomFilter#not should have inverted all bits"); + assertFalse(bf.bits.intersects(origBitSet), + "BloomFilter#not should have inverted all bits"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java index 51c01aa4f014e..1c016df5bd644 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestSecureZKCuratorManager.java @@ -159,21 +159,26 @@ private void validateSSLConfiguration(String keystoreLocation, String keystorePa String truststoreLocation, String truststorePassword, ZooKeeper zk) { try (ClientX509Util x509Util = new ClientX509Util()) { //testing if custom values are set properly - 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"); + 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( - ClientCnxnSocketNetty.class.getCanonicalName() -, zk.getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET), "Validate that expected clientConfig is set in ZK config"); + 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 void testTruststoreKeystoreConfiguration() { 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 void testTruststoreKeystoreConfiguration() { 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."); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java index edf00a0da5521..98fca17193299 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/curator/TestZKCuratorManager.java @@ -231,14 +231,15 @@ public void testCuratorFrameworkFactory() throws Exception{ private void validateJaasConfiguration(String clientConfig, String principal, String keytab, ZooKeeper zk) { - assertEquals(clientConfig -, zk.getClientConfig().getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY), "Validate that expected clientConfig is set in ZK config"); + 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(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"); + 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"); } } \ No newline at end of file diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java index de6376319dd33..5c211252415e3 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java @@ -21,12 +21,14 @@ import java.util.concurrent.Callable; -import org.junit.jupiter.api.Assertions; 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 void testFirstImplReturned() throws Exception { .buildChecked(); Concatenator dashCat = sepCtor.newInstanceChecked("-"); - Assertions.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 void testFirstImplReturned() throws Exception { .buildChecked(); Concatenator cat = defaultCtor.newInstanceChecked(); - Assertions.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 void testStringClassname() throws Exception { .impl(Concatenator.class.getName(), String.class) .buildChecked(); - Assertions.assertNotNull(sepCtor.newInstance("-"), "Should find 1-arg constructor"); + assertNotNull(sepCtor.newInstance("-"), "Should find 1-arg constructor"); } @Test @@ -130,12 +132,12 @@ public void testHiddenMethod() throws Exception { .hiddenImpl(Concatenator.class.getName(), char.class) .buildChecked(); - Assertions.assertNotNull(sepCtor, "Should find hidden ctor with hiddenImpl"); + assertNotNull(sepCtor, "Should find hidden ctor with hiddenImpl"); Concatenator slashCat = sepCtor.newInstanceChecked('/'); - Assertions.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 void testBind() throws Exception { .impl(Concatenator.class.getName()) .buildChecked(); - Assertions.assertTrue(ctor.isStatic(), "Should always be static"); + assertTrue(ctor.isStatic(), "Should always be static"); intercept(IllegalStateException.class, () -> ctor.bind(null)); @@ -162,9 +164,9 @@ public void testInvoke() throws Exception { intercept(IllegalArgumentException.class, () -> ctor.invoke("a")); - Assertions.assertNotNull( + assertNotNull( ctor.invokeChecked(null), "Should allow invokeChecked(null, ...)"); - Assertions.assertNotNull( + assertNotNull( ctor.invoke(null), "Should allow invoke(null, ...)"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java index c205a769eb5e1..1a1082e3a5c41 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java @@ -21,12 +21,16 @@ import java.util.concurrent.Callable; -import org.junit.jupiter.api.Assertions; 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,10 +82,10 @@ public void testFirstImplReturned() throws Exception { .impl(Concatenator.class, String.class, String.class, String.class) .buildChecked(); - Assertions.assertEquals("a-b", cat2.invoke(obj, "a", "b"), + assertEquals("a-b", cat2.invoke(obj, "a", "b"), "Should call the 2-arg version successfully"); - Assertions.assertEquals("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") @@ -90,10 +94,10 @@ public void testFirstImplReturned() throws Exception { .impl(Concatenator.class, String.class, String.class) .build(); - Assertions.assertEquals("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"); - Assertions.assertEquals("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"); } @@ -103,11 +107,11 @@ public void testVarArgs() throws Exception { .impl(Concatenator.class, String[].class) .buildChecked(); - Assertions.assertEquals("abcde", + assertEquals("abcde", cat.invokeChecked(new Concatenator(), (Object) new String[]{"a", "b", "c", "d", "e"}), "Should use the varargs version"); - Assertions.assertEquals("abcde", + assertEquals("abcde", cat.bind(new Concatenator()) .invokeChecked((Object) new String[]{"a", "b", "c", "d", "e"}), "Should use the varargs version"); } @@ -150,7 +154,7 @@ public void testNameChange() throws Exception { .impl(Concatenator.class, "concat", String.class, String.class) .buildChecked(); - Assertions.assertEquals("a-b", cat.invoke(obj, "a", "b"), + assertEquals("a-b", cat.invoke(obj, "a", "b"), "Should find 2-arg concat method"); } @@ -161,7 +165,7 @@ public void testStringClassname() throws Exception { .impl(Concatenator.class.getName(), String.class, String.class) .buildChecked(); - Assertions.assertEquals("a-b", cat.invoke(obj, "a", "b"), + assertEquals("a-b", cat.invoke(obj, "a", "b"), "Should find 2-arg concat method"); } @@ -178,13 +182,12 @@ public void testHiddenMethod() throws Exception { .hiddenImpl(Concatenator.class, String.class) .buildChecked(); - Assertions.assertNotNull( - changeSep, "Should find hidden method with hiddenImpl"); + assertNotNull(changeSep, "Should find hidden method with hiddenImpl"); changeSep.invokeChecked(obj, "/"); - Assertions.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 @@ -197,16 +200,16 @@ public void testBoundMethod() throws Exception { DynMethods.BoundMethod dashCat = cat.bind(new Concatenator("-")); DynMethods.BoundMethod underCat = cat.bind(new Concatenator("_")); - Assertions.assertEquals("a-b", dashCat.invoke("a", "b"), + assertEquals("a-b", dashCat.invoke("a", "b"), "Should use '-' object without passing"); - Assertions.assertEquals("a_b", underCat.invoke("a", "b"), + 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("/")); - Assertions.assertEquals("a/b", slashCat.invoke("a", "b"), + assertEquals("a/b", slashCat.invoke("a", "b"), "Should use bound object from builder without passing"); } @@ -222,7 +225,7 @@ public void testBindStaticMethod() throws Exception { builder.build(new Concatenator())); final DynMethods.UnboundMethod staticCat = builder.buildChecked(); - Assertions.assertTrue(staticCat.isStatic(), "Should be static"); + assertTrue(staticCat.isStatic(), "Should be static"); intercept(IllegalStateException.class, () -> staticCat.bind(new Concatenator())); @@ -234,7 +237,7 @@ public void testStaticMethod() throws Exception { .impl(Concatenator.class, String[].class) .buildStaticChecked(); - Assertions.assertEquals("abcde", staticCat.invokeChecked( + assertEquals("abcde", staticCat.invokeChecked( (Object) new String[]{"a", "b", "c", "d", "e"}), "Should call varargs static method cat(String...)"); } @@ -249,7 +252,7 @@ public void testNonStaticMethod() throws Exception { intercept(IllegalStateException.class, builder::buildStaticChecked); final DynMethods.UnboundMethod cat2 = builder.buildChecked(); - Assertions.assertFalse( + assertFalse( cat2.isStatic(), "concat(String,String) should not be static"); intercept(IllegalStateException.class, cat2::asStatic); @@ -262,11 +265,11 @@ public void testConstructorImpl() throws Exception { .impl(Concatenator.class, String.class); DynMethods.UnboundMethod newConcatenator = builder.buildChecked(); - Assertions.assertTrue( + assertTrue( newConcatenator instanceof DynConstructors.Ctor, "Should find constructor implementation"); - Assertions.assertTrue( + assertTrue( newConcatenator.isStatic(), "Constructor should be a static method"); - Assertions.assertFalse( + assertFalse( newConcatenator.isNoop(), "Constructor should not be NOOP"); // constructors cannot be bound @@ -276,12 +279,12 @@ public void testConstructorImpl() throws Exception { builder.build(new Concatenator())); Concatenator concatenator = newConcatenator.asStatic().invoke("*"); - Assertions.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("@"); - Assertions.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 @@ -291,7 +294,7 @@ public void testConstructorImplAfterFactoryMethod() throws Exception { .ctorImpl(Concatenator.class, String.class) .buildChecked(); - Assertions.assertFalse( + assertFalse( newConcatenator instanceof DynConstructors.Ctor, "Should find factory method before constructor method"); } @@ -303,17 +306,17 @@ public void testNoop() throws Exception { .orNoop() .buildChecked(); - Assertions.assertTrue( + assertTrue( noop.isNoop(), "No implementation found, should return NOOP"); - Assertions.assertNull( + assertNull( noop.invoke(new Concatenator(), "a"), "NOOP should always return null"); - Assertions.assertNull( + assertNull( noop.invoke(null, "a"), "NOOP can be called with null"); - Assertions.assertNull( + assertNull( noop.bind(new Concatenator()).invoke("a"), "NOOP can be bound"); - Assertions.assertNull( + assertNull( noop.bind(null).invoke("a"), "NOOP can be bound to null"); - Assertions.assertNull( + assertNull( noop.asStatic().invoke("a"), "NOOP can be static"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java index 46b4a0ee56ce6..32c6dd0b60f39 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java @@ -17,7 +17,8 @@ */ package org.apache.hadoop.util.hash; -import static org.junit.jupiter.api.Assertions.*; +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.jupiter.api.Test; @@ -27,12 +28,11 @@ public class TestHash { @Test public void testHash() { int iterations = 30; - 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"); + 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"); @@ -40,50 +40,43 @@ public void testHash() { cfg = new Configuration(); cfg.set("hadoop.util.hash.type", "jenkins"); - assertTrue( - JenkinsHash.getInstance() == Hash.getInstance(cfg), "testHash jenkins configuration error !!!"); + assertTrue(JenkinsHash.getInstance() == Hash.getInstance(cfg), + "testHash jenkins configuration error !!!"); cfg = new Configuration(); - assertTrue( - MurmurHash.getInstance() == Hash.getInstance(cfg), "testHash undefine configuration error !!!"); + assertTrue(MurmurHash.getInstance() == Hash.getInstance(cfg), + "testHash undefine configuration error !!!"); - assertTrue( - JenkinsHash.getInstance() == Hash.getInstance(Hash.JENKINS_HASH), "testHash error jenkin getInstance !!!"); - assertTrue( - MurmurHash.getInstance() == Hash.getInstance(Hash.MURMUR_HASH), "testHash error murmur getInstance !!!"); + 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( - Hash.getInstance(Hash.INVALID_HASH), "testHash error invalid getInstance !!!"); + 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( - murmurHash == Hash.getInstance(Hash.MURMUR_HASH) - .hash(LINE.getBytes()), "multiple evaluation murmur hash error !!!"); + 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( - - murmurHash == Hash.getInstance(Hash.MURMUR_HASH).hash( - LINE.getBytes(), 67), "multiple evaluation murmur hash error !!!"); + 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( - - jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash( - LINE.getBytes()), "multiple evaluation jenkins hash error !!!"); + 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( - - jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash( - LINE.getBytes(), 67), "multiple evaluation jenkins hash error !!!"); + assertTrue(jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash( + LINE.getBytes(), 67), "multiple evaluation jenkins hash error !!!"); } } } From c65731736ccb081d93ee95882a73bc383f9c2cc7 Mon Sep 17 00:00:00 2001 From: fanshilun Date: Fri, 7 Feb 2025 16:04:13 +0800 Subject: [PATCH 4/5] HADOOP-19415. [JDK17] Upgrade JUnit from 4 to 5 in hadoop-common Part5. --- .../hadoop/util/TestCacheableIPList.java | 16 +++--- .../util/TestDiskCheckerWithDiskIo.java | 1 - .../apache/hadoop/util/TestNativeCrc32.java | 14 ++--- .../org/apache/hadoop/util/TestOptions.java | 2 +- .../org/apache/hadoop/util/TestProgress.java | 8 +-- .../org/apache/hadoop/util/TestRunJar.java | 6 ++- .../org/apache/hadoop/util/TestShell.java | 2 +- .../apache/hadoop/util/TestStringUtils.java | 25 ++++----- .../org/apache/hadoop/util/TestWinUtils.java | 11 ++-- .../org/apache/hadoop/util/TestXMLUtils.java | 8 +-- .../util/bloom/BloomFilterCommonTester.java | 52 +++++++++---------- .../util/dynamic/TestDynConstructors.java | 7 ++- .../hadoop/util/dynamic/TestDynMethods.java | 41 +++++++-------- .../org/apache/hadoop/util/hash/TestHash.java | 4 +- 14 files changed, 95 insertions(+), 102 deletions(-) diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java index 95400bb7f2734..1c8aa67c56259 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestCacheableIPList.java @@ -46,7 +46,7 @@ public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc new FileBasedIPList("ips.txt"),100); 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"); + 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,7 +56,7 @@ public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedExc Thread.sleep(101); 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"); + assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list"); TestFileBasedIPList.removeFile("ips.txt"); } @@ -83,7 +83,7 @@ public void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte new FileBasedIPList("ips.txt"),100); 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"); + 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"}; @@ -92,7 +92,7 @@ public void testRemovalWithSleepForCacheTimeout() throws IOException, Interrupte Thread.sleep(1005); 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"); + assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is in the list"); TestFileBasedIPList.removeFile("ips.txt"); } @@ -118,7 +118,7 @@ public void testAddWithRefresh() throws IOException, InterruptedException { new FileBasedIPList("ips.txt"),100); 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"); + 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", @@ -128,7 +128,7 @@ public void testAddWithRefresh() throws IOException, InterruptedException { cipl.refresh(); 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"); + assertTrue(cipl.isIn("10.222.103.121"), "10.222.103.121 is not in the list"); TestFileBasedIPList.removeFile("ips.txt"); } @@ -155,7 +155,7 @@ public void testRemovalWithRefresh() throws IOException, InterruptedException { new FileBasedIPList("ips.txt"),100); 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"); + 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"}; @@ -164,7 +164,7 @@ public void testRemovalWithRefresh() throws IOException, InterruptedException { cipl.refresh(); 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"); + assertFalse(cipl.isIn("10.222.103.121"), "10.222.103.121 is in the list"); TestFileBasedIPList.removeFile("ips.txt"); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java index 92d4268a38e12..47dd154d96070 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDiskCheckerWithDiskIo.java @@ -29,7 +29,6 @@ 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.jupiter.api.Assertions.assertThrows; diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java index ddb8ad5859084..1de0df5720b9e 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestNativeCrc32.java @@ -94,7 +94,7 @@ public void testVerifyChunkedSumsFail(DataChecksum.Type pChecksumType) { @ParameterizedTest @MethodSource("data") public void testVerifyChunkedSumsSuccessOddSize(DataChecksum.Type pChecksumType) - throws ChecksumException { + 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 @@ -113,7 +113,7 @@ public void testVerifyChunkedSumsSuccessOddSize(DataChecksum.Type pChecksumType) @ParameterizedTest @MethodSource("data") public void testVerifyChunkedSumsByteArraySuccess(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateArrayByteBuffers(); fillDataAndValidChecksums(); @@ -138,7 +138,7 @@ public void testVerifyChunkedSumsByteArrayFail(DataChecksum.Type pChecksumType) @ParameterizedTest @MethodSource("data") public void testCalculateChunkedSumsSuccess(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateDirectByteBuffers(); fillDataAndValidChecksums(); @@ -149,7 +149,7 @@ public void testCalculateChunkedSumsSuccess(DataChecksum.Type pChecksumType) @ParameterizedTest @MethodSource("data") public void testCalculateChunkedSumsFail(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateDirectByteBuffers(); fillDataAndInvalidChecksums(); @@ -160,7 +160,7 @@ public void testCalculateChunkedSumsFail(DataChecksum.Type pChecksumType) @ParameterizedTest @MethodSource("data") public void testCalculateChunkedSumsByteArraySuccess(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateArrayByteBuffers(); fillDataAndValidChecksums(); @@ -172,7 +172,7 @@ public void testCalculateChunkedSumsByteArraySuccess(DataChecksum.Type pChecksum @ParameterizedTest @MethodSource("data") public void testCalculateChunkedSumsByteArrayFail(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateArrayByteBuffers(); fillDataAndInvalidChecksums(); @@ -185,7 +185,7 @@ public void testCalculateChunkedSumsByteArrayFail(DataChecksum.Type pChecksumTyp @MethodSource("data") @SuppressWarnings("deprecation") public void testNativeVerifyChunkedSumsSuccess(DataChecksum.Type pChecksumType) - throws ChecksumException { + throws ChecksumException { initTestNativeCrc32(pChecksumType); allocateDirectByteBuffers(); fillDataAndValidChecksums(); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java index 8430be9cc730c..ecd8bf6d2b858 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestOptions.java @@ -29,7 +29,7 @@ public void testAppend() throws Exception { 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"}, + assertArrayEquals(new String[]{"aa", "bb", "cc", "dd", "ee", "ff"}, Options.prependOptions(new String[]{"dd", "ee", "ff"}, "aa", "bb", "cc"), "second append"); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java index 38ea9c8e6c1db..9b6bd85faecd4 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestProgress.java @@ -31,15 +31,15 @@ public void testSet(){ assertEquals(0, progress.getProgress(), 0.0); progress.set(Float.NEGATIVE_INFINITY); - assertEquals(0,progress.getProgress(),0.0); + assertEquals(0, progress.getProgress(), 0.0); progress.set(-1); - assertEquals(0,progress.getProgress(),0.0); + assertEquals(0, progress.getProgress(), 0.0); progress.set((float) 1.1); - assertEquals(1,progress.getProgress(),0.0); + assertEquals(1, progress.getProgress(), 0.0); progress.set(Float.POSITIVE_INFINITY); - assertEquals(1,progress.getProgress(),0.0); + assertEquals(1, progress.getProgress(), 0.0); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java index 03f906f0cc3c7..7b1e031360a19 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestRunJar.java @@ -184,8 +184,10 @@ public void testUnJarDoesNotLooseLastModify() throws Exception { unjarDir, MATCH_ANY); String failureMessage = "Last modify time was lost during unJar"; - assertEquals(MOCKED_NOW, new File(unjarDir, TestRunJar.FOOBAR_TXT).lastModified(), failureMessage); - assertEquals(MOCKED_NOW_PLUS_TWO_SEC, new File(unjarDir, FOOBAZ_TXT).lastModified(), failureMessage); + 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) { diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java index 62cf6697fe10f..1c5dadd7a379b 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestShell.java @@ -141,7 +141,7 @@ public void testShellCommandTimeout() throws Throwable { //When timing out exception is thrown. } shellFile.delete(); - assertTrue( shexc.isTimedOut(), "Script did not timeout"); + assertTrue(shexc.isTimedOut(), "Script did not timeout"); } @Test diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java index 39c04787d22bd..e2ec83627cbce 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestStringUtils.java @@ -124,9 +124,8 @@ public void testSimpleSplit() throws Exception { "/", "////"}; for (String testSubject : TO_TEST) { - assertArrayEquals( - testSubject.split("/") -, StringUtils.split(testSubject, '/'), "Testing '" + testSubject + "'"); + assertArrayEquals(testSubject.split("/"), + StringUtils.split(testSubject, '/'), "Testing '" + testSubject + "'"); } } @@ -383,7 +382,7 @@ public void testStringToURI() { @Timeout(value = 30) public void testSimpleHostName() { assertEquals("hadoop01", StringUtils.simpleHostname("hadoop01.domain.com"), - "Should return hostname when FQDN is specified"); + "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"), @@ -481,8 +480,8 @@ public void run() { FAST_DATE_FORMAT, start, end); String formattedTime2 = StringUtils.getFormattedTimeWithDiff( FAST_DATE_FORMAT, start, end); - assertTrue(formattedTime1.equals(formattedTime2), "Method returned inconsistent results indicative of" - + " a race condition"); + assertTrue(formattedTime1.equals(formattedTime2), + "Method returned inconsistent results indicative of a race condition"); } }); @@ -497,16 +496,14 @@ public void testFormatTimeSortable() { long timeDiff = 523452311; String timeDiffStr = "99hrs, 59mins, 59sec"; - assertEquals(timeDiffStr -, StringUtils.formatTimeSortable(timeDiff), "Incorrect time diff string returned"); + assertEquals(timeDiffStr, StringUtils.formatTimeSortable(timeDiff), + "Incorrect time diff string returned"); } @Test public void testIsAlpha() { - assertTrue( - StringUtils.isAlpha("hello"), "Reported hello as non-alpha string"); - assertFalse( - StringUtils.isAlpha("hello1"), "Reported hello1 as alpha string"); + assertTrue(StringUtils.isAlpha("hello"), "Reported hello as non-alpha string"); + assertFalse(StringUtils.isAlpha("hello1"), "Reported hello1 as alpha string"); } @Test @@ -514,8 +511,8 @@ public void testEscapeHTML() { String htmlStr = "

Hello. How are you?

"; String escapedStr = "<p>Hello. How are you?</p>"; - assertEquals( - escapedStr, StringUtils.escapeHTML(htmlStr), "Incorrect escaped HTML string returned"); + assertEquals(escapedStr, StringUtils.escapeHTML(htmlStr), + "Incorrect escaped HTML string returned"); } @Test diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java index 92fb32e65ff46..85b308111d129 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java @@ -58,8 +58,8 @@ public void setUp() throws IOException { // Not supported on non-Windows platforms assumeWindows(); TEST_DIR.mkdirs(); - assertTrue( - TEST_DIR.isDirectory(), "Failed to create Test directory " + TEST_DIR ); + assertTrue(TEST_DIR.isDirectory(), + "Failed to create Test directory " + TEST_DIR ); winutils = Shell.getWinUtilsPath(); } @@ -342,11 +342,12 @@ public void testBasicChmodOnDir() throws IOException { // 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( - b.delete(), "Special behavior: deleting a file will succeed on Windows " + 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(b.renameTo(new File(a, "d")), "Renaming a file should fail on the dir where a user does " + 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 diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java index c99856debb64e..8c7d4531bedde 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java @@ -115,8 +115,8 @@ public void testExternalDtdWithSecureTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer(); try ( - InputStream stream = getResourceStream("/xml/external-dtd.xml"); - StringWriter stringWriter = new StringWriter() + InputStream stream = getResourceStream("/xml/external-dtd.xml"); + StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); } @@ -139,8 +139,8 @@ public void testExternalDtdWithSecureSAXTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer(); try ( - InputStream stream = getResourceStream("/xml/external-dtd.xml"); - StringWriter stringWriter = new StringWriter() + InputStream stream = getResourceStream("/xml/external-dtd.xml"); + StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java index 8c9e28875a0dd..43be057e670b2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/bloom/BloomFilterCommonTester.java @@ -152,17 +152,17 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, filter.add(keys); - assertTrue( - filter.membershipTest(new Key("100".getBytes())), " might contain key error "); - assertTrue( - filter.membershipTest(new Key("200".getBytes())), " might contain key error "); + 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( - filter.membershipTest(new Key("100".getBytes())), " might contain key error "); - assertTrue( - filter.membershipTest(new Key("200".getBytes())), " might contain key error "); + 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() { @@ -178,10 +178,10 @@ public int size() { }); - assertTrue( - filter.membershipTest(new Key("100".getBytes())), " might contain key error "); - assertTrue( - filter.membershipTest(new Key("200".getBytes())), " might contain key error "); + assertTrue(filter.membershipTest(new Key("100".getBytes())), + " might contain key error "); + assertTrue(filter.membershipTest(new Key("200".getBytes())), + " might contain key error "); } }), @@ -357,15 +357,15 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // check on present even key for (int i = 0; i < numInsertions; i += 2) { - assertTrue( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); + 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.membershipTest(new Key(Integer.toString(i).getBytes())), " filter should not contain " + i); + assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " filter should not contain " + i); } } } @@ -402,8 +402,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, tempFilter.readFields(in); for (Integer slot : list) { - assertTrue( - filter.membershipTest(new Key(String.valueOf(slot).getBytes())), "read/write mask check filter error on " + slot); + assertTrue(filter.membershipTest(new Key(String.valueOf(slot).getBytes())), + "read/write mask check filter error on " + slot); } } catch (IOException ex) { @@ -424,8 +424,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, filter.xor(symmetricFilter); // check on present all key for (int i = 0; i < numInsertions; i++) { - assertFalse( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); + assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " filter might contains " + i); } // add all even keys @@ -442,8 +442,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // 1 xor 1 -> 0 // check on absent all key for (int i = 0; i < numInsertions; i++) { - assertFalse( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might not contains " + i); + assertFalse(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " filter might not contains " + i); } } catch (UnsupportedOperationException ex) { @@ -478,8 +478,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, for (int i = 0; i < numInsertions; i++) { if (i >= startIntersection && i <= endIntersection) { - assertTrue( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); + assertTrue(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " filter might contains " + i); } } } @@ -508,8 +508,8 @@ public void assertWhat(Filter filter, int numInsertions, int hashId, // check on present all key for (int i = 0; i < numInsertions; i++) { - assertTrue( - filter.membershipTest(new Key(Integer.toString(i).getBytes())), " filter might contains " + i); + assertTrue(filter.membershipTest(new Key(Integer.toString(i).getBytes())), + " filter might contains " + i); } } }); diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java index 5c211252415e3..84af38ce46129 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynConstructors.java @@ -164,9 +164,8 @@ public void testInvoke() throws Exception { intercept(IllegalArgumentException.class, () -> ctor.invoke("a")); - assertNotNull( - ctor.invokeChecked(null), "Should allow invokeChecked(null, ...)"); - assertNotNull( - ctor.invoke(null), "Should allow invoke(null, ...)"); + assertNotNull(ctor.invokeChecked(null), + "Should allow invokeChecked(null, ...)"); + assertNotNull(ctor.invoke(null), "Should allow invoke(null, ...)"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java index 1a1082e3a5c41..bfd94b25897fa 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/dynamic/TestDynMethods.java @@ -113,7 +113,8 @@ public void testVarArgs() throws Exception { assertEquals("abcde", cat.bind(new Concatenator()) - .invokeChecked((Object) new String[]{"a", "b", "c", "d", "e"}), "Should use the varargs version"); + .invokeChecked((Object) new String[]{"a", "b", "c", "d", "e"}), + "Should use the varargs version"); } @Test @@ -252,8 +253,8 @@ public void testNonStaticMethod() throws Exception { intercept(IllegalStateException.class, builder::buildStaticChecked); final DynMethods.UnboundMethod cat2 = builder.buildChecked(); - assertFalse( - cat2.isStatic(), "concat(String,String) should not be static"); + assertFalse(cat2.isStatic(), + "concat(String,String) should not be static"); intercept(IllegalStateException.class, cat2::asStatic); } @@ -265,12 +266,11 @@ public void testConstructorImpl() throws Exception { .impl(Concatenator.class, String.class); DynMethods.UnboundMethod newConcatenator = builder.buildChecked(); - 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"); + 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, () -> @@ -294,8 +294,8 @@ public void testConstructorImplAfterFactoryMethod() throws Exception { .ctorImpl(Concatenator.class, String.class) .buildChecked(); - assertFalse( - newConcatenator instanceof DynConstructors.Ctor, "Should find factory method before constructor method"); + assertFalse(newConcatenator instanceof DynConstructors.Ctor, + "Should find factory method before constructor method"); } @Test @@ -306,17 +306,12 @@ public void testNoop() throws Exception { .orNoop() .buildChecked(); - 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"); + 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"); } } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java index 32c6dd0b60f39..565d9f7a6d0e2 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/hash/TestHash.java @@ -63,7 +63,7 @@ public void testHash() { murmurHash = Hash.getInstance(Hash.MURMUR_HASH).hash(LINE.getBytes(), 67); for (int i = 0; i < iterations; i++) { - assertTrue( murmurHash == Hash.getInstance(Hash.MURMUR_HASH).hash( + assertTrue(murmurHash == Hash.getInstance(Hash.MURMUR_HASH).hash( LINE.getBytes(), 67), "multiple evaluation murmur hash error !!!"); } @@ -76,7 +76,7 @@ public void testHash() { jenkinsHash = Hash.getInstance(Hash.JENKINS_HASH).hash(LINE.getBytes(), 67); for (int i = 0; i < iterations; i++) { assertTrue(jenkinsHash == Hash.getInstance(Hash.JENKINS_HASH).hash( - LINE.getBytes(), 67), "multiple evaluation jenkins hash error !!!"); + LINE.getBytes(), 67), "multiple evaluation jenkins hash error !!!"); } } } From 7d361f3cd112fa883cd1d46644ace37d40340251 Mon Sep 17 00:00:00 2001 From: fanshilun Date: Fri, 7 Feb 2025 18:04:39 +0800 Subject: [PATCH 5/5] HADOOP-19415. Fix CheckStyle. --- .../test/java/org/apache/hadoop/util/TestWinUtils.java | 2 +- .../test/java/org/apache/hadoop/util/TestXMLUtils.java | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java index 85b308111d129..1450f9de98f09 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java @@ -59,7 +59,7 @@ public void setUp() throws IOException { assumeWindows(); TEST_DIR.mkdirs(); assertTrue(TEST_DIR.isDirectory(), - "Failed to create Test directory " + TEST_DIR ); + "Failed to create Test directory " + TEST_DIR); winutils = Shell.getWinUtilsPath(); } diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java index 8c7d4531bedde..1724be2764ad0 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java @@ -115,8 +115,8 @@ public void testExternalDtdWithSecureTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer(); try ( - InputStream stream = getResourceStream("/xml/external-dtd.xml"); - StringWriter stringWriter = new StringWriter() + InputStream stream = getResourceStream("/xml/external-dtd.xml"); + StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); } @@ -139,8 +139,8 @@ public void testExternalDtdWithSecureSAXTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer(); try ( - InputStream stream = getResourceStream("/xml/external-dtd.xml"); - StringWriter stringWriter = new StringWriter() + InputStream stream = getResourceStream("/xml/external-dtd.xml"); + StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); }