Selaa lähdekoodia

YARN-11263. [JDK17] Upgrade JUnit from 4 to 5 in hadoop-yarn-server-nodemanager Part2. (#7455)

[JDK17] Upgrade JUnit from 4 to 5 in hadoop-yarn-server-nodemanager Part2.

Co-authored-by: Ayush Saxena <ayushsaxena@apache.org>
Co-authored-by: Chris Nauroth <cnauroth@apache.org>
Co-authored-by: Hualong Zhang <hualong.z@hotmail.com>
Reviewed-by: Ayush Saxena <ayushsaxena@apache.org>
Reviewed-by: Chris Nauroth <cnauroth@apache.org>
Reviewed-by: Hualong Zhang <hualong.z@hotmail.com>
Signed-off-by: Shilun Fan <slfan1989@apache.org>
slfan1989 2 kuukautta sitten
vanhempi
commit
e72b2184d1
52 muutettua tiedostoa jossa 1415 lisäystä ja 1320 poistoa
  1. 5 0
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml
  2. 1 1
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java
  3. 5 4
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/NodeManagerTestBase.java
  4. 41 35
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerExecutor.java
  5. 40 37
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDefaultContainerExecutor.java
  6. 10 8
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDeletionService.java
  7. 192 185
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDirectoryCollection.java
  8. 1 1
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java
  9. 39 38
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java
  10. 45 43
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
  11. 36 36
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLocalDirsHandlerService.java
  12. 7 7
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNMAuditLogger.java
  13. 13 10
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNetworkTagMappingJsonManager.java
  14. 34 35
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManager.java
  15. 4 3
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerMXBean.java
  16. 30 31
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerReboot.java
  17. 38 34
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java
  18. 19 17
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerShutdown.java
  19. 3 3
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeResourceMonitor.java
  20. 133 122
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java
  21. 35 32
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdaterForAttributes.java
  22. 34 30
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdaterForLabels.java
  23. 8 7
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestRPCFactories.java
  24. 6 4
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestRecordFactory.java
  25. 1 1
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestExceptionReporter.java
  26. 30 29
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestNodeHealthCheckerService.java
  27. 24 27
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestNodeHealthScriptRunner.java
  28. 26 25
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/logaggregation/tracker/TestNMLogAggregationStatusTracker.java
  29. 20 16
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/metrics/TestNodeManagerMetrics.java
  30. 44 38
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestConfigurationNodeAttributesProvider.java
  31. 15 15
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestConfigurationNodeLabelsProvider.java
  32. 24 22
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestScriptBasedNodeAttributesProvider.java
  33. 24 21
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestScriptBasedNodeLabelsProvider.java
  34. 30 30
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/recovery/TestNMLeveldbStateStoreService.java
  35. 33 29
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/scheduler/TestDistributedScheduler.java
  36. 6 6
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/security/TestNMContainerTokenSecretManager.java
  37. 6 6
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/security/TestNMTokenSecretManagerInNM.java
  38. 50 47
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.java
  39. 69 63
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestCgroupsLCEResourcesHandler.java
  40. 27 23
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestNodeManagerHardwareUtils.java
  41. 12 9
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestProcessIdFileReader.java
  42. 21 18
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
  43. 7 8
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMAppsPage.java
  44. 11 9
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMContainerWebSocket.java
  45. 6 4
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebFilter.java
  46. 10 9
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java
  47. 48 45
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServices.java
  48. 28 28
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesApps.java
  49. 16 15
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesAuxServices.java
  50. 30 34
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java
  51. 6 6
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebTerminal.java
  52. 12 14
      hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/gpu/TestGpuDeviceInformationParser.java

+ 5 - 0
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml

@@ -104,6 +104,11 @@
       <artifactId>junit-platform-launcher</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-junit-jupiter</artifactId>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>

+ 1 - 1
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java

@@ -18,7 +18,7 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 5 - 4
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/NodeManagerTestBase.java

@@ -39,8 +39,7 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb.UnRegisterNodeM
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerManagerImpl;
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
-import org.junit.Assert;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,6 +48,8 @@ import java.io.IOException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 
+import static org.junit.jupiter.api.Assertions.fail;
+
 public class NodeManagerTestBase {
   // temp fix until metrics system can auto-detect itself running in unit test:
   static {
@@ -78,7 +79,7 @@ public class NodeManagerTestBase {
       localhostAddress = InetAddress.getByName("localhost")
           .getCanonicalHostName();
     } catch (UnknownHostException e) {
-      Assert.fail("Unable to get localhost address: " + e.getMessage());
+      fail("Unable to get localhost address: " + e.getMessage());
     }
     conf.setInt(YarnConfiguration.NM_PMEM_MB, 5 * 1024); // 5GB
     conf.set(YarnConfiguration.NM_ADDRESS, localhostAddress + ":" + port);
@@ -154,7 +155,7 @@ public class NodeManagerTestBase {
     }
   }
 
-  @Before
+  @BeforeEach
   public void setUp() throws IOException {
     nmLocalDir.mkdirs();
     tmpDir.mkdirs();

+ 41 - 35
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerExecutor.java

@@ -48,13 +48,14 @@ import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerExecContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerReacquisitionContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerReapContext;
 import org.apache.hadoop.yarn.server.nodemanager.util.NodeManagerHardwareUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.apache.hadoop.test.PlatformAssumptions.assumeWindows;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
@@ -68,28 +69,30 @@ public class TestContainerExecutor {
   
   private ContainerExecutor containerExecutor = new DefaultContainerExecutor();
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRunCommandNoPriority() throws Exception {
     Configuration conf = new Configuration();
     String[] command = containerExecutor.getRunCommand("echo", "group1", "user", null, conf);
-    assertTrue("first command should be the run command for the platform", 
-               command[0].equals(Shell.WINUTILS) || command[0].equals("bash"));  
+    assertTrue(command[0].equals(Shell.WINUTILS) || command[0].equals("bash"),
+        "first command should be the run command for the platform");
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRunCommandwithPriority() throws Exception {
     Configuration conf = new Configuration();
     conf.setInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, 2);
     String[] command = containerExecutor.getRunCommand("echo", "group1", "user", null, conf);
     if (Shell.WINDOWS) {
       // windows doesn't currently support
-      assertEquals("first command should be the run command for the platform", 
-               Shell.WINUTILS, command[0]); 
+      assertEquals(Shell.WINUTILS, command[0],
+          "first command should be the run command for the platform");
     } else {
-      assertEquals("first command should be nice", "nice", command[0]); 
-      assertEquals("second command should be -n", "-n", command[1]); 
-      assertEquals("third command should be the priority", Integer.toString(2),
-                   command[2]); 
+      assertEquals("nice", command[0], "first command should be nice");
+      assertEquals("-n", command[1], "second command should be -n");
+      assertEquals(Integer.toString(2), command[2],
+          "third command should be the priority");
     }
 
     // test with negative number
@@ -97,17 +100,18 @@ public class TestContainerExecutor {
     command = containerExecutor.getRunCommand("echo", "group1", "user", null, conf);
     if (Shell.WINDOWS) {
       // windows doesn't currently support
-      assertEquals("first command should be the run command for the platform", 
-               Shell.WINUTILS, command[0]); 
+      assertEquals(Shell.WINUTILS, command[0],
+          "first command should be the run command for the platform");
     } else {
-      assertEquals("first command should be nice", "nice", command[0]); 
-      assertEquals("second command should be -n", "-n", command[1]); 
-      assertEquals("third command should be the priority", Integer.toString(-5),
-                    command[2]); 
+      assertEquals("nice", command[0], "first command should be nice");
+      assertEquals("-n", command[1], "second command should be -n");
+      assertEquals(Integer.toString(-5),
+          command[2], "third command should be the priority");
     }
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRunCommandWithNoResources() {
     assumeWindows();
     Configuration conf = new Configuration();
@@ -116,10 +120,11 @@ public class TestContainerExecutor {
     // Assert the cpu and memory limits are set correctly in the command
     String[] expected = { Shell.WINUTILS, "task", "create", "-m", "-1", "-c",
         "-1", "group1", "cmd /c " + "echo" };
-    Assert.assertTrue(Arrays.equals(expected, command));
+    assertTrue(Arrays.equals(expected, command));
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRunCommandWithMemoryOnlyResources() {
     assumeWindows();
     Configuration conf = new Configuration();
@@ -129,10 +134,11 @@ public class TestContainerExecutor {
     // Assert the cpu and memory limits are set correctly in the command
     String[] expected = { Shell.WINUTILS, "task", "create", "-m", "1024", "-c",
         "-1", "group1", "cmd /c " + "echo" };
-    Assert.assertTrue(Arrays.equals(expected, command));
+    assertTrue(Arrays.equals(expected, command));
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRunCommandWithCpuAndMemoryResources() {
     assumeWindows();
     int containerCores = 1;
@@ -144,39 +150,39 @@ public class TestContainerExecutor {
         containerExecutor.getRunCommand("echo", "group1", null, null, conf,
           Resource.newInstance(1024, 1));
     int nodeVCores = NodeManagerHardwareUtils.getVCores(conf);
-    Assert.assertEquals(YarnConfiguration.DEFAULT_NM_VCORES, nodeVCores);
+    assertEquals(YarnConfiguration.DEFAULT_NM_VCORES, nodeVCores);
     int cpuRate = Math.min(10000, (containerCores * 10000) / nodeVCores);
 
     // Assert the cpu and memory limits are set correctly in the command
     String[] expected =
         {Shell.WINUTILS, "task", "create", "-m", "1024", "-c",
             String.valueOf(cpuRate), "group1", "cmd /c " + "echo" };
-    Assert.assertEquals(Arrays.toString(expected), Arrays.toString(command));
+    assertEquals(Arrays.toString(expected), Arrays.toString(command));
 
     conf.setBoolean(YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION,
         true);
     int nodeCPUs = NodeManagerHardwareUtils.getNodeCPUs(conf);
     float yarnCPUs = NodeManagerHardwareUtils.getContainersCPUs(conf);
     nodeVCores = NodeManagerHardwareUtils.getVCores(conf);
-    Assert.assertEquals(nodeCPUs, (int) yarnCPUs);
-    Assert.assertEquals(nodeCPUs, nodeVCores);
+    assertEquals(nodeCPUs, (int) yarnCPUs);
+    assertEquals(nodeCPUs, nodeVCores);
     command =
         containerExecutor.getRunCommand("echo", "group1", null, null, conf,
           Resource.newInstance(1024, 1));
     cpuRate = Math.min(10000, (containerCores * 10000) / nodeVCores);
     expected[6] = String.valueOf(cpuRate);
-    Assert.assertEquals(Arrays.toString(expected), Arrays.toString(command));
+    assertEquals(Arrays.toString(expected), Arrays.toString(command));
 
     int yarnCpuLimit = 80;
     conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
         yarnCpuLimit);
     yarnCPUs = NodeManagerHardwareUtils.getContainersCPUs(conf);
     nodeVCores = NodeManagerHardwareUtils.getVCores(conf);
-    Assert.assertEquals(nodeCPUs * 0.8, yarnCPUs, 0.01);
+    assertEquals(nodeCPUs * 0.8, yarnCPUs, 0.01);
     if (nodeCPUs == 1) {
-      Assert.assertEquals(1, nodeVCores);
+      assertEquals(1, nodeVCores);
     } else {
-      Assert.assertEquals((int) (nodeCPUs * 0.8), nodeVCores);
+      assertEquals((int) (nodeCPUs * 0.8), nodeVCores);
     }
     command =
         containerExecutor.getRunCommand("echo", "group1", null, null, conf,
@@ -185,7 +191,7 @@ public class TestContainerExecutor {
     int containerPerc = (yarnCpuLimit * containerCores) / nodeVCores;
     cpuRate = Math.min(10000, 100 * containerPerc);
     expected[6] = String.valueOf(cpuRate);
-    Assert.assertEquals(Arrays.toString(expected), Arrays.toString(command));
+    assertEquals(Arrays.toString(expected), Arrays.toString(command));
   }
 
   @Test
@@ -206,7 +212,7 @@ public class TestContainerExecutor {
       containerExecutor.execContainer(ctx);
     } catch (Exception e) {
       // socket exception should be thrown immediately, without RPC retries.
-      Assert.assertTrue(e instanceof ContainerExecutionException);
+      assertTrue(e instanceof ContainerExecutionException);
     }
   }
 
@@ -228,7 +234,7 @@ public class TestContainerExecutor {
         .thenReturn(localResources);
     when(container.getUser()).thenReturn(System.getProperty("user.name"));
     containerExecutor.cleanupBeforeRelaunch(container);
-    Assert.assertTrue(!Files.exists(linkName));
+    assertTrue(!Files.exists(linkName));
   }
 
   /**

+ 40 - 37
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDefaultContainerExecutor.java

@@ -20,8 +20,11 @@ package org.apache.hadoop.yarn.server.nodemanager;
 
 import static org.apache.hadoop.fs.CreateFlag.CREATE;
 import static org.apache.hadoop.fs.CreateFlag.OVERWRITE;
-import static org.junit.Assert.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.isA;
@@ -85,10 +88,10 @@ import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -105,7 +108,7 @@ public class TestDefaultContainerExecutor {
 
   private NumaResourceAllocator numaResourceAllocator;
 
-  @AfterClass
+  @AfterAll
   public static void deleteTmpFiles() throws IOException {
     FileContext lfs = FileContext.getLocalFSFileContext();
     try {
@@ -169,7 +172,7 @@ public class TestDefaultContainerExecutor {
       for (String dir : localDirs) {
         FileStatus stats = lfs.getFileStatus(
             new Path(new Path(dir, ContainerLocalizer.USERCACHE), user));
-        Assert.assertEquals(userCachePerm, stats.getPermission());
+        assertEquals(userCachePerm, stats.getPermission());
       }
 
       for (String dir : localDirs) {
@@ -178,12 +181,12 @@ public class TestDefaultContainerExecutor {
         Path appCachePath = new Path(userCachePath,
             ContainerLocalizer.APPCACHE);
         FileStatus stats = lfs.getFileStatus(appCachePath);
-        Assert.assertEquals(appCachePerm, stats.getPermission());
+        assertEquals(appCachePerm, stats.getPermission());
         stats = lfs.getFileStatus(
             new Path(userCachePath, ContainerLocalizer.FILECACHE));
-        Assert.assertEquals(fileCachePerm, stats.getPermission());
+        assertEquals(fileCachePerm, stats.getPermission());
         stats = lfs.getFileStatus(new Path(appCachePath, appId));
-        Assert.assertEquals(appDirPerm, stats.getPermission());
+        assertEquals(appDirPerm, stats.getPermission());
       }
 
       String[] permissionsArray = { "000", "111", "555", "710", "777" };
@@ -197,7 +200,7 @@ public class TestDefaultContainerExecutor {
 
         for (String dir : logDirs) {
           FileStatus stats = lfs.getFileStatus(new Path(dir, appId));
-          Assert.assertEquals(logDirPerm, stats.getPermission());
+          assertEquals(logDirPerm, stats.getPermission());
           lfs.delete(new Path(dir, appId), true);
         }
       }
@@ -310,7 +313,7 @@ public class TestDefaultContainerExecutor {
     lfs.delete(workDir, true);
     try {
       lfs.getFileStatus(workDir);
-      Assert.fail("Expected FileNotFoundException on " + workDir);
+      fail("Expected FileNotFoundException on " + workDir);
     } catch (FileNotFoundException e) {
       // expected
     }
@@ -326,33 +329,33 @@ public class TestDefaultContainerExecutor {
     Path finalTrustorePath = new Path(workDir,
         ContainerLaunch.TRUSTSTORE_FILE);
 
-    Assert.assertTrue(lfs.getFileStatus(workDir).isDirectory());
-    Assert.assertTrue(lfs.getFileStatus(finalScriptPath).isFile());
-    Assert.assertTrue(lfs.getFileStatus(finalTokensPath).isFile());
+    assertTrue(lfs.getFileStatus(workDir).isDirectory());
+    assertTrue(lfs.getFileStatus(finalScriptPath).isFile());
+    assertTrue(lfs.getFileStatus(finalTokensPath).isFile());
     if (https) {
-      Assert.assertTrue(lfs.getFileStatus(finalKeystorePath).isFile());
-      Assert.assertTrue(lfs.getFileStatus(finalTrustorePath).isFile());
+      assertTrue(lfs.getFileStatus(finalKeystorePath).isFile());
+      assertTrue(lfs.getFileStatus(finalTrustorePath).isFile());
     } else {
       try {
         lfs.getFileStatus(finalKeystorePath);
-        Assert.fail("Expected FileNotFoundException on " + finalKeystorePath);
+        fail("Expected FileNotFoundException on " + finalKeystorePath);
       } catch (FileNotFoundException e) {
         // expected
       }
       try {
         lfs.getFileStatus(finalTrustorePath);
-        Assert.fail("Expected FileNotFoundException on " + finalKeystorePath);
+        fail("Expected FileNotFoundException on " + finalKeystorePath);
       } catch (FileNotFoundException e) {
         // expected
       }
     }
 
-    Assert.assertEquals("script", readStringFromPath(lfs, finalScriptPath));
-    Assert.assertEquals("tokens", readStringFromPath(lfs, finalTokensPath));
+    assertEquals("script", readStringFromPath(lfs, finalScriptPath));
+    assertEquals("tokens", readStringFromPath(lfs, finalTokensPath));
     if (https) {
-      Assert.assertEquals("keystore", readStringFromPath(lfs,
+      assertEquals("keystore", readStringFromPath(lfs,
           finalKeystorePath));
-      Assert.assertEquals("truststore", readStringFromPath(lfs,
+      assertEquals("truststore", readStringFromPath(lfs,
           finalTrustorePath));
     }
   }
@@ -388,8 +391,8 @@ public class TestDefaultContainerExecutor {
           public Object answer(InvocationOnMock invocationOnMock)
               throws Throwable {
             String diagnostics = (String) invocationOnMock.getArguments()[0];
-            assertTrue("Invalid Diagnostics message: " + diagnostics,
-                diagnostics.contains("No such file or directory"));
+            assertTrue(diagnostics.contains("No such file or directory"),
+                "Invalid Diagnostics message: " + diagnostics);
             return null;
           }
         }
@@ -414,10 +417,9 @@ public class TestDefaultContainerExecutor {
           ContainerDiagnosticsUpdateEvent event =
               (ContainerDiagnosticsUpdateEvent) invocationOnMock
                   .getArguments()[0];
-          assertTrue("Invalid Diagnostics message: "
-                  + event.getDiagnosticsUpdate(),
-              event.getDiagnosticsUpdate().contains("No such file or directory")
-          );
+          assertTrue(event.getDiagnosticsUpdate().contains("No such file or directory"),
+              "Invalid Diagnostics message: "
+              + event.getDiagnosticsUpdate());
           return null;
         }
       }).when(container).handle(any(ContainerDiagnosticsUpdateEvent.class));
@@ -465,7 +467,7 @@ public class TestDefaultContainerExecutor {
           .setLocalDirs(localDirs)
           .setLogDirs(logDirs)
           .build());
-      Assert.assertNotSame(0, ret);
+      assertNotSame(0, ret);
     } finally {
       mockExec.deleteAsUser(new DeletionAsUserContext.Builder()
           .setUser(appSubmitter)
@@ -478,7 +480,8 @@ public class TestDefaultContainerExecutor {
     }
   }
 
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testStartLocalizer() throws IOException, InterruptedException,
       YarnException {
 
@@ -600,7 +603,7 @@ public class TestDefaultContainerExecutor {
           .build());
 
     } catch (IOException e) {
-      Assert.fail("StartLocalizer failed to copy token file: "
+      fail("StartLocalizer failed to copy token file: "
           + StringUtils.stringifyException(e));
     } finally {
       mockExec.deleteAsUser(new DeletionAsUserContext.Builder()
@@ -755,7 +758,7 @@ public class TestDefaultContainerExecutor {
 //        new FsPermission(ApplicationLocalizer.LOGDIR_PERM), true);
 //  }
 
-  @Before
+  @BeforeEach
   public void setUp() throws IOException, YarnException {
     yarnConfiguration = new YarnConfiguration();
     setNumaConfig();
@@ -855,7 +858,7 @@ public class TestDefaultContainerExecutor {
             ContainerId.fromString("container_1481156246874_0001_01_000004"));
     when(mockContainer.getResource())
             .thenReturn(Resource.newInstance(80000, 2));
-    Assert.assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
+    assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
 
     // allocates node 1 for memory and cpu
     testAllocateNumaResource("container_1481156246874_0001_01_000005",
@@ -882,7 +885,7 @@ public class TestDefaultContainerExecutor {
     when(mockContainer.getContainerId()).thenReturn(
             ContainerId.fromString("container_1481156246874_0001_01_000004"));
     when(mockContainer.getResource()).thenReturn(Resource.newInstance(2048, 2));
-    Assert.assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
+    assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
 
     // allocates node 1 for memory and cpu
     testAllocateNumaResource("container_1481156246874_0001_01_000005",
@@ -933,7 +936,7 @@ public class TestDefaultContainerExecutor {
             .thenReturn(Resource.newInstance(1024, 2));
 
     // returns null since there are no sufficient resources available for the request
-    Assert.assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
+    assertNull(numaResourceAllocator.allocateNumaNodes(mockContainer));
   }
 
   @Test
@@ -942,7 +945,7 @@ public class TestDefaultContainerExecutor {
     assertEquals(containerExecutor.concatStringCommands(null, new String[]{"hello"})[0],
             new String[]{"hello"}[0]);
     // test both array of string as null
-    Assert.assertNull(containerExecutor.concatStringCommands(null, null));
+    assertNull(containerExecutor.concatStringCommands(null, null));
     // test case when both arrays are not null and of equal length
     String[] res = containerExecutor.concatStringCommands(new String[]{"one"},
             new String[]{"two"});

+ 10 - 8
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDeletionService.java

@@ -18,10 +18,10 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-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.io.IOException;
 import java.util.ArrayList;
@@ -36,8 +36,9 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task.FileDeletionTask;
 import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
-import org.junit.AfterClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.mockito.Mockito;
 
 
@@ -54,7 +55,7 @@ public class TestDeletionService {
   private static final Path base =
     lfs.makeQualified(new Path("target", TestDeletionService.class.getName()));
 
-  @AfterClass
+  @AfterAll
   public static void removeBase() throws IOException {
     lfs.delete(base, true);
   }
@@ -234,7 +235,8 @@ public class TestDeletionService {
     assertTrue(del.isTerminated());
   }
   
-  @Test (timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testFileDeletionTaskDependency() throws Exception {
     FakeDefaultContainerExecutor exec = new FakeDefaultContainerExecutor();
     Configuration conf = new Configuration();

+ 192 - 185
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestDirectoryCollection.java

@@ -27,10 +27,9 @@ import java.util.List;
 import java.util.ListIterator;
 import java.util.Map;
 
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
@@ -42,6 +41,12 @@ import org.apache.hadoop.fs.permission.FsPermission;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.nodemanager.DirectoryCollection.DirsChangeListener;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 public class TestDirectoryCollection {
 
   private File testDir;
@@ -50,7 +55,7 @@ public class TestDirectoryCollection {
   private Configuration conf;
   private FileContext localFs;
 
-  @Before
+  @BeforeEach
   public void setupForTests() throws IOException {
     conf = new Configuration();
     localFs = FileContext.getLocalFSFileContext(conf);
@@ -59,7 +64,7 @@ public class TestDirectoryCollection {
     testFile.createNewFile();
   }
 
-  @After
+  @AfterEach
   public void teardown() {
     FileUtil.fullyDelete(testDir);
   }
@@ -81,8 +86,8 @@ public class TestDirectoryCollection {
     // DiskErrorException will invalidate iterator of non-concurrent
     // collections. ConcurrentModificationException will be thrown upon next
     // use of the iterator.
-    Assert.assertTrue("checkDirs did not remove test file from directory list",
-        dc.checkDirs());
+    assertTrue(dc.checkDirs(),
+        "checkDirs did not remove test file from directory list");
 
     // Verify no ConcurrentModification is thrown
     li.next();
@@ -110,17 +115,17 @@ public class TestDirectoryCollection {
     FsPermission defaultPerm = FsPermission.getDefault()
         .applyUMask(new FsPermission((short)FsPermission.DEFAULT_UMASK));
     boolean createResult = dc.createNonExistentDirs(localFs, defaultPerm);
-    Assert.assertTrue(createResult);
+    assertTrue(createResult);
 
     FileStatus status = localFs.getFileStatus(new Path(dirA));
-    Assert.assertEquals("local dir parent not created with proper permissions",
-        defaultPerm, status.getPermission());
+    assertEquals(defaultPerm, status.getPermission(),
+        "local dir parent not created with proper permissions");
     status = localFs.getFileStatus(new Path(dirB));
-    Assert.assertEquals("local dir not created with proper permissions",
-        defaultPerm, status.getPermission());
+    assertEquals(defaultPerm, status.getPermission(),
+        "local dir not created with proper permissions");
     status = localFs.getFileStatus(pathC);
-    Assert.assertEquals("existing local directory permissions modified",
-        permDirC, status.getPermission());
+    assertEquals(permDirC, status.getPermission(),
+        "existing local directory permissions modified");
   }
   
   @Test
@@ -130,52 +135,53 @@ public class TestDirectoryCollection {
     String[] dirs = { dirA };
     DirectoryCollection dc = new DirectoryCollection(dirs, 0.0F);
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(1, dc.getFullDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirA));
-    Assert.assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL, dc.getDirectoryErrorInfo(dirA).cause);
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(1, dc.getFullDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL,
+        dc.getDirectoryErrorInfo(dirA).cause);
 
     // no good dirs
-    Assert.assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
+    assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs, 100.0F);
     int utilizedSpacePerc =
         (int) ((testDir.getTotalSpace() - testDir.getUsableSpace()) * 100 /
             testDir.getTotalSpace());
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
-    Assert.assertEquals(utilizedSpacePerc,
+    assertEquals(utilizedSpacePerc,
       dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs, testDir.getTotalSpace() / (1024 * 1024));
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(1, dc.getFullDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(1, dc.getFullDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirA));
     // no good dirs
-    Assert.assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
+    assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs, 100.0F, 100.0F, 0);
     utilizedSpacePerc =
         (int)((testDir.getTotalSpace() - testDir.getUsableSpace()) * 100 /
             testDir.getTotalSpace());
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
-    Assert.assertEquals(utilizedSpacePerc,
+    assertEquals(utilizedSpacePerc,
       dc.getGoodDirsDiskUtilizationPercentage());
   }
 
@@ -188,30 +194,30 @@ public class TestDirectoryCollection {
 
     // Disable disk utilization threshold.
     dc.setDiskUtilizationThresholdEnabled(false);
-    Assert.assertFalse(dc.getDiskUtilizationThresholdEnabled());
+    assertFalse(dc.getDiskUtilizationThresholdEnabled());
 
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
     // Enable disk utilization threshold.
     dc.setDiskUtilizationThresholdEnabled(true);
-    Assert.assertTrue(dc.getDiskUtilizationThresholdEnabled());
+    assertTrue(dc.getDiskUtilizationThresholdEnabled());
 
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(1, dc.getFullDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirA));
-    Assert.assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL,
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(1, dc.getFullDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL,
         dc.getDirectoryErrorInfo(dirA).cause);
 
     // no good dirs
-    Assert.assertEquals(0,
+    assertEquals(0,
         dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs, 100.0F);
@@ -219,13 +225,13 @@ public class TestDirectoryCollection {
         (int) ((testDir.getTotalSpace() - testDir.getUsableSpace()) * 100 /
             testDir.getTotalSpace());
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
-    Assert.assertEquals(utilizedSpacePerc,
+    assertEquals(utilizedSpacePerc,
         dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs,
@@ -233,48 +239,48 @@ public class TestDirectoryCollection {
 
     // Disable disk utilization threshold.
     dc.setDiskUtilizationThresholdEnabled(false);
-    Assert.assertFalse(dc.getDiskUtilizationThresholdEnabled());
+    assertFalse(dc.getDiskUtilizationThresholdEnabled());
 
     // Disable disk free space threshold.
     dc.setDiskFreeSpaceThresholdEnabled(false);
-    Assert.assertFalse(dc.getDiskFreeSpaceThresholdEnabled());
+    assertFalse(dc.getDiskFreeSpaceThresholdEnabled());
     dc.checkDirs();
 
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
     dc = new DirectoryCollection(dirs,
         testDir.getTotalSpace() / (1024 * 1024));
 
     // Enable disk free space threshold.
     dc.setDiskFreeSpaceThresholdEnabled(true);
-    Assert.assertTrue(dc.getDiskFreeSpaceThresholdEnabled());
+    assertTrue(dc.getDiskFreeSpaceThresholdEnabled());
 
     dc.checkDirs();
 
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(1, dc.getFullDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(1, dc.getFullDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirA));
     // no good dirs
-    Assert.assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
+    assertEquals(0, dc.getGoodDirsDiskUtilizationPercentage());
 
     dc = new DirectoryCollection(dirs, 100.0F, 100.0F, 0);
     utilizedSpacePerc =
         (int)((testDir.getTotalSpace() - testDir.getUsableSpace()) * 100 /
             testDir.getTotalSpace());
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
-    Assert.assertEquals(utilizedSpacePerc,
+    assertEquals(utilizedSpacePerc,
         dc.getGoodDirsDiskUtilizationPercentage());
   }
 
@@ -286,48 +292,48 @@ public class TestDirectoryCollection {
     float testValue = 57.5F;
     float delta = 0.1F;
     dc.setDiskUtilizationPercentageCutoff(testValue, 50.0F);
-    Assert.assertEquals(testValue, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(testValue, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(50.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(50.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
 
     testValue = -57.5F;
     dc.setDiskUtilizationPercentageCutoff(testValue, testValue);
-    Assert.assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
 
     testValue = 157.5F;
     dc.setDiskUtilizationPercentageCutoff(testValue, testValue);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
 
     long lowSpaceValue = 57;
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue);
-    Assert.assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
     long highSpaceValue = 73;
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue, highSpaceValue);
-    Assert.assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(highSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(highSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
     lowSpaceValue = -57;
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue, highSpaceValue);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(highSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(highSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
     highSpaceValue = -10;
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue, highSpaceValue);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
     lowSpaceValue = 33;
     dc.setDiskUtilizationSpaceCutoff(lowSpaceValue, highSpaceValue);
-    Assert.assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(lowSpaceValue, dc.getDiskUtilizationSpaceCutoffHigh());
 
   }
 
@@ -338,20 +344,21 @@ public class TestDirectoryCollection {
     String[] dirs = { dirA };
     DirectoryCollection dc = new DirectoryCollection(dirs, 0.0F);
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(1, dc.getFullDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirA));
-    Assert.assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL, dc.getDirectoryErrorInfo(dirA).cause);
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(1, dc.getFullDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(DirectoryCollection.DiskErrorCause.DISK_FULL,
+        dc.getDirectoryErrorInfo(dirA).cause);
 
     dc.setDiskUtilizationPercentageCutoff(100.0F, 100.0F);
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
 
     conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
 
@@ -366,21 +373,21 @@ public class TestDirectoryCollection {
 
     dc = new DirectoryCollection(dirs2, 100.0F);
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(1, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertEquals(1, dc.getErroredDirs().size());
-    Assert.assertNotNull(dc.getDirectoryErrorInfo(dirB));
-    Assert.assertEquals(DirectoryCollection.DiskErrorCause.OTHER, dc.getDirectoryErrorInfo(dirB).cause);
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(1, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertEquals(1, dc.getErroredDirs().size());
+    assertNotNull(dc.getDirectoryErrorInfo(dirB));
+    assertEquals(DirectoryCollection.DiskErrorCause.OTHER, dc.getDirectoryErrorInfo(dirB).cause);
 
     permDirB = new FsPermission((short) 0700);
     localFs.setPermission(pathB, permDirB);
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(0, dc.getFailedDirs().size());
-    Assert.assertEquals(0, dc.getFullDirs().size());
-    Assert.assertEquals(0, dc.getErroredDirs().size());
-    Assert.assertNull(dc.getDirectoryErrorInfo(dirA));
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(0, dc.getFailedDirs().size());
+    assertEquals(0, dc.getFullDirs().size());
+    assertEquals(0, dc.getErroredDirs().size());
+    assertNull(dc.getDirectoryErrorInfo(dirA));
   }
 
   @Test
@@ -389,100 +396,100 @@ public class TestDirectoryCollection {
     String[] dirs = { "dir" };
     float delta = 0.1F;
     DirectoryCollection dc = new DirectoryCollection(dirs);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57.5F);
-    Assert.assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57, 73);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(73, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(73, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57, 33);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57, -33);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(57, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, -57, -33);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, -57, 33);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(33, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(33, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 57.5F, 50.5F, 67);
-    Assert.assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(57.5F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(50.5F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(50.5F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(67, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(67, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(67, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(67, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, -57.5F, -57.5F, -67);
-    Assert.assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(0.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 157.5F, 157.5F, -67);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(0, dc.getDiskUtilizationSpaceCutoffHigh());
 
     dc = new DirectoryCollection(dirs, 157.5F, 157.5F, 5, 10);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffHigh(),
         delta);
-    Assert.assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
+    assertEquals(100.0F, dc.getDiskUtilizationPercentageCutoffLow(),
         delta);
-    Assert.assertEquals(5, dc.getDiskUtilizationSpaceCutoffLow());
-    Assert.assertEquals(10, dc.getDiskUtilizationSpaceCutoffHigh());
+    assertEquals(5, dc.getDiskUtilizationSpaceCutoffLow());
+    assertEquals(10, dc.getDiskUtilizationSpaceCutoffHigh());
   }
 
   @Test
@@ -494,31 +501,31 @@ public class TestDirectoryCollection {
     String dirA = new File(testDir, "dirA").getPath();
     String[] dirs = { dirA };
     DirectoryCollection dc = new DirectoryCollection(dirs, 0.0F);
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(listener1.num, 0);
-    Assert.assertEquals(listener2.num, 0);
-    Assert.assertEquals(listener3.num, 0);
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(listener1.num, 0);
+    assertEquals(listener2.num, 0);
+    assertEquals(listener3.num, 0);
     dc.registerDirsChangeListener(listener1);
     dc.registerDirsChangeListener(listener2);
     dc.registerDirsChangeListener(listener3);
-    Assert.assertEquals(listener1.num, 1);
-    Assert.assertEquals(listener2.num, 1);
-    Assert.assertEquals(listener3.num, 1);
+    assertEquals(listener1.num, 1);
+    assertEquals(listener2.num, 1);
+    assertEquals(listener3.num, 1);
 
     dc.deregisterDirsChangeListener(listener3);
     dc.checkDirs();
-    Assert.assertEquals(0, dc.getGoodDirs().size());
-    Assert.assertEquals(listener1.num, 2);
-    Assert.assertEquals(listener2.num, 2);
-    Assert.assertEquals(listener3.num, 1);
+    assertEquals(0, dc.getGoodDirs().size());
+    assertEquals(listener1.num, 2);
+    assertEquals(listener2.num, 2);
+    assertEquals(listener3.num, 1);
 
     dc.deregisterDirsChangeListener(listener2);
     dc.setDiskUtilizationPercentageCutoff(100.0F, 100.0F);
     dc.checkDirs();
-    Assert.assertEquals(1, dc.getGoodDirs().size());
-    Assert.assertEquals(listener1.num, 3);
-    Assert.assertEquals(listener2.num, 2);
-    Assert.assertEquals(listener3.num, 1);
+    assertEquals(1, dc.getGoodDirs().size());
+    assertEquals(listener1.num, 3);
+    assertEquals(listener2.num, 2);
+    assertEquals(listener3.num, 1);
   }
 
   @Test
@@ -531,8 +538,8 @@ public class TestDirectoryCollection {
     dc.setSubAccessibilityValidationEnabled(true);
     Map<String, DirectoryCollection.DiskErrorInformation> diskErrorInformationMap =
         dc.testDirs(Collections.singletonList(testDir.toString()), Collections.emptySet());
-    Assert.assertEquals(1, diskErrorInformationMap.size());
-    Assert.assertTrue(diskErrorInformationMap.values().iterator().next()
+    assertEquals(1, diskErrorInformationMap.size());
+    assertTrue(diskErrorInformationMap.values().iterator().next()
         .message.contains(testFile.getName()));
   }
 

+ 1 - 1
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java

@@ -52,7 +52,7 @@ import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
 import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 
 public class TestEventFlow {

+ 39 - 38
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java

@@ -20,12 +20,14 @@ package org.apache.hadoop.yarn.server.nodemanager;
 
 import static org.apache.hadoop.fs.CreateFlag.CREATE;
 import static org.apache.hadoop.fs.CreateFlag.OVERWRITE;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doThrow;
@@ -81,11 +83,10 @@ import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext;
 import org.apache.hadoop.yarn.server.nodemanager.util.LCEResourcesHandler;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 /**
  * This is intended to test the LinuxContainerExecutor code, but because of some
@@ -170,7 +171,7 @@ public class TestLinuxContainerExecutor {
   private Configuration conf;
   private FileContext files;
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     files = FileContext.getLocalFSFileContext();
     Path workSpacePath = new Path(workSpace.getAbsolutePath());
@@ -216,7 +217,7 @@ public class TestLinuxContainerExecutor {
 
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     FileContext.getLocalFSFileContext().delete(
       new Path(workSpace.getAbsolutePath()), true);
@@ -360,7 +361,7 @@ public class TestLinuxContainerExecutor {
   @Test
   public void testContainerLocalizer() throws Exception {
 
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
 
     String locId = "container_01_01";
     Path nmPrivateContainerTokensPath =
@@ -418,7 +419,7 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testContainerLaunch() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
     String expectedRunAsUser =
         conf.get(YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY,
           YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER);
@@ -437,8 +438,8 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testNonSecureRunAsSubmitter() throws Exception {
-    Assume.assumeTrue(shouldRun());
-    Assume.assumeFalse(UserGroupInformation.isSecurityEnabled());
+    assumeTrue(shouldRun());
+    assumeFalse(UserGroupInformation.isSecurityEnabled());
     String expectedRunAsUser = appSubmitter;
     conf.set(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, "false");
     exec.setConf(conf);
@@ -458,7 +459,7 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testContainerKill() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
 
     final ContainerId sleepId = getNextContainerId();
     Thread t = new Thread() {
@@ -499,12 +500,12 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testCGroups() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
     String cgroupsMount = System.getProperty("cgroups.mount");
-    Assume.assumeTrue((cgroupsMount != null) && !cgroupsMount.isEmpty());
+    assumeTrue((cgroupsMount != null) && !cgroupsMount.isEmpty());
 
-    assertTrue("Cgroups mount point does not exist", new File(
-        cgroupsMount).exists());
+    assertTrue(new File(cgroupsMount).exists(),
+        "Cgroups mount point does not exist");
     List<String> cgroupKVs = new ArrayList<>();
 
     String hierarchy = "hadoop-yarn";
@@ -517,13 +518,12 @@ public class TestLinuxContainerExecutor {
     try {
       exec.mountCgroups(cgroupKVs, hierarchy);
       for (String controller : controllers) {
-        assertTrue(controller + " cgroup not mounted", new File(
-            cgroupsMount + "/" + controller + "/tasks").exists());
-        assertTrue(controller + " cgroup hierarchy not created",
-            new File(cgroupsMount + "/" + controller + "/" + hierarchy).exists());
-        assertTrue(controller + " cgroup hierarchy created incorrectly",
-            new File(cgroupsMount + "/" + controller + "/" + hierarchy
-                + "/tasks").exists());
+        assertTrue(new File(cgroupsMount + "/" + controller + "/tasks").exists(),
+            controller + " cgroup not mounted");
+        assertTrue(new File(cgroupsMount + "/" + controller + "/" + hierarchy).exists(),
+            controller + " cgroup hierarchy not created");
+        assertTrue(new File(cgroupsMount + "/" + controller + "/" + hierarchy + "/tasks").exists(),
+            controller + " cgroup hierarchy created incorrectly");
       }
     } catch (IOException ie) {
       fail("Couldn't mount cgroups " + ie.toString());
@@ -533,7 +533,7 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testLocalUser() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
     try {
       // nonsecure default
       Configuration conf = new YarnConfiguration();
@@ -542,7 +542,7 @@ public class TestLinuxContainerExecutor {
       UserGroupInformation.setConfiguration(conf);
       LinuxContainerExecutor lce = new LinuxContainerExecutor();
       lce.setConf(conf);
-      Assert.assertEquals(
+      assertEquals(
           YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER,
           lce.getRunAsUser("foo"));
 
@@ -550,14 +550,14 @@ public class TestLinuxContainerExecutor {
       conf.set(YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY, "bar");
       lce = new LinuxContainerExecutor();
       lce.setConf(conf);
-      Assert.assertEquals("bar", lce.getRunAsUser("foo"));
+      assertEquals("bar", lce.getRunAsUser("foo"));
 
       // nonsecure without limits
       conf.set(YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY, "bar");
       conf.setBoolean(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, false);
       lce = new LinuxContainerExecutor();
       lce.setConf(conf);
-      Assert.assertEquals("foo", lce.getRunAsUser("foo"));
+      assertEquals("foo", lce.getRunAsUser("foo"));
 
       // secure
       conf = new YarnConfiguration();
@@ -566,7 +566,7 @@ public class TestLinuxContainerExecutor {
       UserGroupInformation.setConfiguration(conf);
       lce = new LinuxContainerExecutor();
       lce.setConf(conf);
-      Assert.assertEquals("foo", lce.getRunAsUser("foo"));
+      assertEquals("foo", lce.getRunAsUser("foo"));
     } finally {
       Configuration conf = new YarnConfiguration();
       conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
@@ -577,7 +577,7 @@ public class TestLinuxContainerExecutor {
 
   @Test
   public void testNonsecureUsernamePattern() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
     try {
       // nonsecure default
       Configuration conf = new YarnConfiguration();
@@ -627,9 +627,10 @@ public class TestLinuxContainerExecutor {
     }
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testPostExecuteAfterReacquisition() throws Exception {
-    Assume.assumeTrue(shouldRun());
+    assumeTrue(shouldRun());
     // make up some bogus container ID
     ApplicationId appId = ApplicationId.newInstance(12345, 67890);
     ApplicationAttemptId attemptId =
@@ -659,8 +660,8 @@ public class TestLinuxContainerExecutor {
         .setUser("foouser")
         .setContainerId(cid)
         .build());
-    assertTrue("postExec not called after reacquisition",
-        TestResourceHandler.postExecContainers.contains(cid));
+    assertTrue(TestResourceHandler.postExecContainers.contains(cid),
+        "postExec not called after reacquisition");
   }
 
   @Test

+ 45 - 43
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java

@@ -20,9 +20,11 @@ package org.apache.hadoop.yarn.server.nodemanager;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.Mockito.doAnswer;
@@ -70,10 +72,10 @@ import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext
 import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext;
 import org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext;
-import org.junit.Assert;
-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.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
@@ -141,7 +143,7 @@ public class TestLinuxContainerExecutorWithMocks {
         executorAbsolutePath);
   }
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException, ContainerExecutionException,
       URISyntaxException {
     assumeNotWindows();
@@ -169,7 +171,7 @@ public class TestLinuxContainerExecutorWithMocks {
     mockExecMockRuntime.setConf(conf);
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     deleteMockParamFile();
   }
@@ -262,7 +264,8 @@ public class TestLinuxContainerExecutorWithMocks {
     }
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testContainerLaunchWithPriority()
       throws IOException, ConfigurationException, URISyntaxException {
 
@@ -274,24 +277,25 @@ public class TestLinuxContainerExecutorWithMocks {
     mockExec.setConf(conf);
     List<String> command = new ArrayList<String>();
     mockExec.addSchedPriorityCommand(command);
-    assertEquals("first should be nice", "nice", command.get(0));
-    assertEquals("second should be -n", "-n", command.get(1));
-    assertEquals("third should be the priority", Integer.toString(2),
-                 command.get(2));
+    assertEquals("nice", command.get(0), "first should be nice");
+    assertEquals("-n", command.get(1), "second should be -n");
+    assertEquals(Integer.toString(2), command.get(2), "third should be the priority");
 
     testContainerLaunchWithoutHTTPS();
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testLaunchCommandWithoutPriority() throws IOException {
     // make sure the command doesn't contain the nice -n since priority
     // not specified
     List<String> command = new ArrayList<String>();
     mockExec.addSchedPriorityCommand(command);
-    assertEquals("addSchedPriority should be empty", 0, command.size());
+    assertEquals(0, command.size(), "addSchedPriority should be empty");
   }
   
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testStartLocalizer() throws IOException {
     InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", 8040);
     Path nmPrivateCTokensPath= new Path("file:///bin/nmPrivateCTokensPath");
@@ -338,7 +342,7 @@ public class TestLinuxContainerExecutorWithMocks {
 
     } catch (ConfigurationException | InterruptedException e) {
       LOG.error("Error:"+e.getMessage(),e);
-      Assert.fail();
+      fail();
     }
   }
   
@@ -377,8 +381,8 @@ public class TestLinuxContainerExecutorWithMocks {
             public Object answer(InvocationOnMock invocationOnMock)
                 throws Throwable {
               String diagnostics = (String) invocationOnMock.getArguments()[0];
-              assertTrue("Invalid Diagnostics message: " + diagnostics,
-                  diagnostics.contains(expecetedMessage[j]));
+              assertTrue(diagnostics.contains(expecetedMessage[j]),
+                  "Invalid Diagnostics message: " + diagnostics);
               return null;
             }
           }
@@ -408,9 +412,8 @@ public class TestLinuxContainerExecutorWithMocks {
               ContainerDiagnosticsUpdateEvent event =
                   (ContainerDiagnosticsUpdateEvent) invocationOnMock
                       .getArguments()[0];
-              assertTrue("Invalid Diagnostics message: " +
-                      event.getDiagnosticsUpdate(),
-                  event.getDiagnosticsUpdate().contains(expecetedMessage[j]));
+              assertTrue(event.getDiagnosticsUpdate().contains(expecetedMessage[j]),
+                  "Invalid Diagnostics message: " + event.getDiagnosticsUpdate());
               return null;
             }
           }
@@ -445,7 +448,7 @@ public class TestLinuxContainerExecutorWithMocks {
             .setApplicationLocalDirs(new ArrayList<>())
             .build());
 
-        Assert.assertNotSame(0, ret);
+        assertNotSame(0, ret);
         assertEquals(Arrays.asList(YarnConfiguration.
                 DEFAULT_NM_NONSECURE_MODE_LOCAL_USER,
             appSubmitter, cmd, appId, containerId,
@@ -457,11 +460,11 @@ public class TestLinuxContainerExecutorWithMocks {
                 dirsHandler.getLogDirs()),
             "cgroups=none"), readMockParams());
 
-        assertNotEquals("Expected YarnRuntimeException",
-            MOCK_EXECUTOR_WITH_CONFIG_ERROR, executor[i]);
+        assertNotEquals(MOCK_EXECUTOR_WITH_CONFIG_ERROR, executor[i],
+            "Expected YarnRuntimeException");
       } catch (ConfigurationException ex) {
         assertEquals(MOCK_EXECUTOR_WITH_CONFIG_ERROR, executor[i]);
-        Assert.assertEquals("Linux Container Executor reached unrecoverable " +
+        assertEquals("Linux Container Executor reached unrecoverable " +
             "exception", ex.getMessage());
       }
     }
@@ -639,10 +642,10 @@ public class TestLinuxContainerExecutorWithMocks {
 
     try {
       lce.startLocalizer(lsc);
-      Assert.fail("startLocalizer should have thrown an exception");
+      fail("startLocalizer should have thrown an exception");
     } catch (IOException e) {
-      assertTrue("Unexpected exception " + e,
-          e.getMessage().contains("exitCode"));
+      assertTrue(e.getMessage().contains("exitCode"),
+          "Unexpected exception " + e);
     }
 
     final int[] exitCodesToThrow = {
@@ -658,10 +661,10 @@ public class TestLinuxContainerExecutorWithMocks {
 
       try {
         lce.startLocalizer(lsc);
-        Assert.fail("startLocalizer should have thrown a ConfigurationException");
+        fail("startLocalizer should have thrown a ConfigurationException");
       } catch (ConfigurationException e) {
-        assertTrue("Unexpected exception " + e,
-            e.getMessage().contains("exitCode=" + exitCode));
+        assertTrue(e.getMessage().contains("exitCode=" + exitCode),
+            "Unexpected exception " + e);
       }
     }
 
@@ -676,10 +679,10 @@ public class TestLinuxContainerExecutorWithMocks {
 
     try {
       lce.startLocalizer(lsc);
-      Assert.fail("startLocalizer should have thrown an ConfigurationException");
+      fail("startLocalizer should have thrown an ConfigurationException");
     } catch (ConfigurationException e) {
-      assertTrue("Unexpected exception " + e,
-          e.getMessage().contains("Container executor not found"));
+      assertTrue(e.getMessage().contains("Container executor not found"),
+          "Unexpected exception " + e);
     }
 
     // Assert that we do not catch every IOException as a misconfiguration
@@ -691,12 +694,11 @@ public class TestLinuxContainerExecutorWithMocks {
 
     try {
       lce.startLocalizer(lsc);
-      Assert.fail("startLocalizer should have thrown an IOException");
+      fail("startLocalizer should have thrown an IOException");
     } catch (ConfigurationException e) {
-      Assert.fail("startLocalizer should not have thrown a ConfigurationException");
+      fail("startLocalizer should not have thrown a ConfigurationException");
     } catch (IOException e) {
-      assertTrue("Unexpected exception " + e,
-          e.getMessage().contains("exitCode"));
+      assertTrue(e.getMessage().contains("exitCode"), "Unexpected exception " + e);
     }
 
     doThrow(new PrivilegedOperationException("interrupted"))
@@ -728,10 +730,10 @@ public class TestLinuxContainerExecutorWithMocks {
 
     try {
       lce.mountCgroups(new ArrayList<String>(), "hierarchy");
-      Assert.fail("mountCgroups should have thrown an exception");
+      fail("mountCgroups should have thrown an exception");
     } catch (IOException e) {
-      assertTrue("Unexpected exception " + e,
-          e.getMessage().contains("exit code"));
+      assertTrue(e.getMessage().contains("exit code"),
+          "Unexpected exception " + e);
     }
   }
 

+ 36 - 36
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLocalDirsHandlerService.java

@@ -32,23 +32,25 @@ import org.apache.hadoop.service.Service.STATE;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestLocalDirsHandlerService {
   private static final File testDir = new File("target",
       TestDirectoryCollection.class.getName()).getAbsoluteFile();
   private static final File testFile = new File(testDir, "testfile");
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException {
     testDir.mkdirs();
     testFile.createNewFile();
   }
 
-  @After
+  @AfterEach
   public void teardown() {
     FileUtil.fullyDelete(testDir);
   }
@@ -62,7 +64,7 @@ public class TestLocalDirsHandlerService {
     conf.set(YarnConfiguration.NM_LOG_DIRS, logDir1);
     LocalDirsHandlerService dirSvc = new LocalDirsHandlerService();
     dirSvc.init(conf);
-    Assert.assertEquals(1, dirSvc.getLocalDirs().size());
+    assertEquals(1, dirSvc.getLocalDirs().size());
     dirSvc.close();
   }
 
@@ -77,12 +79,11 @@ public class TestLocalDirsHandlerService {
     LocalDirsHandlerService dirSvc = new LocalDirsHandlerService();
     try {
       dirSvc.init(conf);
-      Assert.fail("Service should have thrown an exception due to wrong URI");
+      fail("Service should have thrown an exception due to wrong URI");
     } catch (YarnRuntimeException e) {
     }
-    Assert.assertEquals("Service should not be inited",
-                        STATE.STOPPED,
-                        dirSvc.getServiceState());
+    assertEquals(STATE.STOPPED,
+        dirSvc.getServiceState(), "Service should not be inited");
     dirSvc.close();
   }
   
@@ -110,23 +111,23 @@ public class TestLocalDirsHandlerService {
     NodeManagerMetrics nm = NodeManagerMetrics.create();
     LocalDirsHandlerService dirSvc = new LocalDirsHandlerService(nm);
     dirSvc.init(conf);
-    Assert.assertEquals(0, dirSvc.getLocalDirs().size());
-    Assert.assertEquals(0, dirSvc.getLogDirs().size());
-    Assert.assertEquals(1, dirSvc.getDiskFullLocalDirs().size());
-    Assert.assertEquals(1, dirSvc.getDiskFullLogDirs().size());
+    assertEquals(0, dirSvc.getLocalDirs().size());
+    assertEquals(0, dirSvc.getLogDirs().size());
+    assertEquals(1, dirSvc.getDiskFullLocalDirs().size());
+    assertEquals(1, dirSvc.getDiskFullLogDirs().size());
     // check the metrics
-    Assert.assertEquals(2, nm.getBadLocalDirs());
-    Assert.assertEquals(2, nm.getBadLogDirs());
-    Assert.assertEquals(0, nm.getGoodLocalDirsDiskUtilizationPerc());
-    Assert.assertEquals(0, nm.getGoodLogDirsDiskUtilizationPerc());
+    assertEquals(2, nm.getBadLocalDirs());
+    assertEquals(2, nm.getBadLogDirs());
+    assertEquals(0, nm.getGoodLocalDirsDiskUtilizationPerc());
+    assertEquals(0, nm.getGoodLogDirsDiskUtilizationPerc());
 
-    Assert.assertEquals("",
+    assertEquals("",
         dirSvc.getConfig().get(LocalDirsHandlerService.NM_GOOD_LOCAL_DIRS));
-    Assert.assertEquals("",
+    assertEquals("",
         dirSvc.getConfig().get(LocalDirsHandlerService.NM_GOOD_LOG_DIRS));
-    Assert.assertEquals(localDir1 + "," + localDir2,
+    assertEquals(localDir1 + "," + localDir2,
         dirSvc.getConfig().get(YarnConfiguration.NM_LOCAL_DIRS));
-    Assert.assertEquals(logDir1 + "," + logDir2,
+    assertEquals(logDir1 + "," + logDir2,
         dirSvc.getConfig().get(YarnConfiguration.NM_LOG_DIRS));
 
     conf.setFloat(YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE,
@@ -134,29 +135,28 @@ public class TestLocalDirsHandlerService {
     nm = NodeManagerMetrics.create();
     dirSvc = new LocalDirsHandlerService(nm);
     dirSvc.init(conf);
-    Assert.assertEquals(1, dirSvc.getLocalDirs().size());
-    Assert.assertEquals(1, dirSvc.getLogDirs().size());
-    Assert.assertEquals(0, dirSvc.getDiskFullLocalDirs().size());
-    Assert.assertEquals(0, dirSvc.getDiskFullLogDirs().size());
+    assertEquals(1, dirSvc.getLocalDirs().size());
+    assertEquals(1, dirSvc.getLogDirs().size());
+    assertEquals(0, dirSvc.getDiskFullLocalDirs().size());
+    assertEquals(0, dirSvc.getDiskFullLogDirs().size());
     // check the metrics
     File dir = new File(localDir1);
     int utilizationPerc =
         (int) ((dir.getTotalSpace() - dir.getUsableSpace()) * 100 /
             dir.getTotalSpace());
-    Assert.assertEquals(1, nm.getBadLocalDirs());
-    Assert.assertEquals(1, nm.getBadLogDirs());
-    Assert.assertEquals(utilizationPerc,
+    assertEquals(1, nm.getBadLocalDirs());
+    assertEquals(1, nm.getBadLogDirs());
+    assertEquals(utilizationPerc,
       nm.getGoodLocalDirsDiskUtilizationPerc());
-    Assert
-      .assertEquals(utilizationPerc, nm.getGoodLogDirsDiskUtilizationPerc());
+    assertEquals(utilizationPerc, nm.getGoodLogDirsDiskUtilizationPerc());
 
-    Assert.assertEquals(new Path(localDir2).toString(),
+    assertEquals(new Path(localDir2).toString(),
         dirSvc.getConfig().get(LocalDirsHandlerService.NM_GOOD_LOCAL_DIRS));
-    Assert.assertEquals(new Path(logDir2).toString(),
+    assertEquals(new Path(logDir2).toString(),
         dirSvc.getConfig().get(LocalDirsHandlerService.NM_GOOD_LOG_DIRS));
-    Assert.assertEquals(localDir1 + "," + localDir2,
+    assertEquals(localDir1 + "," + localDir2,
         dirSvc.getConfig().get(YarnConfiguration.NM_LOCAL_DIRS));
-    Assert.assertEquals(logDir1 + "," + logDir2,
+    assertEquals(logDir1 + "," + logDir2,
         dirSvc.getConfig().get(YarnConfiguration.NM_LOG_DIRS));
 
     FileUtils.deleteDirectory(new File(localDir1));

+ 7 - 7
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNMAuditLogger.java

@@ -17,7 +17,8 @@
  */
 package org.apache.hadoop.yarn.server.nodemanager;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -42,9 +43,8 @@ import org.apache.hadoop.net.NetUtils;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.server.nodemanager.NMAuditLogger.Keys;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 /**
  * Tests {@link NMAuditLogger}.
@@ -58,7 +58,7 @@ public class TestNMAuditLogger {
   private static final ApplicationId APPID = mock(ApplicationId.class);
   private static final ContainerId CONTAINERID = mock(ContainerId.class);
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
     when(APPID.toString()).thenReturn("app_1");
     when(CONTAINERID.toString()).thenReturn("container_1");
@@ -205,8 +205,8 @@ public class TestNMAuditLogger {
         throws ServiceException {
       // Ensure clientId is received
       byte[] clientId = Server.getClientId();
-      Assert.assertNotNull(clientId);
-      Assert.assertEquals(ClientId.BYTE_LENGTH, clientId.length);
+      assertNotNull(clientId);
+      assertEquals(ClientId.BYTE_LENGTH, clientId.length);
       // test with ip set
       testSuccessLogFormat(true);
       testFailureLogFormat(true);

+ 13 - 10
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNetworkTagMappingJsonManager.java

@@ -20,9 +20,9 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.File;
 import java.io.FileWriter;
@@ -42,9 +42,10 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resource
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.NetworkTagMappingJsonManager.User;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONObject;
-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;
 
 /**
  * Test NetworkTagMapping Json Manager.
@@ -55,7 +56,7 @@ public class TestNetworkTagMappingJsonManager {
   private Configuration conf = new YarnConfiguration();
   private FileSystem fs;
 
-  @Before
+  @BeforeEach
   public void setUp() throws IOException {
     fs = FileSystem.get(conf);
     if (fs.exists(jsonDirDirPath)) {
@@ -64,14 +65,15 @@ public class TestNetworkTagMappingJsonManager {
     assertTrue(fs.mkdirs(jsonDirDirPath));
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws IOException {
     if (fs.exists(jsonDirDirPath)) {
       fs.delete(jsonDirDirPath, true);
     }
   }
 
-  @Test (timeout=10000)
+  @Test
+  @Timeout(value = 10)
   public void testNetworkMappingJsonManager() throws Exception {
     Path jsonFilePath = new Path(jsonDirDirPath, "test.json");
     File jsonFile = new File(jsonFilePath.toString());
@@ -166,7 +168,8 @@ public class TestNetworkTagMappingJsonManager {
     }
   }
 
-  @Test (timeout=10000)
+  @Test
+  @Timeout(value = 10)
   public void testNetworkTagIDMatchPattern() throws Exception {
     Path jsonFilePath = new Path(jsonDirDirPath, "test.json");
     File jsonFile = new File(jsonFilePath.toString());

+ 34 - 35
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManager.java

@@ -18,7 +18,11 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 
@@ -30,10 +34,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Cont
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerState;
 import org.apache.hadoop.yarn.server.nodemanager.nodelabels.NodeLabelsProvider;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
 
 public class TestNodeManager {
 
@@ -45,9 +46,6 @@ public class TestNodeManager {
     }
   }
 
-  @Rule
-  public ExpectedException thrown = ExpectedException.none();
-
   @Test
   public void testContainerExecutorInitCall() {
     NodeManager nm = new NodeManager();
@@ -122,13 +120,13 @@ public class TestNodeManager {
     postCalls = 0;
     NodeManager.NMContext nmContext =
         nodeManager.createNMContext(null, null, null, false, conf);
-    Assert.assertEquals(2, initCalls);
+    assertEquals(2, initCalls);
     nmContext.getContainerStateTransitionListener().preTransition(
         null, null, null);
     nmContext.getContainerStateTransitionListener().postTransition(
         null, null, null, null);
-    Assert.assertEquals(2, preCalls);
-    Assert.assertEquals(2, postCalls);
+    assertEquals(2, preCalls);
+    assertEquals(2, postCalls);
   }
 
   @Test
@@ -139,40 +137,39 @@ public class TestNodeManager {
       Configuration conf = new Configuration();
       NodeLabelsProvider labelsProviderService =
           nodeManager.createNodeLabelsProvider(conf);
-      Assert
-          .assertNull(
-              "LabelsProviderService should not be initialized in default configuration",
-              labelsProviderService);
+
+      assertNull(labelsProviderService,
+          "LabelsProviderService should not be initialized in default configuration");
 
       // With valid className
       conf.set(
           YarnConfiguration.NM_NODE_LABELS_PROVIDER_CONFIG,
           "org.apache.hadoop.yarn.server.nodemanager.nodelabels.ConfigurationNodeLabelsProvider");
       labelsProviderService = nodeManager.createNodeLabelsProvider(conf);
-      Assert.assertNotNull("LabelsProviderService should be initialized When "
-          + "node labels provider class is configured", labelsProviderService);
+      assertNotNull(labelsProviderService, "LabelsProviderService should be initialized When "
+          + "node labels provider class is configured");
 
       // With invalid className
       conf.set(YarnConfiguration.NM_NODE_LABELS_PROVIDER_CONFIG,
           "org.apache.hadoop.yarn.server.nodemanager.NodeManager");
       try {
         labelsProviderService = nodeManager.createNodeLabelsProvider(conf);
-        Assert.fail("Expected to throw IOException on Invalid configuration");
+        fail("Expected to throw IOException on Invalid configuration");
       } catch (IOException e) {
         // exception expected on invalid configuration
       }
-      Assert.assertNotNull("LabelsProviderService should be initialized When "
-          + "node labels provider class is configured", labelsProviderService);
+      assertNotNull(labelsProviderService, "LabelsProviderService should be initialized When "
+          + "node labels provider class is configured");
 
       // With valid whitelisted configurations
       conf.set(YarnConfiguration.NM_NODE_LABELS_PROVIDER_CONFIG,
           YarnConfiguration.CONFIG_NODE_DESCRIPTOR_PROVIDER);
       labelsProviderService = nodeManager.createNodeLabelsProvider(conf);
-      Assert.assertNotNull("LabelsProviderService should be initialized When "
-          + "node labels provider class is configured", labelsProviderService);
+      assertNotNull(labelsProviderService, "LabelsProviderService should be initialized When "
+          + "node labels provider class is configured");
 
     } catch (Exception e) {
-      Assert.fail("Exception caught");
+      fail("Exception caught");
       e.printStackTrace();
     }
   }
@@ -184,18 +181,20 @@ public class TestNodeManager {
    */
   @Test
   public void testUserProvidedUGIConf() throws Exception {
-    thrown.expect(IllegalArgumentException.class);
-    thrown.expectMessage("Invalid attribute value for "
+    IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
+      Configuration dummyConf = new YarnConfiguration();
+      dummyConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
+              "DUMMYAUTH");
+      NodeManager dummyNodeManager = new NodeManager();
+      try {
+        dummyNodeManager.init(dummyConf);
+      } finally {
+        dummyNodeManager.stop();
+      }
+    });
+
+    assertEquals("Invalid attribute value for "
         + CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION
-        + " of DUMMYAUTH");
-    Configuration dummyConf = new YarnConfiguration();
-    dummyConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
-        "DUMMYAUTH");
-    NodeManager dummyNodeManager = new NodeManager();
-    try {
-      dummyNodeManager.init(dummyConf);
-    } finally {
-      dummyNodeManager.stop();
-    }
+        + " of DUMMYAUTH", exception.getMessage());
   }
 }

+ 4 - 3
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerMXBean.java

@@ -23,12 +23,13 @@ import org.slf4j.LoggerFactory;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
 import java.lang.management.ManagementFactory;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
 /**
  * Class for testing {@link NodeManagerMXBean} implementation.
  */
@@ -50,7 +51,7 @@ public class TestNodeManagerMXBean {
       // Get attribute "SecurityEnabled"
       boolean securityEnabled = (boolean) mbs.getAttribute(mxbeanName,
               "SecurityEnabled");
-      Assert.assertEquals(nodeManager.isSecurityEnabled(), securityEnabled);
+      assertEquals(nodeManager.isSecurityEnabled(), securityEnabled);
     }
   }
 }

+ 30 - 31
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerReboot.java

@@ -66,10 +66,13 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.Cont
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService;
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.util.Records;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestNodeManagerReboot {
 
@@ -86,12 +89,12 @@ public class TestNodeManagerReboot {
   static final Logger LOG =
        LoggerFactory.getLogger(TestNodeManagerReboot.class);
 
-  @Before
+  @BeforeEach
   public void setup() throws UnsupportedFileSystemException {
     localFS = FileContext.getLocalFSFileContext();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws IOException, InterruptedException {
     localFS.delete(new Path(basedir.getPath()), true);
     if (nm != null) {
@@ -99,7 +102,8 @@ public class TestNodeManagerReboot {
     }
   }
 
-  @Test(timeout = 2000000)
+  @Test
+  @Timeout(value = 2000)
   public void testClearLocalDirWhenNodeReboot() throws IOException,
       YarnException, InterruptedException {
     nm = new MyNodeManager();
@@ -177,20 +181,17 @@ public class TestNodeManagerReboot {
       numTries++;
     }
 
-    Assert.assertEquals(ContainerState.DONE, container.getContainerState());
+    assertEquals(ContainerState.DONE, container.getContainerState());
 
-    Assert
-      .assertTrue(
+    assertTrue(numOfLocalDirs(nmLocalDir.getAbsolutePath(),
+        ContainerLocalizer.USERCACHE) > 0,
         "The container should create a subDir named currentUser: " + user
-            + "under localDir/usercache",
-        numOfLocalDirs(nmLocalDir.getAbsolutePath(),
-          ContainerLocalizer.USERCACHE) > 0);
+        + "under localDir/usercache");
 
-    Assert.assertTrue(
-      "There should be files or Dirs under nm_private when "
-          + "container is launched",
-      numOfLocalDirs(nmLocalDir.getAbsolutePath(),
-        ResourceLocalizationService.NM_PRIVATE_DIR) > 0);
+    assertTrue(numOfLocalDirs(nmLocalDir.getAbsolutePath(),
+        ResourceLocalizationService.NM_PRIVATE_DIR) > 0,
+        "There should be files or Dirs under nm_private when "
+        + "container is launched");
 
     // restart the NodeManager
     restartNM(MAX_TRIES);
@@ -237,20 +238,18 @@ public class TestNodeManagerReboot {
   }
   
   private void checkNumOfLocalDirs() throws IOException {
-    Assert
-      .assertTrue(
-        "After NM reboots, all local files should be deleted",
+    assertTrue(
         numOfLocalDirs(nmLocalDir.getAbsolutePath(),
-          ContainerLocalizer.USERCACHE) == 0
-            && numOfLocalDirs(nmLocalDir.getAbsolutePath(),
-              ContainerLocalizer.FILECACHE) == 0
-            && numOfLocalDirs(nmLocalDir.getAbsolutePath(),
-              ResourceLocalizationService.NM_PRIVATE_DIR) == 0);
-    
-    Assert
-    .assertTrue(
-      "After NM reboots, usercache_DEL_* directory should be deleted",
-      numOfUsercacheDELDirs(nmLocalDir.getAbsolutePath()) == 0);
+        ContainerLocalizer.USERCACHE) == 0
+        && numOfLocalDirs(nmLocalDir.getAbsolutePath(),
+        ContainerLocalizer.FILECACHE) == 0
+        && numOfLocalDirs(nmLocalDir.getAbsolutePath(),
+        ResourceLocalizationService.NM_PRIVATE_DIR) == 0,
+        "After NM reboots, all local files should be deleted");
+
+
+    assertTrue(numOfUsercacheDELDirs(nmLocalDir.getAbsolutePath()) == 0,
+        "After NM reboots, usercache_DEL_* directory should be deleted");
   }
   
   private int numOfLocalDirs(String localDir, String localSubDir) {

+ 38 - 34
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java

@@ -18,7 +18,9 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import org.slf4j.Logger;
@@ -90,10 +92,10 @@ import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService
 import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.server.utils.YarnServerBuilderUtils;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class TestNodeManagerResync {
   static final File basedir =
@@ -121,7 +123,7 @@ public class TestNodeManagerResync {
   protected static final Logger LOG =
        LoggerFactory.getLogger(TestNodeManagerResync.class);
 
-  @Before
+  @BeforeEach
   public void setup() throws UnsupportedFileSystemException {
     localFS = FileContext.getLocalFSFileContext();
     tmpDir.mkdirs();
@@ -133,7 +135,7 @@ public class TestNodeManagerResync {
     resyncThreadCount = new AtomicInteger(0);
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws IOException, InterruptedException {
     localFS.delete(new Path(basedir.getPath()), true);
     assertionFailedInThread.set(false);
@@ -172,19 +174,19 @@ public class TestNodeManagerResync {
           processStartFile, port);
 
       nm.setExistingContainerId(cId);
-      Assert.assertEquals(1, ((TestNodeManager1) nm).getNMRegistrationCount());
+      assertEquals(1, ((TestNodeManager1) nm).getNMRegistrationCount());
       nm.getNMDispatcher().getEventHandler().handle(resyncEvent);
       try {
         syncBarrier.await();
       } catch (BrokenBarrierException e) {
       }
-      Assert.assertEquals(2, ((TestNodeManager1) nm).getNMRegistrationCount());
+      assertEquals(2, ((TestNodeManager1) nm).getNMRegistrationCount());
       // Only containers should be killed on resync, apps should lie around.
       // That way local resources for apps can be used beyond resync without
       // relocalization
-      Assert.assertTrue(nm.getNMContext().getApplications()
+      assertTrue(nm.getNMContext().getApplications()
           .containsKey(cId.getApplicationAttemptId().getApplicationId()));
-      Assert.assertFalse(assertionFailedInThread.get());
+      assertFalse(assertionFailedInThread.get());
     }
     finally {
       nm.stop();
@@ -192,7 +194,8 @@ public class TestNodeManagerResync {
   }
 
   @SuppressWarnings("resource")
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testNMMultipleResyncEvent()
       throws IOException, InterruptedException {
     TestNodeManager1 nm = new TestNodeManager1(false);
@@ -202,7 +205,7 @@ public class TestNodeManagerResync {
     try {
       nm.init(conf);
       nm.start();
-      Assert.assertEquals(1, nm.getNMRegistrationCount());
+      assertEquals(1, nm.getNMRegistrationCount());
       for (int i = 0; i < resyncEventCount; i++) {
         nm.getNMDispatcher().getEventHandler().handle(resyncEvent);
       }
@@ -219,15 +222,16 @@ public class TestNodeManagerResync {
       LOG.info("Barrier wait done for the resync thread");
 
       // Resync should only happen once
-      Assert.assertEquals(2, nm.getNMRegistrationCount());
-      Assert.assertFalse("NM shutdown called.", isNMShutdownCalled.get());
+      assertEquals(2, nm.getNMRegistrationCount());
+      assertFalse(isNMShutdownCalled.get(), "NM shutdown called.");
     } finally {
       nm.stop();
     }
   }
 
   @SuppressWarnings("resource")
-  @Test(timeout=10000)
+  @Test
+  @Timeout(value = 10)
   public void testNMshutdownWhenResyncThrowException() throws IOException,
       InterruptedException, YarnException {
     NodeManager nm = new TestNodeManager3();
@@ -235,7 +239,7 @@ public class TestNodeManagerResync {
     try {
       nm.init(conf);
       nm.start();
-      Assert.assertEquals(1, ((TestNodeManager3) nm).getNMRegistrationCount());
+      assertEquals(1, ((TestNodeManager3) nm).getNMRegistrationCount());
       nm.getNMDispatcher().getEventHandler()
           .handle(new NodeManagerEvent(NodeManagerEventType.RESYNC));
 
@@ -248,14 +252,15 @@ public class TestNodeManagerResync {
         }
       }
 
-      Assert.assertTrue("NM shutdown not called.", isNMShutdownCalled.get());
+      assertTrue(isNMShutdownCalled.get(), "NM shutdown not called.");
     } finally {
       nm.stop();
     }
   }
 
   @SuppressWarnings("resource")
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testContainerResourceIncreaseIsSynchronizedWithRMResync()
       throws IOException, InterruptedException, YarnException {
     NodeManager nm = new TestNodeManager4();
@@ -278,7 +283,7 @@ public class TestNodeManagerResync {
       } catch (BrokenBarrierException e) {
         e.printStackTrace();
       }
-      Assert.assertFalse(assertionFailedInThread.get());
+      assertFalse(assertionFailedInThread.get());
     } finally {
       nm.stop();
     }
@@ -315,7 +320,7 @@ public class TestNodeManagerResync {
                 if (registerCount == 0) {
                   // first register, no containers info.
                   try {
-                    Assert.assertEquals(0, request.getNMContainerStatuses()
+                    assertEquals(0, request.getNMContainerStatuses()
                       .size());
                   } catch (AssertionError error) {
                     error.printStackTrace();
@@ -333,8 +338,8 @@ public class TestNodeManagerResync {
                   List<NMContainerStatus> statuses =
                       request.getNMContainerStatuses();
                   try {
-                    Assert.assertEquals(1, statuses.size());
-                    Assert.assertEquals(testCompleteContainer.getContainerId(),
+                    assertEquals(1, statuses.size());
+                    assertEquals(testCompleteContainer.getContainerId(),
                       statuses.get(0).getContainerId());
                   } catch (AssertionError error) {
                     error.printStackTrace();
@@ -352,8 +357,8 @@ public class TestNodeManagerResync {
                 List<ContainerStatus> statuses =
                     request.getNodeStatus().getContainersStatuses();
                 try {
-                  Assert.assertEquals(1, statuses.size());
-                  Assert.assertEquals(testCompleteContainer.getContainerId(),
+                  assertEquals(1, statuses.size());
+                  assertEquals(testCompleteContainer.getContainerId(),
                     statuses.get(0).getContainerId());
                 } catch (AssertionError error) {
                   error.printStackTrace();
@@ -378,7 +383,7 @@ public class TestNodeManagerResync {
         syncBarrier.await();
       } catch (BrokenBarrierException e) {
       }
-      Assert.assertFalse(assertionFailedInThread.get());
+      assertFalse(assertionFailedInThread.get());
     } finally {
       nm.stop();
     }
@@ -488,8 +493,8 @@ public class TestNodeManagerResync {
         try {
           try {
             if (containersShouldBePreserved) {
-              Assert.assertFalse(containers.isEmpty());
-              Assert.assertTrue(containers.containsKey(existingCid));
+              assertFalse(containers.isEmpty());
+              assertTrue(containers.containsKey(existingCid));
               ContainerState state = containers.get(existingCid)
                   .cloneAndGetContainerStatus().getState();
               // Wait till RUNNING state...
@@ -498,14 +503,14 @@ public class TestNodeManagerResync {
                 Thread.sleep(100);
                 counter--;
               }
-              Assert.assertEquals(ContainerState.RUNNING,
+              assertEquals(ContainerState.RUNNING,
                   containers.get(existingCid)
                   .cloneAndGetContainerStatus().getState());
             } else {
               // ensure that containers are empty or are completed before
               // restart nodeStatusUpdater
               if (!containers.isEmpty()) {
-                Assert.assertEquals(ContainerState.COMPLETE,
+                assertEquals(ContainerState.COMPLETE,
                     containers.get(existingCid)
                         .cloneAndGetContainerStatus().getState());
               }
@@ -755,10 +760,9 @@ public class TestNodeManagerResync {
             ContainerUpdateResponse updateResponse =
                 getContainerManager()
                     .updateContainer(updateRequest);
-            Assert.assertEquals(
-                1, updateResponse.getSuccessfullyUpdatedContainers()
-                    .size());
-            Assert.assertTrue(updateResponse.getFailedRequests().isEmpty());
+            assertEquals(1,
+                updateResponse.getSuccessfullyUpdatedContainers().size());
+            assertTrue(updateResponse.getFailedRequests().isEmpty());
           } catch (Exception e) {
             e.printStackTrace();
           } finally {

+ 19 - 17
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerShutdown.java

@@ -33,7 +33,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.junit.Assert;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileContext;
 import org.apache.hadoop.fs.Path;
@@ -69,9 +68,12 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.TestContainerM
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.util.ConverterUtils;
-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 static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestNodeManagerShutdown {
   static final File basedir =
@@ -90,7 +92,7 @@ public class TestNodeManagerShutdown {
   private ContainerId cId;
   private NodeManager nm;
 
-  @Before
+  @BeforeEach
   public void setup() throws UnsupportedFileSystemException {
     localFS = FileContext.getLocalFSFileContext();
     tmpDir.mkdirs();
@@ -102,7 +104,7 @@ public class TestNodeManagerShutdown {
     cId = createContainerId();
   }
   
-  @After
+  @AfterEach
   public void tearDown() throws IOException, InterruptedException {
     if (nm != null) {
       nm.stop();
@@ -121,23 +123,23 @@ public class TestNodeManagerShutdown {
     // verify state store is not removed on normal shutdown
     nm.init(conf);
     nm.start();
-    Assert.assertTrue(recoveryDir.exists());
-    Assert.assertTrue(recoveryDir.isDirectory());
+    assertTrue(recoveryDir.exists());
+    assertTrue(recoveryDir.isDirectory());
     nm.stop();
     nm = null;
-    Assert.assertTrue(recoveryDir.exists());
-    Assert.assertTrue(recoveryDir.isDirectory());
+    assertTrue(recoveryDir.exists());
+    assertTrue(recoveryDir.isDirectory());
 
     // verify state store is removed on decommissioned shutdown
     nm = new TestNodeManager();
     nm.init(conf);
     nm.start();
-    Assert.assertTrue(recoveryDir.exists());
-    Assert.assertTrue(recoveryDir.isDirectory());
+    assertTrue(recoveryDir.exists());
+    assertTrue(recoveryDir.isDirectory());
     nm.getNMContext().setDecommissioned(true);
     nm.stop();
     nm = null;
-    Assert.assertFalse(recoveryDir.exists());
+    assertFalse(recoveryDir.exists());
   }
 
   @Test
@@ -166,8 +168,8 @@ public class TestNodeManagerShutdown {
     // There is no way for the process to trap and respond.  Instead, we can
     // verify that the job object with ID matching container ID no longer exists.
     if (Shell.WINDOWS) {
-      Assert.assertFalse("Process is still alive!",
-        DefaultContainerExecutor.containerIsAlive(cId.toString()));
+      assertFalse(DefaultContainerExecutor.containerIsAlive(cId.toString()),
+          "Process is still alive!");
     } else {
       BufferedReader reader =
           new BufferedReader(new FileReader(processStartFile));
@@ -183,7 +185,7 @@ public class TestNodeManagerShutdown {
           break;
         }
       }
-      Assert.assertTrue("Did not find sigterm message", foundSigTermMessage);
+      assertTrue(foundSigTermMessage, "Did not find sigterm message");
       reader.close();
     }
   }
@@ -257,7 +259,7 @@ public class TestNodeManagerShutdown {
         GetContainerStatusesRequest.newInstance(containerIds);
     ContainerStatus containerStatus =
         containerManager.getContainerStatuses(request).getContainerStatuses().get(0);
-    Assert.assertTrue(EnumSet.of(ContainerState.RUNNING)
+    assertTrue(EnumSet.of(ContainerState.RUNNING)
             .contains(containerStatus.getState()));
   }
   

+ 3 - 3
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeResourceMonitor.java

@@ -27,8 +27,8 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager
 import org.apache.hadoop.yarn.server.nodemanager.containermanager
     .monitor.MockResourceCalculatorPlugin;
 
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.timeout;
@@ -38,7 +38,7 @@ public class TestNodeResourceMonitor extends BaseContainerManagerTest {
     super();
   }
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException {
     // Enable node resource monitor with a mocked resource calculator.
     conf.set(

+ 133 - 122
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java

@@ -20,6 +20,11 @@ package org.apache.hadoop.yarn.server.nodemanager;
 
 import static org.apache.hadoop.yarn.server.utils.YarnServerBuilderUtils.newNodeHeartbeatResponse;
 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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -119,10 +124,10 @@ import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.server.utils.YarnServerBuilderUtils;
 import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.apache.hadoop.ipc.RPC;
 import org.apache.hadoop.ipc.Server;
 
@@ -139,13 +144,13 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
   private NodeManager nm;
   private AtomicBoolean assertionFailedInThread = new AtomicBoolean(false);
 
-  @Before
+  @BeforeEach
   public void before() {
     // to avoid threading issues with JUnit 4.13+
     ProtobufRpcEngine2.clearClientCache();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     this.registeredNodes.clear();
     heartBeatID.set(0);
@@ -186,8 +191,8 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       // NOTE: this really should be checking against the config value
       InetSocketAddress expected = NetUtils.getConnectAddress(
           conf.getSocketAddr(YarnConfiguration.NM_ADDRESS, null, -1));
-      Assert.assertEquals(NetUtils.getHostPortString(expected), nodeId.toString());
-      Assert.assertEquals(5 * 1024, resource.getMemorySize());
+      assertEquals(NetUtils.getHostPortString(expected), nodeId.toString());
+      assertEquals(5 * 1024, resource.getMemorySize());
       registeredNodes.add(nodeId);
 
       RegisterNodeManagerResponse response = recordFactory
@@ -235,7 +240,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
 
       ContainerId firstContainerID = null;
       if (heartBeatID.get() == 1) {
-        Assert.assertEquals(0, nodeStatus.getContainersStatuses().size());
+        assertEquals(0, nodeStatus.getContainersStatuses().size());
 
         // Give a container to the NM.
         ApplicationAttemptId appAttemptID =
@@ -259,15 +264,15 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         this.context.getContainers().put(firstContainerID, container);
       } else if (heartBeatID.get() == 2) {
         // Checks on the RM end
-        Assert.assertEquals("Number of applications should only be one!", 1,
-            nodeStatus.getContainersStatuses().size());
-        Assert.assertEquals("Number of container for the app should be one!",
-            1, appToContainers.get(appId1).size());
+        assertEquals(1, nodeStatus.getContainersStatuses().size(),
+            "Number of applications should only be one!");
+        assertEquals(1, appToContainers.get(appId1).size(),
+            "Number of container for the app should be one!");
 
         // Checks on the NM end
         ConcurrentMap<ContainerId, Container> activeContainers =
             this.context.getContainers();
-        Assert.assertEquals(1, activeContainers.size());
+        assertEquals(1, activeContainers.size());
 
         if (this.signalContainer) {
           containersToSignal = new ArrayList<SignalContainerRequest>();
@@ -300,17 +305,17 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         this.context.getContainers().put(secondContainerID, container);
       } else if (heartBeatID.get() == 3) {
         // Checks on the RM end
-        Assert.assertEquals("Number of applications should have two!", 2,
-            appToContainers.size());
-        Assert.assertEquals("Number of container for the app-1 should be only one!",
-            1, appToContainers.get(appId1).size());
-        Assert.assertEquals("Number of container for the app-2 should be only one!",
-            1, appToContainers.get(appId2).size());
+        assertEquals(2, appToContainers.size(),
+            "Number of applications should have two!");
+        assertEquals(1, appToContainers.get(appId1).size(),
+            "Number of container for the app-1 should be only one!");
+        assertEquals(1, appToContainers.get(appId2).size(),
+            "Number of container for the app-2 should be only one!");
 
         // Checks on the NM end
         ConcurrentMap<ContainerId, Container> activeContainers =
             this.context.getContainers();
-        Assert.assertEquals(2, activeContainers.size());
+        assertEquals(2, activeContainers.size());
       }
 
       NodeHeartbeatResponse nhResponse = YarnServerBuilderUtils.
@@ -704,31 +709,31 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
           <ContainerId>();
       try {
         if (heartBeatID.get() == 0) {
-          Assert.assertEquals(0, request.getNodeStatus().getContainersStatuses()
+          assertEquals(0, request.getNodeStatus().getContainersStatuses()
             .size());
-          Assert.assertEquals(0, context.getContainers().size());
+          assertEquals(0, context.getContainers().size());
         } else if (heartBeatID.get() == 1) {
           List<ContainerStatus> statuses =
               request.getNodeStatus().getContainersStatuses();
-          Assert.assertEquals(2, statuses.size());
-          Assert.assertEquals(2, context.getContainers().size());
+          assertEquals(2, statuses.size());
+          assertEquals(2, context.getContainers().size());
 
           boolean container2Exist = false, container3Exist = false;
           for (ContainerStatus status : statuses) {
             if (status.getContainerId().equals(
               containerStatus2.getContainerId())) {
-              Assert.assertEquals(containerStatus2.getState(),
+              assertEquals(containerStatus2.getState(),
                   status.getState());
               container2Exist = true;
             }
             if (status.getContainerId().equals(
               containerStatus3.getContainerId())) {
-              Assert.assertEquals(containerStatus3.getState(),
+              assertEquals(containerStatus3.getState(),
                   status.getState());
               container3Exist = true;
             }
           }
-          Assert.assertTrue(container2Exist && container3Exist);
+          assertTrue(container2Exist && container3Exist);
 
           // should throw exception that can be retried by the
           // nodeStatusUpdaterRunnable, otherwise nm just shuts down and the
@@ -741,38 +746,38 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
           // since heartbeat 1 was lost.  It will send them again on
           // heartbeat 3, because it does not clear them if the previous
           // heartbeat was lost in case the RM treated it as a duplicate.
-          Assert.assertEquals(4, statuses.size());
-          Assert.assertEquals(4, context.getContainers().size());
+          assertEquals(4, statuses.size());
+          assertEquals(4, context.getContainers().size());
 
           boolean container2Exist = false, container3Exist = false,
               container4Exist = false, container5Exist = false;
           for (ContainerStatus status : statuses) {
             if (status.getContainerId().equals(
               containerStatus2.getContainerId())) {
-              Assert.assertEquals(containerStatus2.getState(),
+              assertEquals(containerStatus2.getState(),
                   status.getState());
               container2Exist = true;
             }
             if (status.getContainerId().equals(
               containerStatus3.getContainerId())) {
-              Assert.assertEquals(containerStatus3.getState(),
+              assertEquals(containerStatus3.getState(),
                   status.getState());
               container3Exist = true;
             }
             if (status.getContainerId().equals(
               containerStatus4.getContainerId())) {
-              Assert.assertEquals(containerStatus4.getState(),
+              assertEquals(containerStatus4.getState(),
                   status.getState());
               container4Exist = true;
             }
             if (status.getContainerId().equals(
               containerStatus5.getContainerId())) {
-              Assert.assertEquals(containerStatus5.getState(),
+              assertEquals(containerStatus5.getState(),
                   status.getState());
               container5Exist = true;
             }
           }
-          Assert.assertTrue(container2Exist && container3Exist
+          assertTrue(container2Exist && container3Exist
               && container4Exist && container5Exist);
 
           if (heartBeatID.get() == 3) {
@@ -781,9 +786,9 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         } else if (heartBeatID.get() == 4) {
           List<ContainerStatus> statuses =
               request.getNodeStatus().getContainersStatuses();
-          Assert.assertEquals(2, statuses.size());
+          assertEquals(2, statuses.size());
           // Container 3 is acked by AM, hence removed from context
-          Assert.assertEquals(3, context.getContainers().size());
+          assertEquals(3, context.getContainers().size());
 
           boolean container3Exist = false;
           for (ContainerStatus status : statuses) {
@@ -792,7 +797,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
               container3Exist = true;
             }
           }
-          Assert.assertFalse(container3Exist);
+          assertFalse(container3Exist);
         }
       } catch (AssertionError error) {
         error.printStackTrace();
@@ -897,9 +902,9 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         // NOTE: this really should be checking against the config value
         InetSocketAddress expected = NetUtils.getConnectAddress(
             conf.getSocketAddr(YarnConfiguration.NM_ADDRESS, null, -1));
-        Assert.assertEquals(NetUtils.getHostPortString(expected),
+        assertEquals(NetUtils.getHostPortString(expected),
             nodeId.toString());
-        Assert.assertEquals(5 * 1024, resource.getMemorySize());
+        assertEquals(5 * 1024, resource.getMemorySize());
         registeredNodes.add(nodeId);
 
         RegisterNodeManagerResponse response = recordFactory
@@ -929,18 +934,19 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     }
   }
 
-  @Before
+  @BeforeEach
   public void clearError() {
     nmStartError = null;
   }
 
-  @After
+  @AfterEach
   public void deleteBaseDir() throws IOException {
     FileContext lfs = FileContext.getLocalFSFileContext();
     lfs.delete(new Path(basedir.getPath()), true);
   }
 
-  @Test(timeout = 90000)
+  @Test
+  @Timeout(value = 90)
   public void testRecentlyFinishedContainers() throws Exception {
     NodeManager nm = new NodeManager();
     YarnConfiguration conf = new YarnConfiguration();
@@ -958,22 +964,23 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     nm.getNMContext().getContainers().putIfAbsent(cId, mock(Container.class));
 
     nodeStatusUpdater.addCompletedContainer(cId);
-    Assert.assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(cId));     
+    assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(cId));
 
     // verify container remains even after expiration if app
     // is still active
     nm.getNMContext().getContainers().remove(cId);
     Thread.sleep(10);
     nodeStatusUpdater.removeVeryOldStoppedContainersFromCache();
-    Assert.assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(cId));
+    assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(cId));
 
     // complete the application and verify container is removed
     nm.getNMContext().getApplications().remove(appId);
     nodeStatusUpdater.removeVeryOldStoppedContainersFromCache();
-    Assert.assertFalse(nodeStatusUpdater.isContainerRecentlyStopped(cId));
+    assertFalse(nodeStatusUpdater.isContainerRecentlyStopped(cId));
   }
 
-  @Test(timeout = 90000)
+  @Test
+  @Timeout(value = 90)
   public void testRemovePreviousCompletedContainersFromContext() throws Exception {
     NodeManager nm = new NodeManager();
     YarnConfiguration conf = new YarnConfiguration();
@@ -1036,7 +1043,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     nm.getNMContext().getContainers()
       .put(runningContainerId, runningContainer);
 
-    Assert.assertEquals(2, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(2, nodeStatusUpdater.getContainerStatuses().size());
 
     List<ContainerId> ackedContainers = new ArrayList<ContainerId>();
     ackedContainers.add(cId);
@@ -1050,14 +1057,15 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       containerIdSet.add(status.getContainerId());
     }
 
-    Assert.assertEquals(1, containerStatuses.size());
+    assertEquals(1, containerStatuses.size());
     // completed container is removed;
-    Assert.assertFalse(containerIdSet.contains(cId));
+    assertFalse(containerIdSet.contains(cId));
     // running container is not removed;
-    Assert.assertTrue(containerIdSet.contains(runningContainerId));
+    assertTrue(containerIdSet.contains(runningContainerId));
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testCompletedContainersIsRecentlyStopped() throws Exception {
     NodeManager nm = new NodeManager();
     nm.init(conf);
@@ -1088,8 +1096,8 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     nm.getNMContext().getApplications().putIfAbsent(appId, completedApp);
     nm.getNMContext().getContainers().put(containerId, completedContainer);
 
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
-    Assert.assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertTrue(nodeStatusUpdater.isContainerRecentlyStopped(
         containerId));
   }
 
@@ -1129,19 +1137,19 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     nm.getNMContext().getApplications().putIfAbsent(appId, application);
     nm.getNMContext().getContainers().put(cId, anyCompletedContainer);
 
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
 
     when(application.getApplicationState()).thenReturn(
         ApplicationState.FINISHING_CONTAINERS_WAIT);
     // The completed container will be saved in case of lost heartbeat.
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
 
     nm.getNMContext().getContainers().put(cId, anyCompletedContainer);
     nm.getNMContext().getApplications().remove(appId);
     // The completed container will be saved in case of lost heartbeat.
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
-    Assert.assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
+    assertEquals(1, nodeStatusUpdater.getContainerStatuses().size());
   }
 
   @Test
@@ -1162,8 +1170,8 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     // with RM)
     Object[] services  = nm.getServices().toArray();
     Object lastService = services[services.length-1];
-    Assert.assertTrue("last service is NOT the node status updater",
-        lastService instanceof NodeStatusUpdater);
+    assertTrue(lastService instanceof NodeStatusUpdater,
+        "last service is NOT the node status updater");
 
     Thread starterThread = new Thread(() -> {
       try {
@@ -1181,16 +1189,16 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
 
     if (nmStartError != null) {
       LOG.error("Error during startup. ", nmStartError);
-      Assert.fail(nmStartError.getCause().getMessage());
+      fail(nmStartError.getCause().getMessage());
     }
 
     GenericTestUtils.waitFor(
         () -> nm.getServiceState() != STATE.STARTED || heartBeatID.get() > 3,
         50, 20000);
 
-    Assert.assertTrue(heartBeatID.get() > 3);
-    Assert.assertEquals("Number of registered NMs is wrong!!",
-        1, this.registeredNodes.size());
+    assertTrue(heartBeatID.get() > 3);
+    assertEquals(1, this.registeredNodes.size(),
+        "Number of registered NMs is wrong!!");
   }
 
   @Test
@@ -1234,7 +1242,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     GenericTestUtils.waitFor(
         () -> nm.getServiceState() != STATE.STARTED || heartBeatID.get() >= 1,
         50, 20000);
-    Assert.assertTrue(heartBeatID.get() >= 1);
+    assertTrue(heartBeatID.get() >= 1);
 
     // Meanwhile call stop directly as the shutdown hook would
     nm.stop();
@@ -1242,11 +1250,11 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     // NM takes a while to reach the STOPPED state.
     nm.waitForServiceToStop(20000);
 
-    Assert.assertEquals(STATE.STOPPED, nm.getServiceState());
+    assertEquals(STATE.STOPPED, nm.getServiceState());
 
     // It further takes a while after NM reached the STOPPED state.
     GenericTestUtils.waitFor(() -> numCleanups.get() > 0, 20, 20000);
-    Assert.assertEquals(1, numCleanups.get());
+    assertEquals(1, numCleanups.get());
   }
 
   @Test
@@ -1254,7 +1262,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     nm = getNodeManager(NodeAction.SHUTDOWN);
     YarnConfiguration conf = createNMConfig();
     nm.init(conf);
-    Assert.assertEquals(STATE.INITED, nm.getServiceState());
+    assertEquals(STATE.INITED, nm.getServiceState());
     nm.start();
     GenericTestUtils.waitFor(() -> nm.getServiceState() == STATE.STARTED,
         20, 10000);
@@ -1267,13 +1275,13 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
           return true;
         },
         50, 200000);
-    Assert.assertTrue(heartBeatID.get() >= 1);
-    Assert.assertTrue(nm.getNMContext().getDecommissioned());
+    assertTrue(heartBeatID.get() >= 1);
+    assertTrue(nm.getNMContext().getDecommissioned());
 
     // NM takes a while to reach the STOPPED state.
     nm.waitForServiceToStop(20000);
 
-    Assert.assertEquals(STATE.STOPPED, nm.getServiceState());
+    assertEquals(STATE.STOPPED, nm.getServiceState());
   }
 
   private abstract class NodeManagerWithCustomNodeStatusUpdater extends NodeManager {
@@ -1321,7 +1329,8 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         + "Message from ResourceManager: RM Shutting Down Node");
   }
 
-  @Test (timeout = 100000)
+  @Test
+  @Timeout(value = 100)
   public void testNMRMConnectionConf() throws Exception {
     final long delta = 50000;
     final long nmRmConnectionWaitMs = 100;
@@ -1357,7 +1366,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     long waitStartTime = System.currentTimeMillis();
     try {
       nm.start();
-      Assert.fail("NM should have failed to start due to RM connect failure");
+      fail("NM should have failed to start due to RM connect failure");
     } catch(Exception e) {
       long t = System.currentTimeMillis();
       long duration = t - waitStartTime;
@@ -1402,7 +1411,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     long waitStartTime = System.currentTimeMillis();
     try {
       nm.start();
-      Assert.fail("NM should have failed to start due to RM connect failure");
+      fail("NM should have failed to start due to RM connect failure");
     } catch(Exception e) {
       long t = System.currentTimeMillis();
       long duration = t - waitStartTime;
@@ -1432,7 +1441,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     };
     nm.init(conf);
     NodeStatusUpdater updater = nmWithUpdater.getUpdater();
-    Assert.assertNotNull("Updater not yet created ", updater);
+    assertNotNull(updater, "Updater not yet created ");
     waitStartTime = System.currentTimeMillis();
     try {
       nm.start();
@@ -1443,26 +1452,27 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     }
     long duration = System.currentTimeMillis() - waitStartTime;
     MyNodeStatusUpdater4 myUpdater = (MyNodeStatusUpdater4) updater;
-    Assert.assertTrue("NM started before updater triggered",
-                      myUpdater.isTriggered());
-    Assert.assertTrue("NM should have connected to RM after "
+    assertTrue(myUpdater.isTriggered(), "NM started before updater triggered");
+    assertTrue((duration >= rmStartIntervalMS),
+        "NM should have connected to RM after "
         +"the start interval of " + rmStartIntervalMS
         +": actual " + duration
-        + " " + myUpdater,
-        (duration >= rmStartIntervalMS));
-    Assert.assertTrue("NM should have connected to RM less than "
+        + " " + myUpdater);
+    assertTrue((duration < (rmStartIntervalMS + delta)),
+        "NM should have connected to RM less than "
         + (rmStartIntervalMS + delta)
         +" milliseconds of RM starting up: actual " + duration
-        + " " + myUpdater,
-        (duration < (rmStartIntervalMS + delta)));
+        + " " + myUpdater);
   }
 
-  @Test (timeout = 150000)
+  @Test
+  @Timeout(value = 150)
   public void testNMConnectionToRM() throws Exception {
     testNMConnectionToRMInternal(false);
   }
 
-  @Test (timeout = 150000)
+  @Test
+  @Timeout(value = 150)
   public void testNMConnectionToRMwithSocketTimeout() throws Exception {
     testNMConnectionToRMInternal(true);
   }
@@ -1523,21 +1533,21 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
               || heartBeatID.get() >= 12,
           100L, 60000000);
 
-      Assert.assertTrue(heartBeatID.get() >= 12);
+      assertTrue(heartBeatID.get() >= 12);
       MyResourceTracker3 rt =
           (MyResourceTracker3) nm.getNodeStatusUpdater().getRMClient();
       rt.context.getApplications().remove(rt.appId);
-      Assert.assertEquals(1, rt.keepAliveRequests.size());
+      assertEquals(1, rt.keepAliveRequests.size());
       int numKeepAliveRequests = rt.keepAliveRequests.get(rt.appId).size();
       LOG.info("Number of Keep Alive Requests: [{}]", numKeepAliveRequests);
-      Assert.assertTrue(numKeepAliveRequests == 2 || numKeepAliveRequests == 3);
+      assertTrue(numKeepAliveRequests == 2 || numKeepAliveRequests == 3);
       GenericTestUtils.waitFor(
           () -> nm.getServiceState() != STATE.STARTED
               || heartBeatID.get() >= 20,
           100L, 60000000);
-      Assert.assertTrue(heartBeatID.get() >= 20);
+      assertTrue(heartBeatID.get() >= 20);
       int numKeepAliveRequests2 = rt.keepAliveRequests.get(rt.appId).size();
-      Assert.assertEquals(numKeepAliveRequests, numKeepAliveRequests2);
+      assertEquals(numKeepAliveRequests, numKeepAliveRequests2);
     } finally {
       if (nm != null) {
         nm.stop();
@@ -1550,7 +1560,8 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
    * Test completed containerStatus get back up when heart beat lost, and will
    * be sent via next heart beat.
    */
-  @Test(timeout = 200000)
+  @Test
+  @Timeout(value = 200)
   public void testCompletedContainerStatusBackup() throws Exception {
     nm = new NodeManager() {
       @Override
@@ -1584,15 +1595,16 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         () -> nm.getServiceState() != STATE.STARTED || heartBeatID.get() > 4,
         50, 20000);
     int hbID = heartBeatID.get();
-    Assert.assertFalse("Failed to get all heartbeats in time, "
-        + "heartbeatID:" + hbID, hbID <= 4);
-    Assert.assertFalse("ContainerStatus Backup failed",
-        assertionFailedInThread.get());
-    Assert.assertNotNull(nm.getNMContext().getSystemCredentialsForApps()
+    assertFalse(hbID <= 4, "Failed to get all heartbeats in time, "
+        + "heartbeatID:" + hbID);
+    assertFalse(assertionFailedInThread.get(),
+        "ContainerStatus Backup failed");
+    assertNotNull(nm.getNMContext().getSystemCredentialsForApps()
       .get(ApplicationId.newInstance(1234, 1)).getToken(new Text("token1")));
   }
 
-  @Test(timeout = 200000)
+  @Test
+  @Timeout(value = 200)
   public void testNodeStatusUpdaterRetryAndNMShutdown()
       throws Exception {
     final long connectionWaitSecs = 1000;
@@ -1623,11 +1635,11 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       syncBarrier.await(10000, TimeUnit.MILLISECONDS);
     } catch (Exception e) {
     }
-    Assert.assertFalse("Containers not cleaned up when NM stopped",
-      assertionFailedInThread.get());
-    Assert.assertTrue(((MyNodeManager2) nm).isStopped);
-    Assert.assertEquals("calculate heartBeatCount based on" +
-        " connectionWaitSecs and RetryIntervalSecs", 2, heartBeatID.get());
+    assertFalse(assertionFailedInThread.get(),
+        "Containers not cleaned up when NM stopped");
+    assertTrue(((MyNodeManager2) nm).isStopped);
+    assertEquals(2, heartBeatID.get(), "calculate heartBeatCount based on" +
+        " connectionWaitSecs and RetryIntervalSecs");
   }
 
   @Test
@@ -1707,13 +1719,13 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
         () -> nm.getServiceState() != STATE.STARTED
             || heartBeatID.get() > 3,
         50, 20000);
-    Assert.assertTrue(heartBeatID.get() > 3);
-    Assert.assertEquals("Number of registered NMs is wrong!!", 1,
-        this.registeredNodes.size());
+    assertTrue(heartBeatID.get() > 3);
+    assertEquals(1, this.registeredNodes.size(),
+        "Number of registered NMs is wrong!!");
 
     MyContainerManager containerManager =
         (MyContainerManager)nm.getContainerManager();
-    Assert.assertTrue(containerManager.signaled);
+    assertTrue(containerManager.signaled);
   }
 
   @Test
@@ -1750,7 +1762,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
                 NodeHeartbeatResponseProto proto =
                     ((NodeHeartbeatResponsePBImpl)nodeHeartBeatResponse)
                         .getProto();
-                Assert.assertNotNull(proto);
+                assertNotNull(proto);
               }
             } catch (Throwable t) {
               exceptions.add(t);
@@ -1763,16 +1775,16 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       }
 
       int testTimeout = 2;
-      Assert.assertTrue("Timeout waiting for more than " + testTimeout + " " +
-              "seconds",
-          allDone.await(testTimeout, TimeUnit.SECONDS));
+      assertTrue(allDone.await(testTimeout, TimeUnit.SECONDS),
+          "Timeout waiting for more than " + testTimeout + " " +
+          "seconds");
     } catch (InterruptedException ie) {
       exceptions.add(ie);
     } finally {
       threadPool.shutdownNow();
     }
-    Assert.assertTrue("Test failed with exception(s)" + exceptions,
-        exceptions.isEmpty());
+    assertTrue(exceptions.isEmpty(),
+        "Test failed with exception(s)" + exceptions);
   }
 
   /**
@@ -1805,9 +1817,9 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       ContainerManager containerManager = nodeManager.getContainerManager();
       ContainersMonitor containerMonitor =
           containerManager.getContainersMonitor();
-      Assert.assertEquals(8,
+      assertEquals(8,
           containerMonitor.getVCoresAllocatedForContainers());
-      Assert.assertEquals(8 * GB,
+      assertEquals(8 * GB,
           containerMonitor.getPmemAllocatedForContainers());
 
       LOG.info("The first heartbeat should trigger a resource change to {}",
@@ -1815,7 +1827,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       GenericTestUtils.waitFor(
           () -> containerMonitor.getVCoresAllocatedForContainers() == 1,
           100, 2 * 1000);
-      Assert.assertEquals(8 * GB,
+      assertEquals(8 * GB,
           containerMonitor.getPmemAllocatedForContainers());
 
       resource.setVirtualCores(5);
@@ -1824,7 +1836,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
       GenericTestUtils.waitFor(
           () -> containerMonitor.getVCoresAllocatedForContainers() == 5,
           100, 2 * 1000);
-      Assert.assertEquals(4 * GB,
+      assertEquals(4 * GB,
           containerMonitor.getPmemAllocatedForContainers());
     } finally {
       LOG.info("Cleanup");
@@ -1956,7 +1968,7 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
   }
 
   private void verifyNodeStartFailure(String errMessage) throws Exception {
-    Assert.assertNotNull("nm is null", nm);
+    assertNotNull(nm, "nm is null");
     YarnConfiguration conf = createNMConfig();
     nm.init(conf);
 
@@ -1967,11 +1979,10 @@ public class TestNodeStatusUpdater extends NodeManagerTestBase {
     LambdaTestUtils.intercept(Exception.class, errMessage, () -> nm.start());
 
     // the service should be stopped
-    Assert.assertEquals("NM state is wrong!", STATE.STOPPED,
-        nm.getServiceState());
+    assertEquals(STATE.STOPPED, nm.getServiceState(), "NM state is wrong!");
 
-    Assert.assertEquals("Number of registered nodes is wrong!", 0,
-        this.registeredNodes.size());
+    assertEquals(0, this.registeredNodes.size(),
+        "Number of registered nodes is wrong!");
   }
 
   private NodeManager getNodeManager(final NodeAction nodeHeartBeatAction) {

+ 35 - 32
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdaterForAttributes.java

@@ -18,9 +18,10 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-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.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.IOException;
 import java.lang.Thread.State;
@@ -59,10 +60,10 @@ import org.apache.hadoop.yarn.server.api.records.impl.pb.MasterKeyPBImpl;
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.server.nodemanager.nodelabels.NodeAttributesProvider;
 import org.apache.hadoop.yarn.server.utils.YarnServerBuilderUtils;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 /**
  * Test NodeStatusUpdater for node attributes.
@@ -74,12 +75,12 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
   private NodeManager nm;
   private DummyNodeAttributesProvider dummyAttributesProviderRef;
 
-  @Before
+  @BeforeEach
   public void setup() {
     dummyAttributesProviderRef = new DummyNodeAttributesProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     if (null != nm) {
       ServiceOperations.stop(nm);
@@ -122,7 +123,7 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
         throws InterruptedException, TimeoutException {
       GenericTestUtils.waitFor(() -> receivedNMHeartbeat, 100, 30000);
       if (!receivedNMHeartbeat) {
-        Assert.fail("Heartbeat is not received even after waiting");
+        fail("Heartbeat is not received even after waiting");
       }
     }
 
@@ -130,7 +131,7 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
         throws InterruptedException, TimeoutException {
       GenericTestUtils.waitFor(() -> receivedNMRegister, 100, 30000);
       if (!receivedNMRegister) {
-        Assert.fail("Registration is not received even after waiting");
+        fail("Registration is not received even after waiting");
       }
     }
 
@@ -205,7 +206,8 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
     return conf;
   }
 
-  @Test(timeout = 20000)
+  @Test
+  @Timeout(value = 20)
   public void testNodeStatusUpdaterForNodeAttributes()
       throws InterruptedException, IOException, TimeoutException {
     final ResourceTrackerForAttributes resourceTracker =
@@ -270,19 +272,17 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
     resourceTracker.resetNMHeartbeatReceiveFlag();
-    assertNull("If no change in attributes"
-            + " then null should be sent as part of request",
-        resourceTracker.attributes);
+    assertNull(resourceTracker.attributes, "If no change in attributes"
+        + " then null should be sent as part of request");
 
     // provider return with null attributes
     dummyAttributesProviderRef.setDescriptors(null);
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNotNull("If provider sends null"
-            + " then empty label set should be sent and not null",
-        resourceTracker.attributes);
-    assertTrue("If provider sends null then empty attributes should be sent",
-        resourceTracker.attributes.isEmpty());
+    assertNotNull(resourceTracker.attributes, "If provider sends null"
+        + " then empty label set should be sent and not null");
+    assertTrue(resourceTracker.attributes.isEmpty(),
+        "If provider sends null then empty attributes should be sent");
     resourceTracker.resetNMHeartbeatReceiveFlag();
     // Since the resync interval is set to 2 sec in every alternate heartbeat
     // the attributes will be send along with heartbeat.
@@ -297,22 +297,23 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
       if (null == resourceTracker.attributes) {
         nullAttributes++;
       } else {
-        Assert.assertTrue("In heartbeat PI attributes should be send",
-            NodeLabelUtil.isNodeAttributesEquals(ImmutableSet.of(attribute1),
-                resourceTracker.attributes));
+        assertTrue(NodeLabelUtil.isNodeAttributesEquals(ImmutableSet.of(attribute1),
+            resourceTracker.attributes),
+            "In heartbeat PI attributes should be send");
         nonNullAttributes++;
       }
       resourceTracker.resetNMHeartbeatReceiveFlag();
       Thread.sleep(1000);
     }
-    Assert.assertTrue("More than one heartbeat with empty attributes expected",
-        nullAttributes > 1);
-    Assert.assertTrue("More than one heartbeat with attributes expected",
-        nonNullAttributes > 1);
+    assertTrue(nullAttributes > 1,
+        "More than one heartbeat with empty attributes expected");
+    assertTrue(nonNullAttributes > 1,
+        "More than one heartbeat with attributes expected");
     nm.stop();
   }
 
-  @Test(timeout = 20000)
+  @Test
+  @Timeout(value = 20)
   public void testInvalidNodeAttributesFromProvider()
       throws InterruptedException, IOException, TimeoutException {
     final ResourceTrackerForAttributes resourceTracker =
@@ -393,8 +394,9 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
         .setDescriptors(ImmutableSet.of(invalidAttribute));
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNull("On Invalid Attributes we need to retain earlier attributes, HB"
-        + " needs to send null", resourceTracker.attributes);
+    assertNull(resourceTracker.attributes,
+        "On Invalid Attributes we need to retain earlier attributes, HB"
+        + " needs to send null");
     resourceTracker.resetNMHeartbeatReceiveFlag();
 
     // on next heartbeat same invalid attributes will be given by the provider,
@@ -402,8 +404,9 @@ public class TestNodeStatusUpdaterForAttributes extends NodeLabelTestBase {
     // should not happen
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNull("NodeStatusUpdater need not send repeatedly empty attributes on"
-        + " invalid attributes from provider ", resourceTracker.attributes);
+    assertNull(resourceTracker.attributes,
+        "NodeStatusUpdater need not send repeatedly empty attributes on"
+        + " invalid attributes from provider ");
     resourceTracker.resetNMHeartbeatReceiveFlag();
   }
 

+ 34 - 30
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdaterForLabels.java

@@ -18,9 +18,11 @@
 
 package org.apache.hadoop.yarn.server.nodemanager;
 
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 import java.lang.Thread.State;
@@ -53,10 +55,10 @@ import org.apache.hadoop.yarn.server.api.records.impl.pb.MasterKeyPBImpl;
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.server.nodemanager.nodelabels.NodeLabelsProvider;
 import org.apache.hadoop.yarn.server.utils.YarnServerBuilderUtils;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
   private static final RecordFactory recordFactory = RecordFactoryProvider
@@ -65,12 +67,12 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
   private NodeManager nm;
   protected DummyNodeLabelsProvider dummyLabelsProviderRef;
 
-  @Before
+  @BeforeEach
   public void setup() {
     dummyLabelsProviderRef = new DummyNodeLabelsProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     if (null != nm) {
       ServiceOperations.stop(nm);
@@ -126,7 +128,7 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
         }
       }
       if (!receivedNMHeartbeat) {
-        Assert.fail("Heartbeat dint receive even after waiting");
+        fail("Heartbeat dint receive even after waiting");
       }
     }
 
@@ -215,7 +217,8 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
     return conf;
   }
 
-  @Test(timeout=20000)
+  @Test
+  @Timeout(value = 20)
   public void testNodeStatusUpdaterForNodeLabels() throws InterruptedException,
       IOException {
     final ResourceTrackerForLabels resourceTracker =
@@ -274,19 +277,17 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
     resourceTracker.resetNMHeartbeatReceiveFlag();
-    assertNull(
-        "If no change in labels then null should be sent as part of request",
-        resourceTracker.labels);
+    assertNull(resourceTracker.labels,
+        "If no change in labels then null should be sent as part of request");
 
     // provider return with null labels
     dummyLabelsProviderRef.setDescriptors(null);
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNotNull(
-        "If provider sends null then empty label set should be sent and not null",
-        resourceTracker.labels);
-    assertTrue("If provider sends null then empty labels should be sent",
-        resourceTracker.labels.isEmpty());
+    assertNotNull(resourceTracker.labels,
+        "If provider sends null then empty label set should be sent and not null");
+    assertTrue(resourceTracker.labels.isEmpty(),
+        "If provider sends null then empty labels should be sent");
     resourceTracker.resetNMHeartbeatReceiveFlag();
     // Since the resync interval is set to 2 sec in every alternate heartbeat
     // the labels will be send along with heartbeat.In loop we sleep for 1 sec
@@ -300,21 +301,22 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
       if (null == resourceTracker.labels) {
         nullLabels++;
       } else {
-        Assert.assertEquals("In heartbeat PI labels should be send",
-            toNodeLabelSet("P1"), resourceTracker.labels);
+        assertEquals(toNodeLabelSet("P1"), resourceTracker.labels,
+            "In heartbeat PI labels should be send");
         nonNullLabels++;
       }
       resourceTracker.resetNMHeartbeatReceiveFlag();
       Thread.sleep(1000);
     }
-    Assert.assertTrue("More than one heartbeat with empty labels expected",
-        nullLabels > 1);
-    Assert.assertTrue("More than one heartbeat with labels expected",
-        nonNullLabels > 1);
+    assertTrue(nullLabels > 1,
+        "More than one heartbeat with empty labels expected");
+    assertTrue(nonNullLabels > 1,
+        "More than one heartbeat with labels expected");
     nm.stop();
   }
 
-  @Test(timeout=20000)
+  @Test
+  @Timeout(value = 20)
   public void testInvalidNodeLabelsFromProvider() throws InterruptedException,
       IOException {
     final ResourceTrackerForLabels resourceTracker =
@@ -360,8 +362,9 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
 
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNull("On Invalid Labels we need to retain earlier labels, HB "
-        + "needs to send null", resourceTracker.labels);
+    assertNull(resourceTracker.labels,
+        "On Invalid Labels we need to retain earlier labels, HB "
+        + "needs to send null");
     resourceTracker.resetNMHeartbeatReceiveFlag();
 
     // on next heartbeat same invalid labels will be given by the provider, but
@@ -369,8 +372,9 @@ public class TestNodeStatusUpdaterForLabels extends NodeLabelTestBase {
     // not happen
     sendOutofBandHeartBeat();
     resourceTracker.waitTillHeartbeat();
-    assertNull("NodeStatusUpdater need not send repeatedly empty labels on "
-        + "invalid labels from provider ", resourceTracker.labels);
+    assertNull(resourceTracker.labels,
+        "NodeStatusUpdater need not send repeatedly empty labels on "
+        + "invalid labels from provider ");
     resourceTracker.resetNMHeartbeatReceiveFlag();
   }
 

+ 8 - 7
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestRPCFactories.java

@@ -22,8 +22,6 @@ import java.net.InetSocketAddress;
 import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse;
 import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus;
 
-import org.junit.Assert;
-
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.ipc.Server;
 import org.apache.hadoop.net.NetUtils;
@@ -31,7 +29,10 @@ import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 import org.apache.hadoop.yarn.factories.impl.pb.RpcClientFactoryPBImpl;
 import org.apache.hadoop.yarn.factories.impl.pb.RpcServerFactoryPBImpl;
 import org.apache.hadoop.yarn.server.nodemanager.api.LocalizationProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestRPCFactories {
   
@@ -58,7 +59,7 @@ public class TestRPCFactories {
       server.start();
     } catch (YarnRuntimeException e) {
       e.printStackTrace();
-      Assert.fail("Failed to create server");
+      fail("Failed to create server");
     } finally {
       if (server != null) {
         server.stop();
@@ -86,15 +87,15 @@ public class TestRPCFactories {
           RpcClientFactoryPBImpl.get().getClient(
               LocalizationProtocol.class, 1,
               NetUtils.getConnectAddress(server), conf);
-        Assert.assertNotNull(client);
+        assertNotNull(client);
       } catch (YarnRuntimeException e) {
         e.printStackTrace();
-        Assert.fail("Failed to create client");
+        fail("Failed to create client");
       }
       
     } catch (YarnRuntimeException e) {
       e.printStackTrace();
-      Assert.fail("Failed to create server");
+      fail("Failed to create server");
     } finally {
       server.stop();
     }     

+ 6 - 4
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestRecordFactory.java

@@ -23,8 +23,10 @@ import org.apache.hadoop.yarn.factories.impl.pb.RecordFactoryPBImpl;
 import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse;
 import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.impl.pb.LocalizerHeartbeatResponsePBImpl;
 
-import org.junit.Test;
-import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestRecordFactory {
   
@@ -35,11 +37,11 @@ public class TestRecordFactory {
     try {
       LocalizerHeartbeatResponse response = pbRecordFactory.newRecordInstance(
           LocalizerHeartbeatResponse.class);
-      Assert.assertEquals(LocalizerHeartbeatResponsePBImpl.class,
+      assertEquals(LocalizerHeartbeatResponsePBImpl.class,
                           response.getClass());
     } catch (YarnRuntimeException e) {
       e.printStackTrace();
-      Assert.fail("Failed to crete record");
+      fail("Failed to crete record");
     }
   }
 

+ 1 - 1
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestExceptionReporter.java

@@ -17,7 +17,7 @@
  */
 package org.apache.hadoop.yarn.server.nodemanager.health;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
 

+ 30 - 29
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestNodeHealthCheckerService.java

@@ -39,13 +39,14 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.factories.RecordFactory;
 import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
 import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
 
@@ -67,12 +68,12 @@ public class TestNodeHealthCheckerService {
   private File nodeHealthScriptFile = new File(TEST_ROOT_DIR,
       Shell.appendScriptExtension("failingscript"));
 
-  @Before
+  @BeforeEach
   public void setup() {
     TEST_ROOT_DIR.mkdirs();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (TEST_ROOT_DIR.exists()) {
       FileContext.getLocalFSFileContext().delete(
@@ -151,10 +152,10 @@ public class TestNodeHealthCheckerService {
         nodeHealthChecker.getLastHealthReportTime());
     LOG.info("Checking initial healthy condition");
     // Check proper report conditions.
-    Assert.assertTrue("Node health status reported unhealthy", healthStatus
-        .getIsNodeHealthy());
-    Assert.assertTrue("Node health status reported unhealthy", healthStatus
-        .getHealthReport().equals(nodeHealthChecker.getHealthReport()));
+    assertTrue(healthStatus
+        .getIsNodeHealthy(), "Node health status reported unhealthy");
+    assertTrue(healthStatus.getHealthReport().equals(nodeHealthChecker.getHealthReport()),
+        "Node health status reported unhealthy");
 
     doReturn(false).when(nodeHealthScriptRunner).isHealthy();
     // update health status
@@ -162,10 +163,11 @@ public class TestNodeHealthCheckerService {
         nodeHealthChecker.getHealthReport(),
         nodeHealthChecker.getLastHealthReportTime());
     LOG.info("Checking Healthy--->Unhealthy");
-    Assert.assertFalse("Node health status reported healthy", healthStatus
-        .getIsNodeHealthy());
-    Assert.assertTrue("Node health status reported healthy", healthStatus
-        .getHealthReport().equals(nodeHealthChecker.getHealthReport()));
+    assertFalse(healthStatus
+        .getIsNodeHealthy(), "Node health status reported healthy");
+    assertTrue(healthStatus
+        .getHealthReport().equals(nodeHealthChecker.getHealthReport()),
+        "Node health status reported healthy");
 
     doReturn(true).when(nodeHealthScriptRunner).isHealthy();
     setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(),
@@ -173,10 +175,10 @@ public class TestNodeHealthCheckerService {
         nodeHealthChecker.getLastHealthReportTime());
     LOG.info("Checking UnHealthy--->healthy");
     // Check proper report conditions.
-    Assert.assertTrue("Node health status reported unhealthy", healthStatus
-        .getIsNodeHealthy());
-    Assert.assertTrue("Node health status reported unhealthy", healthStatus
-        .getHealthReport().equals(nodeHealthChecker.getHealthReport()));
+    assertTrue(healthStatus
+        .getIsNodeHealthy(), "Node health status reported unhealthy");
+    assertTrue(healthStatus.getHealthReport().equals(nodeHealthChecker.getHealthReport()),
+        "Node health status reported unhealthy");
 
     // Healthy to timeout transition.
     doReturn(false).when(nodeHealthScriptRunner).isHealthy();
@@ -186,16 +188,15 @@ public class TestNodeHealthCheckerService {
         nodeHealthChecker.getHealthReport(),
         nodeHealthChecker.getLastHealthReportTime());
     LOG.info("Checking Healthy--->timeout");
-    Assert.assertFalse("Node health status reported healthy even after timeout",
-        healthStatus.getIsNodeHealthy());
-    Assert.assertTrue("Node script time out message not propagated",
-        healthStatus.getHealthReport().equals(
-            Joiner.on(NodeHealthCheckerService.SEPARATOR).skipNulls().join(
-                NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG,
-                Strings.emptyToNull(
-                    nodeHealthChecker.getDiskHandler()
-                        .getDisksHealthReport(false))
-            )));
+    assertFalse(healthStatus.getIsNodeHealthy(),
+        "Node health status reported healthy even after timeout");
+    assertTrue(healthStatus.getHealthReport().equals(
+        Joiner.on(NodeHealthCheckerService.SEPARATOR).skipNulls().join(
+            NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG,
+            Strings.emptyToNull(
+                nodeHealthChecker.getDiskHandler()
+                    .getDisksHealthReport(false))
+        )), "Node script time out message not propagated");
   }
 
   private abstract class HealthReporterService extends AbstractService

+ 24 - 27
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestNodeHealthScriptRunner.java

@@ -30,13 +30,13 @@ import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-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 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;
 
 /**
  * Test class for {@link NodeHealthScriptRunner}.
@@ -50,12 +50,12 @@ public class TestNodeHealthScriptRunner {
   private File nodeHealthscriptFile = new File(testRootDir,
       Shell.appendScriptExtension("failingscript"));
 
-  @Before
+  @BeforeEach
   public void setup() {
     testRootDir.mkdirs();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (testRootDir.exists()) {
       FileContext.getLocalFSFileContext().delete(
@@ -106,19 +106,16 @@ public class TestNodeHealthScriptRunner {
 
   @Test
   public void testNodeHealthScriptShouldRun() throws IOException {
-    assertFalse("Node health script should start",
-        NodeHealthScriptRunner.shouldRun("script",
-            nodeHealthscriptFile.getAbsolutePath()));
+    assertFalse(NodeHealthScriptRunner.shouldRun("script",
+        nodeHealthscriptFile.getAbsolutePath()), "Node health script should start");
     writeNodeHealthScriptFile("", false);
     // Node health script should not start if the node health script is not
     // executable.
-    assertFalse("Node health script should start",
-        NodeHealthScriptRunner.shouldRun("script",
-            nodeHealthscriptFile.getAbsolutePath()));
+    assertFalse(NodeHealthScriptRunner.shouldRun("script",
+        nodeHealthscriptFile.getAbsolutePath()), "Node health script should start");
     writeNodeHealthScriptFile("", true);
-    assertTrue("Node health script should start",
-        NodeHealthScriptRunner.shouldRun("script",
-            nodeHealthscriptFile.getAbsolutePath()));
+    assertTrue(NodeHealthScriptRunner.shouldRun("script",
+        nodeHealthscriptFile.getAbsolutePath()), "Node health script should start");
   }
 
   @Test
@@ -139,31 +136,31 @@ public class TestNodeHealthScriptRunner {
 
     timerTask.run();
     // Normal Script runs successfully
-    assertTrue("Node health status reported unhealthy",
-        nodeHealthScriptRunner.isHealthy());
+    assertTrue(nodeHealthScriptRunner.isHealthy(),
+        "Node health status reported unhealthy");
     assertTrue(nodeHealthScriptRunner.getHealthReport().isEmpty());
 
     // Error script.
     writeNodeHealthScriptFile(errorScript, true);
     // Run timer
     timerTask.run();
-    assertFalse("Node health status reported healthy",
-        nodeHealthScriptRunner.isHealthy());
+    assertFalse(nodeHealthScriptRunner.isHealthy(),
+        "Node health status reported healthy");
     assertTrue(
         nodeHealthScriptRunner.getHealthReport().contains("ERROR"));
 
     // Healthy script.
     writeNodeHealthScriptFile(normalScript, true);
     timerTask.run();
-    assertTrue("Node health status reported unhealthy",
-        nodeHealthScriptRunner.isHealthy());
+    assertTrue(nodeHealthScriptRunner.isHealthy(),
+        "Node health status reported unhealthy");
     assertTrue(nodeHealthScriptRunner.getHealthReport().isEmpty());
 
     // Timeout script.
     writeNodeHealthScriptFile(timeOutScript, true);
     timerTask.run();
-    assertFalse("Node health status reported healthy even after timeout",
-        nodeHealthScriptRunner.isHealthy());
+    assertFalse(nodeHealthScriptRunner.isHealthy(),
+        "Node health status reported healthy even after timeout");
     assertEquals(
         NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG,
         nodeHealthScriptRunner.getHealthReport());
@@ -171,8 +168,8 @@ public class TestNodeHealthScriptRunner {
     // Exit code 127
     writeNodeHealthScriptFile(exitCodeScript, true);
     timerTask.run();
-    assertTrue("Node health status reported unhealthy",
-        nodeHealthScriptRunner.isHealthy());
+    assertTrue(nodeHealthScriptRunner.isHealthy(),
+        "Node health status reported unhealthy");
     assertEquals("", nodeHealthScriptRunner.getHealthReport());
   }
 }

+ 26 - 25
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/logaggregation/tracker/TestNMLogAggregationStatusTracker.java

@@ -33,8 +33,10 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.api.protocolrecords.LogAggregationReport;
 import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Function test for {@link NMLogAggregationStatusTracker}.
@@ -65,8 +67,8 @@ public class TestNMLogAggregationStatusTracker {
         .pullCachedLogAggregationReports();
     // we can not get any cached log aggregation status because
     // the log aggregation is disabled.
-    Assert.assertTrue("No cached log aggregation status because "
-        + "log aggregation is disabled.", reports.isEmpty());
+    assertTrue(reports.isEmpty(), "No cached log aggregation status because "
+        + "log aggregation is disabled.");
 
     // enable the log aggregation.
     conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true);
@@ -79,28 +81,27 @@ public class TestNMLogAggregationStatusTracker {
         LogAggregationStatus.RUNNING, baseTime, "", false);
     reports = tracker
         .pullCachedLogAggregationReports();
-    Assert.assertTrue("No cached log aggregation status "
-        + "because the application is finished or not existed.",
-        reports.isEmpty());
+    assertTrue(reports.isEmpty(), "No cached log aggregation status "
+        + "because the application is finished or not existed.");
 
     tracker.updateLogAggregationStatus(appId1,
         LogAggregationStatus.RUNNING, baseTime, "", false);
     reports = tracker
         .pullCachedLogAggregationReports();
-    Assert.assertEquals("Should have one cached log aggregation status.",
-        1, reports.size());
-    Assert.assertEquals("The cached log aggregation status should be RUNNING.",
-        LogAggregationStatus.RUNNING,
-        reports.get(0).getLogAggregationStatus());
+    assertEquals(1, reports.size(),
+        "Should have one cached log aggregation status.");
+    assertEquals(LogAggregationStatus.RUNNING,
+        reports.get(0).getLogAggregationStatus(),
+        "The cached log aggregation status should be RUNNING.");
 
     tracker.updateLogAggregationStatus(appId1,
         LogAggregationStatus.SUCCEEDED, baseTime + 60 * 1000, "", true);
     reports = tracker
         .pullCachedLogAggregationReports();
-    Assert.assertEquals(1, reports.size());
-    Assert.assertEquals("Update cached log aggregation status to SUCCEEDED",
-        LogAggregationStatus.SUCCEEDED,
-        reports.get(0).getLogAggregationStatus());
+    assertEquals(1, reports.size());
+    assertEquals(LogAggregationStatus.SUCCEEDED,
+        reports.get(0).getLogAggregationStatus(),
+        "Update cached log aggregation status to SUCCEEDED");
 
     // the log aggregation status is finalized. So, we would
     // ingore the following update
@@ -108,10 +109,10 @@ public class TestNMLogAggregationStatusTracker {
         LogAggregationStatus.FAILED, baseTime + 10 * 60 * 1000, "", true);
     reports = tracker
         .pullCachedLogAggregationReports();
-    Assert.assertEquals(1, reports.size());
-    Assert.assertEquals("The cached log aggregation status "
-        + "should be still SUCCEEDED.", LogAggregationStatus.SUCCEEDED,
-        reports.get(0).getLogAggregationStatus());
+    assertEquals(1, reports.size());
+    assertEquals(LogAggregationStatus.SUCCEEDED,
+        reports.get(0).getLogAggregationStatus(), "The cached log aggregation status "
+        + "should be still SUCCEEDED.");
   }
 
   public void testLogAggregationStatusRoller() throws Exception {
@@ -133,11 +134,11 @@ public class TestNMLogAggregationStatusTracker {
     // verify that we have cached the log aggregation status for app1
     List<LogAggregationReport> reports = tracker
         .pullCachedLogAggregationReports();
-    Assert.assertEquals("Should have one cached log aggregation status.",
-        1, reports.size());
-    Assert.assertEquals("The cached log aggregation status should be RUNNING.",
-        LogAggregationStatus.RUNNING,
-        reports.get(0).getLogAggregationStatus());
+    assertEquals(1, reports.size(),
+        "Should have one cached log aggregation status.");
+    assertEquals(LogAggregationStatus.RUNNING,
+        reports.get(0).getLogAggregationStatus(),
+        "The cached log aggregation status should be RUNNING.");
     // wait for 10s
     GenericTestUtils.waitFor(new Supplier<Boolean>() {
       @Override

+ 20 - 16
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/metrics/TestNodeManagerMetrics.java

@@ -37,24 +37,27 @@ import org.apache.hadoop.yarn.metrics.GenericEventTypeMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
 import org.apache.hadoop.yarn.util.Records;
 
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestNodeManagerMetrics {
   static final int GiB = 1024; // MiB
 
   private NodeManagerMetrics metrics;
 
-  @Before
+  @BeforeEach
   public void setup() {
     DefaultMetricsSystem.initialize("NodeManager");
     DefaultMetricsSystem.setMiniClusterMode(true);
     metrics = NodeManagerMetrics.create();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     DefaultMetricsSystem.shutdown();
   }
@@ -62,8 +65,9 @@ public class TestNodeManagerMetrics {
   @Test
   public void testReferenceOfSingletonJvmMetrics()  {
     JvmMetrics jvmMetrics = JvmMetrics.initSingleton("NodeManagerModule", null);
-    Assert.assertEquals("NodeManagerMetrics should reference the singleton" +
-        " JvmMetrics instance", jvmMetrics, metrics.getJvmMetrics());
+    assertEquals(jvmMetrics, metrics.getJvmMetrics(),
+        "NodeManagerMetrics should reference the singleton" +
+        " JvmMetrics instance");
   }
 
   @Test public void testNames() {
@@ -110,9 +114,9 @@ public class TestNodeManagerMetrics {
     // Decrease resource for a container
     metrics.changeContainer(resource, smallerResource);
 
-    Assert.assertTrue(!metrics.containerLaunchDuration.changed());
+    assertTrue(!metrics.containerLaunchDuration.changed());
     metrics.addContainerLaunchDuration(1);
-    Assert.assertTrue(metrics.containerLaunchDuration.changed());
+    assertTrue(metrics.containerLaunchDuration.changed());
 
     // Set node gpu utilization
     metrics.setNodeGpuUtilization(35.5F);
@@ -223,18 +227,18 @@ public class TestNodeManagerMetrics {
 
     String testEventTypeCountExpect =
         Long.toString(genericEventTypeMetrics.get(TestEnum.TestEventType));
-    Assert.assertNotNull(testEventTypeCountExpect);
+    assertNotNull(testEventTypeCountExpect);
     String testEventTypeCountMetric =
         genericEventTypeMetrics.getRegistry().get("TestEventType_event_count").toString();
-    Assert.assertNotNull(testEventTypeCountMetric);
-    Assert.assertEquals(testEventTypeCountExpect, testEventTypeCountMetric);
+    assertNotNull(testEventTypeCountMetric);
+    assertEquals(testEventTypeCountExpect, testEventTypeCountMetric);
 
     String testEventTypeProcessingTimeExpect =
         Long.toString(genericEventTypeMetrics.getTotalProcessingTime(TestEnum.TestEventType));
-    Assert.assertNotNull(testEventTypeProcessingTimeExpect);
+    assertNotNull(testEventTypeProcessingTimeExpect);
     String testEventTypeProcessingTimeMetric =
         genericEventTypeMetrics.getRegistry().get("TestEventType_processing_time").toString();
-    Assert.assertNotNull(testEventTypeProcessingTimeMetric);
-    Assert.assertEquals(testEventTypeProcessingTimeExpect, testEventTypeProcessingTimeMetric);
+    assertNotNull(testEventTypeProcessingTimeMetric);
+    assertEquals(testEventTypeProcessingTimeExpect, testEventTypeProcessingTimeMetric);
   }
 }

+ 44 - 38
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestConfigurationNodeAttributesProvider.java

@@ -25,12 +25,12 @@ import org.apache.hadoop.yarn.api.records.NodeAttribute;
 import org.apache.hadoop.yarn.api.records.NodeAttributeKey;
 import org.apache.hadoop.yarn.api.records.NodeAttributeType;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.junit.BeforeClass;
-import org.junit.Before;
-import org.junit.AfterClass;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.Assert;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import org.mockito.Mockito;
 
@@ -42,6 +42,11 @@ import java.util.Set;
 import java.util.ArrayList;
 import java.util.concurrent.TimeoutException;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
 /**
  * Test class for node configuration node attributes provider.
  */
@@ -53,17 +58,17 @@ public class TestConfigurationNodeAttributesProvider {
 
   private ConfigurationNodeAttributesProvider nodeAttributesProvider;
 
-  @BeforeClass
+  @BeforeAll
   public static void create() {
     testRootDir.mkdirs();
   }
 
-  @Before
+  @BeforeEach
   public void setup() {
     nodeAttributesProvider = new ConfigurationNodeAttributesProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (nodeAttributesProvider != null) {
       nodeAttributesProvider.close();
@@ -71,7 +76,7 @@ public class TestConfigurationNodeAttributesProvider {
     }
   }
 
-  @AfterClass
+  @AfterAll
   public static void remove() throws Exception {
     if (testRootDir.exists()) {
       FileContext.getLocalFSFileContext()
@@ -79,7 +84,8 @@ public class TestConfigurationNodeAttributesProvider {
     }
   }
 
-  @Test(timeout=30000L)
+  @Test
+  @Timeout(30)
   public void testNodeAttributesFetchInterval()
       throws IOException, InterruptedException {
     Set<NodeAttribute> expectedAttributes1 = new HashSet<>();
@@ -100,7 +106,7 @@ public class TestConfigurationNodeAttributesProvider {
     spyProvider.start();
 
     // Verify init value is honored.
-    Assert.assertEquals(expectedAttributes1, spyProvider.getDescriptors());
+    assertEquals(expectedAttributes1, spyProvider.getDescriptors());
 
     // Configuration provider provides a different set of attributes.
     Set<NodeAttribute> expectedAttributes2 = new HashSet<>();
@@ -120,7 +126,7 @@ public class TestConfigurationNodeAttributesProvider {
     int times=5;
     while(times>0) {
       Set<NodeAttribute> current = spyProvider.getDescriptors();
-      Assert.assertEquals(1, current.size());
+      assertEquals(1, current.size());
       String attributeName =
           current.iterator().next().getAttributeKey().getAttributeName();
       if ("host".equals(attributeName)){
@@ -132,10 +138,10 @@ public class TestConfigurationNodeAttributesProvider {
       times--;
     }
     // We should either see the old value or the new value.
-    Assert.assertEquals(5, numOfNewValue + numOfOldValue);
+    assertEquals(5, numOfNewValue + numOfOldValue);
     // Both values should be more than 0.
-    Assert.assertTrue(numOfOldValue > 0);
-    Assert.assertTrue(numOfNewValue > 0);
+    assertTrue(numOfOldValue > 0);
+    assertTrue(numOfNewValue > 0);
   }
 
   @Test
@@ -156,7 +162,7 @@ public class TestConfigurationNodeAttributesProvider {
         .thenReturn(expectedAttributes1);
     spyProvider.init(conf);
     spyProvider.start();
-    Assert.assertEquals(expectedAttributes1,
+    assertEquals(expectedAttributes1,
         spyProvider.getDescriptors());
 
     // The configuration added another attribute,
@@ -178,11 +184,11 @@ public class TestConfigurationNodeAttributesProvider {
       }, 500, 1000);
     } catch (Exception e) {
       // Make sure we get the timeout exception.
-      Assert.assertTrue(e instanceof TimeoutException);
+      assertTrue(e instanceof TimeoutException);
       return;
     }
 
-    Assert.fail("Expecting a failure in previous check!");
+    fail("Expecting a failure in previous check!");
   }
 
   @Test
@@ -201,48 +207,48 @@ public class TestConfigurationNodeAttributesProvider {
     String attributesStr = "hostname,STRING,host1234:uptime,STRING,321543";
     Set<NodeAttribute> attributes = nodeAttributesProvider
         .parseAttributes(attributesStr);
-    Assert.assertEquals(2, attributes.size());
+    assertEquals(2, attributes.size());
     Iterator<NodeAttribute> ait = attributes.iterator();
 
     while(ait.hasNext()) {
       NodeAttribute attr = ait.next();
       NodeAttributeKey at = attr.getAttributeKey();
       if (at.getAttributeName().equals("hostname")) {
-        Assert.assertEquals("hostname", at.getAttributeName());
-        Assert.assertEquals(NodeAttribute.PREFIX_DISTRIBUTED,
+        assertEquals("hostname", at.getAttributeName());
+        assertEquals(NodeAttribute.PREFIX_DISTRIBUTED,
             at.getAttributePrefix());
-        Assert.assertEquals(NodeAttributeType.STRING,
+        assertEquals(NodeAttributeType.STRING,
             attr.getAttributeType());
-        Assert.assertEquals("host1234", attr.getAttributeValue());
+        assertEquals("host1234", attr.getAttributeValue());
       } else if (at.getAttributeName().equals("uptime")) {
-        Assert.assertEquals("uptime", at.getAttributeName());
-        Assert.assertEquals(NodeAttribute.PREFIX_DISTRIBUTED,
+        assertEquals("uptime", at.getAttributeName());
+        assertEquals(NodeAttribute.PREFIX_DISTRIBUTED,
             at.getAttributePrefix());
-        Assert.assertEquals(NodeAttributeType.STRING,
+        assertEquals(NodeAttributeType.STRING,
             attr.getAttributeType());
-        Assert.assertEquals("321543", attr.getAttributeValue());
+        assertEquals("321543", attr.getAttributeValue());
       } else {
-        Assert.fail("Unexpected attribute");
+        fail("Unexpected attribute");
       }
     }
     // Missing type
     attributesStr = "hostname,host1234";
     try {
       nodeAttributesProvider.parseAttributes(attributesStr);
-      Assert.fail("Expecting a parsing failure");
+      fail("Expecting a parsing failure");
     } catch (IOException e) {
-      Assert.assertNotNull(e);
-      Assert.assertTrue(e.getMessage().contains("Invalid value"));
+      assertNotNull(e);
+      assertTrue(e.getMessage().contains("Invalid value"));
     }
 
     // Extra prefix
     attributesStr = "prefix/hostname,STRING,host1234";
     try {
       nodeAttributesProvider.parseAttributes(attributesStr);
-      Assert.fail("Expecting a parsing failure");
+      fail("Expecting a parsing failure");
     } catch (IOException e) {
-      Assert.assertNotNull(e);
-      Assert.assertTrue(e.getMessage()
+      assertNotNull(e);
+      assertTrue(e.getMessage()
           .contains("should not contain any prefix."));
     }
 
@@ -250,11 +256,11 @@ public class TestConfigurationNodeAttributesProvider {
     attributesStr = "hostname,T,host1234";
     try {
       nodeAttributesProvider.parseAttributes(attributesStr);
-      Assert.fail("Expecting a parsing failure");
+      fail("Expecting a parsing failure");
     } catch (IOException e) {
       e.printStackTrace();
-      Assert.assertNotNull(e);
-      Assert.assertTrue(e.getMessage()
+      assertNotNull(e);
+      assertTrue(e.getMessage()
           .contains("Invalid node attribute type"));
     }
   }

+ 15 - 15
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestConfigurationNodeLabelsProvider.java

@@ -31,12 +31,14 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
 
@@ -53,7 +55,7 @@ public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
 
   private static ClassLoader classContextClassLoader;
 
-  @BeforeClass
+  @BeforeAll
   public static void create() {
     classContextClassLoader = Thread.currentThread().getContextClassLoader();
     loader =
@@ -63,12 +65,12 @@ public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
     Thread.currentThread().setContextClassLoader(loader);
   }
 
-  @Before
+  @BeforeEach
   public void setup() {
     nodeLabelsProvider = new ConfigurationNodeLabelsProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (nodeLabelsProvider != null) {
       nodeLabelsProvider.close();
@@ -76,7 +78,7 @@ public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
     }
   }
 
-  @AfterClass
+  @AfterAll
   public static void remove() throws Exception {
     if (classContextClassLoader != null) {
       // testcases will fail after testcases present in this class, as
@@ -118,10 +120,8 @@ public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
             .DISABLE_NODE_DESCRIPTORS_PROVIDER_FETCH_TIMER);
     nodeLabelsProvider.init(conf);
     nodeLabelsProvider.start();
-    Assert
-        .assertNull("Timer is not expected to be"
-                + " created when interval is configured as -1",
-            nodeLabelsProvider.getScheduler());
+    assertNull(nodeLabelsProvider.getScheduler(), "Timer is not expected to be"
+        + " created when interval is configured as -1");
     // Ensure that even though timer is not run, node labels
     // are fetched at least once so that NM registers/updates Labels with RM
     assertNLCollectionEquals(toNodeLabelSet("A"),
@@ -168,7 +168,7 @@ public class TestConfigurationNodeLabelsProvider extends NodeLabelTestBase {
           return nodeLabelsConfigFile.toURI().toURL();
         } catch (MalformedURLException e) {
           e.printStackTrace();
-          Assert.fail();
+          fail();
         }
       }
       return super.getResource(name);

+ 24 - 22
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestScriptBasedNodeAttributesProvider.java

@@ -26,10 +26,9 @@ import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.yarn.api.records.NodeAttribute;
 import org.apache.hadoop.yarn.api.records.NodeAttributeType;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -40,6 +39,9 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.concurrent.TimeoutException;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
 /**
  * Test cases for script based node attributes provider.
  */
@@ -54,13 +56,13 @@ public class TestScriptBasedNodeAttributesProvider {
 
   private ScriptBasedNodeAttributesProvider nodeAttributesProvider;
 
-  @Before
+  @BeforeEach
   public void setup() {
     testRootDir.mkdirs();
     nodeAttributesProvider = new ScriptBasedNodeAttributesProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (testRootDir.exists()) {
       FileContext.getLocalFSFileContext()
@@ -96,7 +98,7 @@ public class TestScriptBasedNodeAttributesProvider {
       pw.flush();
     } catch (Exception e) {
       e.printStackTrace();
-      Assert.fail();
+      fail();
     } finally {
       if (null != pw) {
         pw.close();
@@ -121,7 +123,7 @@ public class TestScriptBasedNodeAttributesProvider {
           () -> nodeAttributesProvider.getDescriptors().size() == 3,
           500, 3000);
     } catch (TimeoutException e) {
-      Assert.fail("Expecting node attributes size is 3, but got "
+      fail("Expecting node attributes size is 3, but got "
           + nodeAttributesProvider.getDescriptors().size());
     }
 
@@ -131,19 +133,19 @@ public class TestScriptBasedNodeAttributesProvider {
       NodeAttribute att = it.next();
       switch (att.getAttributeKey().getAttributeName()) {
       case "host":
-        Assert.assertEquals(NodeAttributeType.STRING, att.getAttributeType());
-        Assert.assertEquals("host1234", att.getAttributeValue());
+        assertEquals(NodeAttributeType.STRING, att.getAttributeType());
+        assertEquals("host1234", att.getAttributeValue());
         break;
       case "os":
-        Assert.assertEquals(NodeAttributeType.STRING, att.getAttributeType());
-        Assert.assertEquals("redhat_6_3", att.getAttributeValue());
+        assertEquals(NodeAttributeType.STRING, att.getAttributeType());
+        assertEquals("redhat_6_3", att.getAttributeValue());
         break;
       case "ip":
-        Assert.assertEquals(NodeAttributeType.STRING, att.getAttributeType());
-        Assert.assertEquals("10.0.0.1", att.getAttributeValue());
+        assertEquals(NodeAttributeType.STRING, att.getAttributeType());
+        assertEquals("10.0.0.1", att.getAttributeValue());
         break;
       default:
-        Assert.fail("Unexpected attribute name "
+        fail("Unexpected attribute name "
             + att.getAttributeKey().getAttributeName());
         break;
       }
@@ -164,10 +166,10 @@ public class TestScriptBasedNodeAttributesProvider {
       GenericTestUtils.waitFor(
           () -> nodeAttributesProvider.getDescriptors().size() == 1,
           500, 3000);
-      Assert.fail("This test should timeout because the provide is unable"
+      fail("This test should timeout because the provide is unable"
           + " to parse any attributes from the script output.");
     } catch (TimeoutException e) {
-      Assert.assertEquals(0, nodeAttributesProvider
+      assertEquals(0, nodeAttributesProvider
           .getDescriptors().size());
     }
   }
@@ -189,10 +191,10 @@ public class TestScriptBasedNodeAttributesProvider {
           .waitFor(() -> nodeAttributesProvider
                   .getDescriptors().size() == 1,
               500, 3000);
-      Assert.fail("This test should timeout because the provide is unable"
+      fail("This test should timeout because the provide is unable"
           + " to parse any attributes from the script output.");
     } catch (TimeoutException e) {
-      Assert.assertEquals(0, nodeAttributesProvider
+      assertEquals(0, nodeAttributesProvider
           .getDescriptors().size());
     }
   }
@@ -213,7 +215,7 @@ public class TestScriptBasedNodeAttributesProvider {
       Set<NodeAttribute> attributes =
           nodeAttributesProvider.getDescriptors();
       if (attributes != null) {
-        Assert.assertEquals(1, attributes.size());
+        assertEquals(1, attributes.size());
         resultSet.add(attributes.iterator().next().getAttributeValue());
         return resultSet.size() > 1;
       } else {
@@ -241,10 +243,10 @@ public class TestScriptBasedNodeAttributesProvider {
           .waitFor(() -> nodeAttributesProvider
                   .getDescriptors().size() == 3,
               500, 3000);
-      Assert.fail("This test should timeout because the provide is unable"
+      fail("This test should timeout because the provide is unable"
           + " to parse any attributes from the script output.");
     } catch (TimeoutException e) {
-      Assert.assertEquals(0, nodeAttributesProvider
+      assertEquals(0, nodeAttributesProvider
           .getDescriptors().size());
     }
   }

+ 24 - 21
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/nodelabels/TestScriptBasedNodeLabelsProvider.java

@@ -32,10 +32,15 @@ import org.apache.hadoop.service.ServiceStateException;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
 
@@ -48,13 +53,13 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
 
   private ScriptBasedNodeLabelsProvider nodeLabelsProvider;
 
-  @Before
+  @BeforeEach
   public void setup() {
     testRootDir.mkdirs();
     nodeLabelsProvider = new ScriptBasedNodeLabelsProvider();
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     if (testRootDir.exists()) {
       FileContext.getLocalFSFileContext()
@@ -88,7 +93,7 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
       pw.flush();
     } catch (Exception e) {
       e.printStackTrace();
-      Assert.fail();
+      fail();
     } finally {
       if (null != pw) {
         pw.close();
@@ -131,9 +136,9 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
     writeNodeLabelsScriptFile("", true);
     nodeLabelsProvider.init(getConfForNodeLabelScript());
     nodeLabelsProvider.start();
-    Assert
-        .assertNotNull("Node Label Script runner should be started when script"
-            + " is executable", nodeLabelsProvider.getTimerTask());
+    assertNotNull(nodeLabelsProvider.getTimerTask(),
+        "Node Label Script runner should be started when script"
+        + " is executable");
     nodeLabelsProvider.stop();
   }
 
@@ -141,10 +146,10 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
       ScriptBasedNodeLabelsProvider nodeLabelsProvider) {
     try {
       nodeLabelsProvider.init(new Configuration());
-      Assert.fail(message);
+      fail(message);
     } catch (ServiceStateException ex) {
-      Assert.assertEquals("IOException was expected", IOException.class,
-          ex.getCause().getClass());
+      assertEquals(IOException.class,
+          ex.getCause().getClass(), "IOException was expected");
     }
   }
 
@@ -159,9 +164,8 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
     writeNodeLabelsScriptFile(normalScript, true);
     nodeLabelsProvider.init(conf);
     nodeLabelsProvider.start();
-    Assert.assertNull(
-        "Timer is not expected to be created when interval is configured as -1",
-        nodeLabelsProvider.getScheduler());
+    assertNull(nodeLabelsProvider.getScheduler(),
+        "Timer is not expected to be created when interval is configured as -1");
     // Ensure that even though timer is not run script is run at least once so
     // that NM registers/updates Labels with RM
     assertNLCollectionEquals(toNodeLabelSet("X86"),
@@ -184,10 +188,9 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
     Thread.sleep(500l);
     TimerTask timerTask = nodeLabelsProvider.getTimerTask();
     timerTask.run();
-    Assert.assertNull(
+    assertNull(nodeLabelsProvider.getDescriptors(),
         "Node Label Script runner should return null when script doesnt "
-            + "give any Labels output",
-        nodeLabelsProvider.getDescriptors());
+        + "give any Labels output");
 
     writeNodeLabelsScriptFile(normalScript, true);
     timerTask.run();
@@ -205,7 +208,7 @@ public class TestScriptBasedNodeLabelsProvider extends NodeLabelTestBase {
     writeNodeLabelsScriptFile(timeOutScript, true);
     timerTask.run();
 
-    Assert.assertNotEquals("Node Labels should not be set after timeout ",
-        toNodeLabelSet("ALL"), nodeLabelsProvider.getDescriptors());
+    assertNotEquals(toNodeLabelSet("ALL"), nodeLabelsProvider.getDescriptors(),
+        "Node Labels should not be set after timeout ");
   }
 }

+ 30 - 30
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/recovery/TestNMLeveldbStateStoreService.java

@@ -20,12 +20,13 @@ package org.apache.hadoop.yarn.server.nodemanager.recovery;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.fusesource.leveldbjni.JniDBFactory.bytes;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.isNull;
 import static org.mockito.Mockito.mock;
@@ -98,10 +99,9 @@ import org.apache.hadoop.yarn.server.security.BaseNMTokenSecretManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.iq80.leveldb.DB;
 import org.iq80.leveldb.DBException;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 
 public class TestNMLeveldbStateStoreService {
@@ -113,7 +113,7 @@ public class TestNMLeveldbStateStoreService {
   YarnConfiguration conf;
   NMLeveldbStateStoreService stateStore;
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException {
     FileUtil.fullyDelete(TMP_DIR);
     conf = new YarnConfiguration();
@@ -122,7 +122,7 @@ public class TestNMLeveldbStateStoreService {
     restartStateStore();
   }
 
-  @After
+  @AfterEach
   public void cleanup() throws IOException {
     if (stateStore != null) {
       stateStore.close();
@@ -258,17 +258,17 @@ public class TestNMLeveldbStateStoreService {
   public void testCheckVersion() throws IOException {
     // default version
     Version defaultVersion = stateStore.getCurrentVersion();
-    Assert.assertEquals(defaultVersion, stateStore.loadVersion());
+    assertEquals(defaultVersion, stateStore.loadVersion());
 
     // compatible version
     Version compatibleVersion =
         Version.newInstance(defaultVersion.getMajorVersion(),
           defaultVersion.getMinorVersion() + 2);
     stateStore.storeVersion(compatibleVersion);
-    Assert.assertEquals(compatibleVersion, stateStore.loadVersion());
+    assertEquals(compatibleVersion, stateStore.loadVersion());
     restartStateStore();
     // overwrite the compatible version
-    Assert.assertEquals(defaultVersion, stateStore.loadVersion());
+    assertEquals(defaultVersion, stateStore.loadVersion());
 
     // incompatible version
     Version incompatibleVersion =
@@ -277,10 +277,10 @@ public class TestNMLeveldbStateStoreService {
     stateStore.storeVersion(incompatibleVersion);
     try {
       restartStateStore();
-      Assert.fail("Incompatible version, should expect fail here.");
+      fail("Incompatible version, should expect fail here.");
     } catch (ServiceStateException e) {
-      Assert.assertTrue("Exception message mismatch",
-        e.getMessage().contains("Incompatible version for NM state:"));
+      assertTrue(e.getMessage().contains("Incompatible version for NM state:"),
+          "Exception message mismatch");
     }
   }
 
@@ -591,8 +591,8 @@ public class TestNMLeveldbStateStoreService {
 
     // verify the container version key is not stored for new containers
     DB db = stateStore.getDB();
-    assertNull("version key present for new container", db.get(bytes(
-        stateStore.getContainerVersionKey(containerId.toString()))));
+    assertNull(db.get(bytes(stateStore.getContainerVersionKey(containerId.toString()))),
+        "version key present for new container");
 
     return new ContainerStateConstructParams()
         .setContainerRequest(containerReq)
@@ -1746,16 +1746,16 @@ public class TestNMLeveldbStateStoreService {
     RecoveredContainerState rcs = recoveredContainers.get(0);
     List<Serializable> resources = rcs.getResourceMappings()
         .getAssignedResources("gpu");
-    Assert.assertEquals(gpuRes1, resources);
-    Assert.assertEquals(gpuRes1, resourceMappings.getAssignedResources("gpu"));
+    assertEquals(gpuRes1, resources);
+    assertEquals(gpuRes1, resourceMappings.getAssignedResources("gpu"));
 
     resources = rcs.getResourceMappings().getAssignedResources("fpga");
-    Assert.assertEquals(fpgaRes, resources);
-    Assert.assertEquals(fpgaRes, resourceMappings.getAssignedResources("fpga"));
+    assertEquals(fpgaRes, resources);
+    assertEquals(fpgaRes, resourceMappings.getAssignedResources("fpga"));
 
     resources = rcs.getResourceMappings().getAssignedResources("numa");
-    Assert.assertEquals(numaRes, resources);
-    Assert.assertEquals(numaRes, resourceMappings.getAssignedResources("numa"));
+    assertEquals(numaRes, resources);
+    assertEquals(numaRes, resourceMappings.getAssignedResources("numa"));
     // test removing numa resources from state store
     stateStore.releaseAssignedResources(containerId, "numa");
     recoveredContainers = loadContainersState(stateStore.getContainerStateIterator());
@@ -1766,7 +1766,7 @@ public class TestNMLeveldbStateStoreService {
     try {
       stateStore.releaseAssignedResources(containerId, "numa");
     }catch (RuntimeException e){
-      Assert.fail("Should not throw exception while deleting non existing key from statestore");
+      fail("Should not throw exception while deleting non existing key from statestore");
     }
   }
 
@@ -1792,14 +1792,14 @@ public class TestNMLeveldbStateStoreService {
       // Cause should be wrapped DBException
       assertTrue(ioErr.getCause() instanceof DBException);
       // check the store is marked unhealthy
-      assertFalse("Statestore should have been unhealthy",
-          stateStore.isHealthy());
+      assertFalse(stateStore.isHealthy(),
+          "Statestore should have been unhealthy");
       return;
     } finally {
       // restore the working DB
       stateStore.setDB(keepDB);
     }
-    Assert.fail("Expected exception not thrown");
+    fail("Expected exception not thrown");
   }
 
   @Test

+ 33 - 29
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/scheduler/TestDistributedScheduler.java

@@ -48,9 +48,7 @@ import org.apache.hadoop.yarn.server.scheduler.DistributedOpportunisticContainer
 import org.apache.hadoop.yarn.server.scheduler.OpportunisticContainerAllocator;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.util.Records;
-import org.junit.Assert;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -62,6 +60,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
 /**
  * Test cases for {@link DistributedScheduler}.
  */
@@ -82,9 +86,9 @@ public class TestDistributedScheduler {
         RemoteNode.newInstance(NodeId.newInstance("d", 4), "http://d:4")));
 
     final AtomicBoolean flipFlag = new AtomicBoolean(true);
-    Mockito.when(
+    when(
         finalReqIntcptr.allocateForDistributedScheduling(
-            Mockito.any(DistributedSchedulingAllocateRequest.class)))
+           any(DistributedSchedulingAllocateRequest.class)))
         .thenAnswer(new Answer<DistributedSchedulingAllocateResponse>() {
           @Override
           public DistributedSchedulingAllocateResponse answer(
@@ -126,18 +130,18 @@ public class TestDistributedScheduler {
     // Verify 4 containers were allocated
     AllocateResponse allocateResponse =
         distributedScheduler.allocate(allocateRequest);
-    Assert.assertEquals(4, allocateResponse.getAllocatedContainers().size());
+    assertEquals(4, allocateResponse.getAllocatedContainers().size());
 
     // Verify equal distribution on hosts a, b, c and d, and none on e / f
     // NOTE: No more than 1 container will be allocated on a node in the
     //       top k list per allocate call.
     Map<NodeId, List<ContainerId>> allocs = mapAllocs(allocateResponse, 4);
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("a", 1)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("b", 2)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("d", 4)).size());
-    Assert.assertNull(allocs.get(NodeId.newInstance("e", 5)));
-    Assert.assertNull(allocs.get(NodeId.newInstance("f", 6)));
+    assertEquals(1, allocs.get(NodeId.newInstance("a", 1)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("b", 2)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("d", 4)).size());
+    assertNull(allocs.get(NodeId.newInstance("e", 5)));
+    assertNull(allocs.get(NodeId.newInstance("f", 6)));
 
     // New Allocate request
     allocateRequest = Records.newRecord(AllocateRequest.class);
@@ -147,17 +151,17 @@ public class TestDistributedScheduler {
 
     // Verify 4 containers were allocated
     allocateResponse = distributedScheduler.allocate(allocateRequest);
-    Assert.assertEquals(4, allocateResponse.getAllocatedContainers().size());
+    assertEquals(4, allocateResponse.getAllocatedContainers().size());
 
     // Verify new containers are equally distribution on hosts c and d,
     // and none on a or b
     allocs = mapAllocs(allocateResponse, 4);
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("d", 4)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("e", 5)).size());
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("f", 6)).size());
-    Assert.assertNull(allocs.get(NodeId.newInstance("a", 1)));
-    Assert.assertNull(allocs.get(NodeId.newInstance("b", 2)));
+    assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("d", 4)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("e", 5)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("f", 6)).size());
+    assertNull(allocs.get(NodeId.newInstance("a", 1)));
+    assertNull(allocs.get(NodeId.newInstance("b", 2)));
 
     // Ensure the DistributedScheduler respects the list order..
     // The first request should be allocated to "c" since it is ranked higher
@@ -169,7 +173,7 @@ public class TestDistributedScheduler {
     allocateRequest.setAskList(Arrays.asList(guaranteedReq, opportunisticReq));
     allocateResponse = distributedScheduler.allocate(allocateRequest);
     allocs = mapAllocs(allocateResponse, 1);
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
 
     allocateRequest = Records.newRecord(AllocateRequest.class);
     opportunisticReq =
@@ -177,7 +181,7 @@ public class TestDistributedScheduler {
     allocateRequest.setAskList(Arrays.asList(guaranteedReq, opportunisticReq));
     allocateResponse = distributedScheduler.allocate(allocateRequest);
     allocs = mapAllocs(allocateResponse, 1);
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("f", 6)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("f", 6)).size());
 
     allocateRequest = Records.newRecord(AllocateRequest.class);
     opportunisticReq =
@@ -185,7 +189,7 @@ public class TestDistributedScheduler {
     allocateRequest.setAskList(Arrays.asList(guaranteedReq, opportunisticReq));
     allocateResponse = distributedScheduler.allocate(allocateRequest);
     allocs = mapAllocs(allocateResponse, 1);
-    Assert.assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
+    assertEquals(1, allocs.get(NodeId.newInstance("c", 3)).size());
   }
 
   private void registerAM(DistributedScheduler distributedScheduler,
@@ -202,9 +206,9 @@ public class TestDistributedScheduler {
     distSchedRegisterResponse.setMinContainerResource(
         Resource.newInstance(512, 2));
     distSchedRegisterResponse.setNodesForScheduling(nodeList);
-    Mockito.when(
+    when(
         finalReqIntcptr.registerApplicationMasterForDistributedScheduling(
-            Mockito.any(RegisterApplicationMasterRequest.class)))
+            any(RegisterApplicationMasterRequest.class)))
         .thenReturn(distSchedRegisterResponse);
 
     distributedScheduler.registerApplicationMaster(
@@ -213,8 +217,8 @@ public class TestDistributedScheduler {
 
   private RequestInterceptor setup(Configuration conf,
       DistributedScheduler distributedScheduler) {
-    NodeStatusUpdater nodeStatusUpdater = Mockito.mock(NodeStatusUpdater.class);
-    Mockito.when(nodeStatusUpdater.getRMIdentifier()).thenReturn(12345l);
+    NodeStatusUpdater nodeStatusUpdater = mock(NodeStatusUpdater.class);
+    when(nodeStatusUpdater.getRMIdentifier()).thenReturn(12345L);
     NMContainerTokenSecretManager nmContainerTokenSecretManager = new
         NMContainerTokenSecretManager(conf);
     MasterKey mKey = new MasterKey() {
@@ -243,7 +247,7 @@ public class TestDistributedScheduler {
         ApplicationAttemptId.newInstance(ApplicationId.newInstance(1, 1), 1),
         containerAllocator, nmTokenSecretManagerInNM, "test");
 
-    RequestInterceptor finalReqIntcptr = Mockito.mock(RequestInterceptor.class);
+    RequestInterceptor finalReqIntcptr = mock(RequestInterceptor.class);
     distributedScheduler.setNextInterceptor(finalReqIntcptr);
     return finalReqIntcptr;
   }
@@ -273,13 +277,13 @@ public class TestDistributedScheduler {
 
   private Map<NodeId, List<ContainerId>> mapAllocs(
       AllocateResponse allocateResponse, int expectedSize) throws Exception {
-    Assert.assertEquals(expectedSize,
+    assertEquals(expectedSize,
         allocateResponse.getAllocatedContainers().size());
     Map<NodeId, List<ContainerId>> allocs = new HashMap<>();
     for (Container c : allocateResponse.getAllocatedContainers()) {
       ContainerTokenIdentifier cTokId = BuilderUtils
           .newContainerTokenIdentifier(c.getContainerToken());
-      Assert.assertEquals(
+      assertEquals(
           c.getNodeId().getHost() + ":" + c.getNodeId().getPort(),
           cTokId.getNmHostAddress());
       List<ContainerId> cIds = allocs.get(c.getNodeId());

+ 6 - 6
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/security/TestNMContainerTokenSecretManager.java

@@ -18,11 +18,11 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.security;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.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.IOException;
 
@@ -39,7 +39,7 @@ import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreServ
 import org.apache.hadoop.yarn.server.security.BaseContainerTokenSecretManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestNMContainerTokenSecretManager {
 

+ 6 - 6
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/security/TestNMTokenSecretManagerInNM.java

@@ -18,11 +18,11 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.security;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.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.IOException;
 
@@ -38,7 +38,7 @@ import org.apache.hadoop.yarn.server.api.records.MasterKey;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
 import org.apache.hadoop.yarn.server.security.BaseNMTokenSecretManager;
 import org.apache.hadoop.yarn.util.ConverterUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestNMTokenSecretManagerInNM {
 

+ 50 - 47
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.java

@@ -18,8 +18,10 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.timelineservice;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -56,10 +58,9 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Cont
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResumeEvent;
 import org.apache.hadoop.yarn.util.ResourceCalculatorProcessTree;
 import org.apache.hadoop.yarn.util.TimelineServiceHelper;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
 
 public class TestNMTimelinePublisher {
   private static final String MEMORY_ID = "MEMORY";
@@ -71,7 +72,8 @@ public class TestNMTimelinePublisher {
   private DrainDispatcher dispatcher;
 
 
-  @Before public void setup() throws Exception {
+  @BeforeEach
+  public void setup() throws Exception {
     conf = new Configuration();
     conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
     conf.setFloat(YarnConfiguration.TIMELINE_SERVICE_VERSION, 2.0f);
@@ -119,7 +121,8 @@ public class TestNMTimelinePublisher {
     return context;
   }
 
-  @After public void tearDown() throws Exception {
+  @AfterEach
+  public void tearDown() throws Exception {
     if (publisher != null) {
       publisher.stop();
     }
@@ -155,15 +158,15 @@ public class TestNMTimelinePublisher {
     TimelineEntity[] lastPublishedEntities =
         timelineClient.getLastPublishedEntities();
 
-    Assert.assertNotNull(lastPublishedEntities);
-    Assert.assertEquals(1, lastPublishedEntities.length);
+    assertNotNull(lastPublishedEntities);
+    assertEquals(1, lastPublishedEntities.length);
     TimelineEntity entity = lastPublishedEntities[0];
-    Assert.assertTrue(cEntity.equals(entity));
-    Assert.assertEquals(diag,
+    assertTrue(cEntity.equals(entity));
+    assertEquals(diag,
         entity.getInfo().get(ContainerMetricsConstants.DIAGNOSTICS_INFO));
-    Assert.assertEquals(exitStatus,
+    assertEquals(exitStatus,
         entity.getInfo().get(ContainerMetricsConstants.EXIT_STATUS_INFO));
-    Assert.assertEquals(TimelineServiceHelper.invertLong(
+    assertEquals(TimelineServiceHelper.invertLong(
         cId.getContainerId()), entity.getIdPrefix());
   }
 
@@ -187,20 +190,20 @@ public class TestNMTimelinePublisher {
     TimelineEntity[] lastPublishedEntities =
         timelineClient.getLastPublishedEntities();
 
-    Assert.assertNotNull(lastPublishedEntities);
-    Assert.assertEquals(1, lastPublishedEntities.length);
+    assertNotNull(lastPublishedEntities);
+    assertEquals(1, lastPublishedEntities.length);
     TimelineEntity entity = lastPublishedEntities[0];
-    Assert.assertEquals(cEntity, entity);
+    assertEquals(cEntity, entity);
 
     NavigableSet<TimelineEvent> events = entity.getEvents();
-    Assert.assertEquals(1, events.size());
-    Assert.assertEquals(ContainerMetricsConstants.PAUSED_EVENT_TYPE,
+    assertEquals(1, events.size());
+    assertEquals(ContainerMetricsConstants.PAUSED_EVENT_TYPE,
         events.iterator().next().getId());
 
     Map<String, Object> info = entity.getInfo();
-    Assert.assertTrue(
+    assertTrue(
         info.containsKey(ContainerMetricsConstants.DIAGNOSTICS_INFO));
-    Assert.assertEquals("test pause",
+    assertEquals("test pause",
         info.get(ContainerMetricsConstants.DIAGNOSTICS_INFO));
   }
 
@@ -224,20 +227,20 @@ public class TestNMTimelinePublisher {
     TimelineEntity[] lastPublishedEntities =
         timelineClient.getLastPublishedEntities();
 
-    Assert.assertNotNull(lastPublishedEntities);
-    Assert.assertEquals(1, lastPublishedEntities.length);
+    assertNotNull(lastPublishedEntities);
+    assertEquals(1, lastPublishedEntities.length);
     TimelineEntity entity = lastPublishedEntities[0];
-    Assert.assertEquals(cEntity, entity);
+    assertEquals(cEntity, entity);
 
     NavigableSet<TimelineEvent> events = entity.getEvents();
-    Assert.assertEquals(1, events.size());
-    Assert.assertEquals(ContainerMetricsConstants.RESUMED_EVENT_TYPE,
+    assertEquals(1, events.size());
+    assertEquals(ContainerMetricsConstants.RESUMED_EVENT_TYPE,
         events.iterator().next().getId());
 
     Map<String, Object> info = entity.getInfo();
-    Assert.assertTrue(
+    assertTrue(
         info.containsKey(ContainerMetricsConstants.DIAGNOSTICS_INFO));
-    Assert.assertEquals("test resume",
+    assertEquals("test resume",
         info.get(ContainerMetricsConstants.DIAGNOSTICS_INFO));
   }
 
@@ -261,24 +264,24 @@ public class TestNMTimelinePublisher {
     TimelineEntity[] lastPublishedEntities =
         timelineClient.getLastPublishedEntities();
 
-    Assert.assertNotNull(lastPublishedEntities);
-    Assert.assertEquals(1, lastPublishedEntities.length);
+    assertNotNull(lastPublishedEntities);
+    assertEquals(1, lastPublishedEntities.length);
     TimelineEntity entity = lastPublishedEntities[0];
-    Assert.assertEquals(cEntity, entity);
+    assertEquals(cEntity, entity);
 
     NavigableSet<TimelineEvent> events = entity.getEvents();
-    Assert.assertEquals(1, events.size());
-    Assert.assertEquals(ContainerMetricsConstants.KILLED_EVENT_TYPE,
+    assertEquals(1, events.size());
+    assertEquals(ContainerMetricsConstants.KILLED_EVENT_TYPE,
         events.iterator().next().getId());
 
     Map<String, Object> info = entity.getInfo();
-    Assert.assertTrue(
+    assertTrue(
         info.containsKey(ContainerMetricsConstants.DIAGNOSTICS_INFO));
-    Assert.assertEquals("test kill",
+    assertEquals("test kill",
         info.get(ContainerMetricsConstants.DIAGNOSTICS_INFO));
-    Assert.assertTrue(
+    assertTrue(
         info.containsKey(ContainerMetricsConstants.EXIT_STATUS_INFO));
-    Assert.assertEquals(1,
+    assertEquals(1,
         info.get(ContainerMetricsConstants.EXIT_STATUS_INFO));
   }
 
@@ -327,9 +330,9 @@ public class TestNMTimelinePublisher {
         (memoryUsage == ResourceCalculatorProcessTree.UNAVAILABLE) ? 0 : 1;
     numberOfResourceMetrics +=
         (cpuUsage == ResourceCalculatorProcessTree.UNAVAILABLE) ? 0 : 1;
-    assertNotNull("entities are expected to be published", entities);
-    assertEquals("Expected number of metrics notpublished",
-        numberOfResourceMetrics, entities[0].getMetrics().size());
+    assertNotNull(entities, "entities are expected to be published");
+    assertEquals(numberOfResourceMetrics, entities[0].getMetrics().size(),
+        "Expected number of metrics notpublished");
     assertEquals(idPrefix, entities[0].getIdPrefix());
     Iterator<TimelineMetric> metrics = entities[0].getMetrics().iterator();
     while (metrics.hasNext()) {
@@ -338,22 +341,22 @@ public class TestNMTimelinePublisher {
       switch (metric.getId()) {
       case CPU_ID:
         if (cpuUsage == ResourceCalculatorProcessTree.UNAVAILABLE) {
-          Assert.fail("Not Expecting CPU Metric to be published");
+          fail("Not Expecting CPU Metric to be published");
         }
         entrySet = metric.getValues().entrySet().iterator();
-        assertEquals("CPU usage metric not matching", cpuUsage,
-            entrySet.next().getValue());
+        assertEquals(cpuUsage, entrySet.next().getValue(),
+            "CPU usage metric not matching");
         break;
       case MEMORY_ID:
         if (memoryUsage == ResourceCalculatorProcessTree.UNAVAILABLE) {
-          Assert.fail("Not Expecting Memory Metric to be published");
+          fail("Not Expecting Memory Metric to be published");
         }
         entrySet = metric.getValues().entrySet().iterator();
-        assertEquals("Memory usage metric not matching", memoryUsage,
-            entrySet.next().getValue());
+        assertEquals(memoryUsage, entrySet.next().getValue(),
+            "Memory usage metric not matching");
         break;
       default:
-        Assert.fail("Invalid Resource Usage metric");
+        fail("Invalid Resource Usage metric");
         break;
       }
     }

+ 69 - 63
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestCgroupsLCEResourcesHandler.java

@@ -25,12 +25,10 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resource
 
 import org.apache.hadoop.yarn.util.ControlledClock;
 import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin;
-import org.junit.Assert;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.junit.Test;
-import org.junit.After;
-import org.junit.Before;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
 
 import java.io.*;
 import java.util.Collections;
@@ -41,13 +39,21 @@ import java.util.Scanner;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 
+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 static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
 @Deprecated
 public class TestCgroupsLCEResourcesHandler {
   private static File cgroupDir = null;
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
     cgroupDir =
         new File(System.getProperty("test.build.data",
@@ -56,7 +62,7 @@ public class TestCgroupsLCEResourcesHandler {
     FileUtils.deleteQuietly(cgroupDir);
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws Exception {
     FileUtils.deleteQuietly(cgroupDir);
   }
@@ -70,22 +76,22 @@ public class TestCgroupsLCEResourcesHandler {
     FileUtils.deleteQuietly(cgroupDir);
     // Test 0
     // tasks file not present, should return false
-    Assert.assertFalse(handler.checkAndDeleteCgroup(cgroupDir));
+    assertFalse(handler.checkAndDeleteCgroup(cgroupDir));
 
     File tfile = new File(cgroupDir.getAbsolutePath(), "tasks");
     FileOutputStream fos = FileUtils.openOutputStream(tfile);
-    File fspy = Mockito.spy(cgroupDir);
+    File fspy = spy(cgroupDir);
 
     // Test 1, tasks file is empty
     // tasks file has no data, should return true
-    Mockito.when(fspy.delete()).thenReturn(true);
-    Assert.assertTrue(handler.checkAndDeleteCgroup(fspy));
+    when(fspy.delete()).thenReturn(true);
+    assertTrue(handler.checkAndDeleteCgroup(fspy));
 
     // Test 2, tasks file has data
     fos.write("1234".getBytes());
     fos.close();
     // tasks has data, would not be able to delete, should return false
-    Assert.assertFalse(handler.checkAndDeleteCgroup(fspy));
+    assertFalse(handler.checkAndDeleteCgroup(fspy));
     FileUtils.deleteQuietly(cgroupDir);
 
   }
@@ -122,7 +128,7 @@ public class TestCgroupsLCEResourcesHandler {
       }
     }.start();
     latch.await();
-    Assert.assertFalse(handler.deleteCgroup(cgroupDir.getAbsolutePath()));
+    assertFalse(handler.deleteCgroup(cgroupDir.getAbsolutePath()));
     FileUtils.deleteQuietly(cgroupDir);
   }
 
@@ -181,9 +187,9 @@ public class TestCgroupsLCEResourcesHandler {
     YarnConfiguration conf = new YarnConfiguration();
     final int numProcessors = 4;
     ResourceCalculatorPlugin plugin =
-        Mockito.mock(ResourceCalculatorPlugin.class);
-    Mockito.doReturn(numProcessors).when(plugin).getNumProcessors();
-    Mockito.doReturn(numProcessors).when(plugin).getNumCores();
+        mock(ResourceCalculatorPlugin.class);
+    doReturn(numProcessors).when(plugin).getNumProcessors();
+    doReturn(numProcessors).when(plugin).getNumCores();
     handler.setConf(conf);
     handler.initConfig();
 
@@ -204,8 +210,8 @@ public class TestCgroupsLCEResourcesHandler {
     handler.init(mockLCE, plugin);
     File periodFile = new File(cpuCgroupMountDir, "cpu.cfs_period_us");
     File quotaFile = new File(cpuCgroupMountDir, "cpu.cfs_quota_us");
-    Assert.assertFalse(periodFile.exists());
-    Assert.assertFalse(quotaFile.exists());
+    assertFalse(periodFile.exists());
+    assertFalse(quotaFile.exists());
 
     // subset of cpu being used, files should be created
     conf
@@ -215,8 +221,8 @@ public class TestCgroupsLCEResourcesHandler {
     handler.init(mockLCE, plugin);
     int period = readIntFromFile(periodFile);
     int quota = readIntFromFile(quotaFile);
-    Assert.assertEquals(100 * 1000, period);
-    Assert.assertEquals(1000 * 1000, quota);
+    assertEquals(100 * 1000, period);
+    assertEquals(1000 * 1000, quota);
 
     // set cpu back to 100, quota should be -1
     conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
@@ -225,7 +231,7 @@ public class TestCgroupsLCEResourcesHandler {
     handler.limits[1] = 1000 * 1000;
     handler.init(mockLCE, plugin);
     quota = readIntFromFile(quotaFile);
-    Assert.assertEquals(-1, quota);
+    assertEquals(-1, quota);
 
     FileUtils.deleteQuietly(cgroupDir);
   }
@@ -246,18 +252,18 @@ public class TestCgroupsLCEResourcesHandler {
     CgroupsLCEResourcesHandler handler = new CgroupsLCEResourcesHandler();
 
     int[] ret = handler.getOverallLimits(2);
-    Assert.assertEquals(expectedQuota / 2, ret[0]);
-    Assert.assertEquals(expectedQuota, ret[1]);
+    assertEquals(expectedQuota / 2, ret[0]);
+    assertEquals(expectedQuota, ret[1]);
 
     ret = handler.getOverallLimits(2000);
-    Assert.assertEquals(expectedQuota, ret[0]);
-    Assert.assertEquals(-1, ret[1]);
+    assertEquals(expectedQuota, ret[0]);
+    assertEquals(-1, ret[1]);
 
     int[] params = {0, -1};
     for (int cores : params) {
       try {
         handler.getOverallLimits(cores);
-        Assert.fail("Function call should throw error.");
+        fail("Function call should throw error.");
       } catch (IllegalArgumentException ie) {
         // expected
       }
@@ -265,8 +271,8 @@ public class TestCgroupsLCEResourcesHandler {
 
     // test minimums
     ret = handler.getOverallLimits(1000 * 1000);
-    Assert.assertEquals(1000 * 1000, ret[0]);
-    Assert.assertEquals(-1, ret[1]);
+    assertEquals(1000 * 1000, ret[0]);
+    assertEquals(-1, ret[1]);
   }
 
   @Test
@@ -279,9 +285,9 @@ public class TestCgroupsLCEResourcesHandler {
     conf.setBoolean(YarnConfiguration.NM_DISK_RESOURCE_ENABLED, true);
     final int numProcessors = 4;
     ResourceCalculatorPlugin plugin =
-        Mockito.mock(ResourceCalculatorPlugin.class);
-    Mockito.doReturn(numProcessors).when(plugin).getNumProcessors();
-    Mockito.doReturn(numProcessors).when(plugin).getNumCores();
+        mock(ResourceCalculatorPlugin.class);
+    doReturn(numProcessors).when(plugin).getNumProcessors();
+    doReturn(numProcessors).when(plugin).getNumCores();
     handler.setConf(conf);
     handler.initConfig();
 
@@ -300,16 +306,16 @@ public class TestCgroupsLCEResourcesHandler {
     // check the controller paths map isn't empty
     ContainerId id = ContainerId.fromString("container_1_1_1_1");
     handler.preExecute(id, Resource.newInstance(1024, 1));
-    Assert.assertNotNull(handler.getControllerPaths());
+    assertNotNull(handler.getControllerPaths());
     // check values
     // default case - files shouldn't exist, strict mode off by default
     File containerCpuDir = new File(cpuCgroupMountDir, id.toString());
-    Assert.assertTrue(containerCpuDir.exists());
-    Assert.assertTrue(containerCpuDir.isDirectory());
+    assertTrue(containerCpuDir.exists());
+    assertTrue(containerCpuDir.isDirectory());
     File periodFile = new File(containerCpuDir, "cpu.cfs_period_us");
     File quotaFile = new File(containerCpuDir, "cpu.cfs_quota_us");
-    Assert.assertFalse(periodFile.exists());
-    Assert.assertFalse(quotaFile.exists());
+    assertFalse(periodFile.exists());
+    assertFalse(quotaFile.exists());
 
     // no files created because we're using all cpu
     FileUtils.deleteQuietly(containerCpuDir);
@@ -319,12 +325,12 @@ public class TestCgroupsLCEResourcesHandler {
     handler.initConfig();
     handler.preExecute(id,
         Resource.newInstance(1024, YarnConfiguration.DEFAULT_NM_VCORES));
-    Assert.assertTrue(containerCpuDir.exists());
-    Assert.assertTrue(containerCpuDir.isDirectory());
+    assertTrue(containerCpuDir.exists());
+    assertTrue(containerCpuDir.isDirectory());
     periodFile = new File(containerCpuDir, "cpu.cfs_period_us");
     quotaFile = new File(containerCpuDir, "cpu.cfs_quota_us");
-    Assert.assertFalse(periodFile.exists());
-    Assert.assertFalse(quotaFile.exists());
+    assertFalse(periodFile.exists());
+    assertFalse(quotaFile.exists());
 
     // 50% of CPU
     FileUtils.deleteQuietly(containerCpuDir);
@@ -334,14 +340,14 @@ public class TestCgroupsLCEResourcesHandler {
     handler.initConfig();
     handler.preExecute(id,
         Resource.newInstance(1024, YarnConfiguration.DEFAULT_NM_VCORES / 2));
-    Assert.assertTrue(containerCpuDir.exists());
-    Assert.assertTrue(containerCpuDir.isDirectory());
+    assertTrue(containerCpuDir.exists());
+    assertTrue(containerCpuDir.isDirectory());
     periodFile = new File(containerCpuDir, "cpu.cfs_period_us");
     quotaFile = new File(containerCpuDir, "cpu.cfs_quota_us");
-    Assert.assertTrue(periodFile.exists());
-    Assert.assertTrue(quotaFile.exists());
-    Assert.assertEquals(500 * 1000, readIntFromFile(periodFile));
-    Assert.assertEquals(1000 * 1000, readIntFromFile(quotaFile));
+    assertTrue(periodFile.exists());
+    assertTrue(quotaFile.exists());
+    assertEquals(500 * 1000, readIntFromFile(periodFile));
+    assertEquals(1000 * 1000, readIntFromFile(quotaFile));
 
     // CGroups set to 50% of CPU, container set to 50% of YARN CPU
     FileUtils.deleteQuietly(containerCpuDir);
@@ -354,14 +360,14 @@ public class TestCgroupsLCEResourcesHandler {
     handler.init(mockLCE, plugin);
     handler.preExecute(id,
         Resource.newInstance(1024, YarnConfiguration.DEFAULT_NM_VCORES / 2));
-    Assert.assertTrue(containerCpuDir.exists());
-    Assert.assertTrue(containerCpuDir.isDirectory());
+    assertTrue(containerCpuDir.exists());
+    assertTrue(containerCpuDir.isDirectory());
     periodFile = new File(containerCpuDir, "cpu.cfs_period_us");
     quotaFile = new File(containerCpuDir, "cpu.cfs_quota_us");
-    Assert.assertTrue(periodFile.exists());
-    Assert.assertTrue(quotaFile.exists());
-    Assert.assertEquals(1000 * 1000, readIntFromFile(periodFile));
-    Assert.assertEquals(1000 * 1000, readIntFromFile(quotaFile));
+    assertTrue(periodFile.exists());
+    assertTrue(quotaFile.exists());
+    assertEquals(1000 * 1000, readIntFromFile(periodFile));
+    assertEquals(1000 * 1000, readIntFromFile(quotaFile));
 
     FileUtils.deleteQuietly(cgroupDir);
   }
@@ -375,9 +381,9 @@ public class TestCgroupsLCEResourcesHandler {
       CgroupsLCEResourcesHandler handler = new CgroupsLCEResourcesHandler();
       Map<String, Set<String>> cgroups = new LinkedHashMap<>();
 
-      Assert.assertTrue("temp dir should be created", cpu.mkdirs());
-      Assert.assertTrue("temp dir should be created", memory.mkdirs());
-      Assert.assertFalse("temp dir should not be created", cpuNoExist.exists());
+      assertTrue(cpu.mkdirs(), "temp dir should be created");
+      assertTrue(memory.mkdirs(), "temp dir should be created");
+      assertFalse(cpuNoExist.exists(), "temp dir should not be created");
 
       cgroups.put(
           memory.getAbsolutePath(), Collections.singleton("memory"));
@@ -385,8 +391,8 @@ public class TestCgroupsLCEResourcesHandler {
           cpuNoExist.getAbsolutePath(), Collections.singleton("cpu"));
       cgroups.put(cpu.getAbsolutePath(), Collections.singleton("cpu"));
       String selectedCPU = handler.findControllerInMtab("cpu", cgroups);
-      Assert.assertEquals("Wrong CPU mount point selected",
-          cpu.getAbsolutePath(), selectedCPU);
+      assertEquals(cpu.getAbsolutePath(), selectedCPU,
+          "Wrong CPU mount point selected");
     } finally {
       FileUtils.deleteQuietly(cpu);
       FileUtils.deleteQuietly(memory);
@@ -403,18 +409,18 @@ public class TestCgroupsLCEResourcesHandler {
     File cpu = new File(new File(cgroupDir, "cpuacct,cpu"), "/hadoop-yarn");
 
     try {
-      Assert.assertTrue("temp dir should be created", cpu.mkdirs());
+      assertTrue(cpu.mkdirs(), "temp dir should be created");
 
       final int numProcessors = 4;
       ResourceCalculatorPlugin plugin =
-              Mockito.mock(ResourceCalculatorPlugin.class);
-      Mockito.doReturn(numProcessors).when(plugin).getNumProcessors();
-      Mockito.doReturn(numProcessors).when(plugin).getNumCores();
+              mock(ResourceCalculatorPlugin.class);
+      doReturn(numProcessors).when(plugin).getNumProcessors();
+      doReturn(numProcessors).when(plugin).getNumCores();
       when(plugin.getNumProcessors()).thenReturn(8);
       handler.init(null, plugin);
 
-      Assert.assertEquals("CPU CGRoup path was not set", cpu.getParent(),
-          handler.getControllerPaths().get("cpu"));
+      assertEquals(cpu.getParent(), handler.getControllerPaths().get("cpu"),
+          "CPU CGRoup path was not set");
 
     } finally {
       FileUtils.deleteQuietly(cpu);

+ 27 - 23
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestNodeManagerHardwareUtils.java

@@ -20,9 +20,13 @@ package org.apache.hadoop.yarn.server.nodemanager.util;
 
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin;
-import org.junit.Assert;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
 
 /**
  * Test the various functions provided by the NodeManagerHardwareUtils class.
@@ -91,44 +95,44 @@ public class TestNodeManagerHardwareUtils {
     final int numProcessors = 8;
     final int numCores = 4;
     ResourceCalculatorPlugin plugin =
-        Mockito.mock(ResourceCalculatorPlugin.class);
-    Mockito.doReturn(numProcessors).when(plugin).getNumProcessors();
-    Mockito.doReturn(numCores).when(plugin).getNumCores();
+        mock(ResourceCalculatorPlugin.class);
+    doReturn(numProcessors).when(plugin).getNumProcessors();
+    doReturn(numCores).when(plugin).getNumCores();
 
     conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, 0);
     boolean catchFlag = false;
     try {
       NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-      Assert.fail("getContainerCores should have thrown exception");
+      fail("getContainerCores should have thrown exception");
     } catch (IllegalArgumentException ie) {
       catchFlag = true;
     }
-    Assert.assertTrue(catchFlag);
+    assertTrue(catchFlag);
 
     conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
         100);
     ret = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-    Assert.assertEquals(4, (int) ret);
+    assertEquals(4, (int) ret);
 
     conf
       .setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, 50);
     ret = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-    Assert.assertEquals(2, (int) ret);
+    assertEquals(2, (int) ret);
 
     conf
       .setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, 75);
     ret = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-    Assert.assertEquals(3, (int) ret);
+    assertEquals(3, (int) ret);
 
     conf
       .setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, 85);
     ret = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-    Assert.assertEquals(3.4, ret, 0.1);
+    assertEquals(3.4, ret, 0.1);
 
     conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
         110);
     ret = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf);
-    Assert.assertEquals(4, (int) ret);
+    assertEquals(4, (int) ret);
   }
 
   @Test
@@ -140,28 +144,28 @@ public class TestNodeManagerHardwareUtils {
     conf.setFloat(YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER, 1.25f);
 
     int ret = NodeManagerHardwareUtils.getVCores(plugin, conf);
-    Assert.assertEquals(YarnConfiguration.DEFAULT_NM_VCORES, ret);
+    assertEquals(YarnConfiguration.DEFAULT_NM_VCORES, ret);
 
     conf.setBoolean(YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION,
         true);
     ret = NodeManagerHardwareUtils.getVCores(plugin, conf);
-    Assert.assertEquals(5, ret);
+    assertEquals(5, ret);
 
     conf.setBoolean(YarnConfiguration.NM_COUNT_LOGICAL_PROCESSORS_AS_CORES,
         true);
     ret = NodeManagerHardwareUtils.getVCores(plugin, conf);
-    Assert.assertEquals(10, ret);
+    assertEquals(10, ret);
 
     conf.setInt(YarnConfiguration.NM_VCORES, 10);
     ret = NodeManagerHardwareUtils.getVCores(plugin, conf);
-    Assert.assertEquals(10, ret);
+    assertEquals(10, ret);
 
     YarnConfiguration conf1 = new YarnConfiguration();
     conf1.setBoolean(YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION,
         false);
     conf.setInt(YarnConfiguration.NM_VCORES, 10);
     ret = NodeManagerHardwareUtils.getVCores(plugin, conf);
-    Assert.assertEquals(10, ret);
+    assertEquals(10, ret);
   }
 
   @Test
@@ -173,26 +177,26 @@ public class TestNodeManagerHardwareUtils {
     conf.setBoolean(YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION,
         true);
     long mem = NodeManagerHardwareUtils.getContainerMemoryMB(null, conf);
-    Assert.assertEquals(YarnConfiguration.DEFAULT_NM_PMEM_MB, mem);
+    assertEquals(YarnConfiguration.DEFAULT_NM_PMEM_MB, mem);
 
     mem = NodeManagerHardwareUtils.getContainerMemoryMB(plugin, conf);
     int hadoopHeapSizeMB =
         (int) (Runtime.getRuntime().maxMemory() / (1024 * 1024));
     int calculatedMemMB =
         (int) (0.8 * (physicalMemMB - (2 * hadoopHeapSizeMB)));
-    Assert.assertEquals(calculatedMemMB, mem);
+    assertEquals(calculatedMemMB, mem);
 
     conf.setInt(YarnConfiguration.NM_PMEM_MB, 1024);
     mem = NodeManagerHardwareUtils.getContainerMemoryMB(conf);
-    Assert.assertEquals(1024, mem);
+    assertEquals(1024, mem);
 
     conf = new YarnConfiguration();
     conf.setBoolean(YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION,
         false);
     mem = NodeManagerHardwareUtils.getContainerMemoryMB(conf);
-    Assert.assertEquals(YarnConfiguration.DEFAULT_NM_PMEM_MB, mem);
+    assertEquals(YarnConfiguration.DEFAULT_NM_PMEM_MB, mem);
     conf.setInt(YarnConfiguration.NM_PMEM_MB, 10 * 1024);
     mem = NodeManagerHardwareUtils.getContainerMemoryMB(conf);
-    Assert.assertEquals(10 * 1024, mem);
+    assertEquals(10 * 1024, mem);
   }
 }

+ 12 - 9
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/util/TestProcessIdFileReader.java

@@ -17,23 +17,24 @@
  */
 package org.apache.hadoop.yarn.server.nodemanager.util;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
 
-import org.junit.Assert;
-
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.yarn.server.nodemanager.util.ProcessIdFileReader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class TestProcessIdFileReader {
 
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testNullPath() {
     String pid = null;
     try {
@@ -45,7 +46,8 @@ public class TestProcessIdFileReader {
     assert(pid == null);
   }
   
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testSimpleGet() throws IOException {
     String rootDir = new File(System.getProperty(
         "test.build.data", "/tmp")).getAbsolutePath();
@@ -63,7 +65,7 @@ public class TestProcessIdFileReader {
                   
       processId = ProcessIdFileReader.getProcessId(
           new Path(rootDir + Path.SEPARATOR + "temp.txt"));
-      Assert.assertEquals(expectedProcessId, processId);      
+      assertEquals(expectedProcessId, processId);
       
     } finally {
       if (testFile != null
@@ -74,7 +76,8 @@ public class TestProcessIdFileReader {
   }
 
     
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testComplexGet() throws IOException {
     String rootDir = new File(System.getProperty(
         "test.build.data", "/tmp")).getAbsolutePath();
@@ -98,7 +101,7 @@ public class TestProcessIdFileReader {
                   
       processId = ProcessIdFileReader.getProcessId(
           new Path(rootDir + Path.SEPARATOR + "temp.txt"));
-      Assert.assertEquals(expectedProcessId, processId);
+      assertEquals(expectedProcessId, processId);
       
     } finally {
       if (testFile != null

+ 21 - 18
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java

@@ -18,7 +18,10 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
-import static org.junit.Assume.assumeTrue;
+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.Assumptions.assumeTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
@@ -70,8 +73,8 @@ import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.webapp.YarnWebParams;
 import org.apache.hadoop.yarn.webapp.test.WebAppTests;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import com.google.inject.Injector;
 import com.google.inject.Module;
@@ -83,7 +86,8 @@ public class TestContainerLogsPage {
     return new NodeHealthCheckerService(dirsHandler);
   }
 
-  @Test(timeout=30000)
+  @Test
+  @Timeout(value = 30)
   public void testContainerLogDirs() throws IOException, YarnException {
     File absLogDir = new File("target",
       TestNMWebServer.class.getSimpleName() + "LogDir").getAbsoluteFile();
@@ -118,13 +122,13 @@ public class TestContainerLogsPage {
     nmContext.getContainers().put(container1, container);   
     List<File> files = null;
     files = ContainerLogsUtils.getContainerLogDirs(container1, user, nmContext);
-    Assert.assertTrue(!(files.get(0).toString().contains("file:")));
+    assertTrue(!(files.get(0).toString().contains("file:")));
     
     // After container is completed, it is removed from nmContext
     nmContext.getContainers().remove(container1);
-    Assert.assertNull(nmContext.getContainers().get(container1));
+    assertNull(nmContext.getContainers().get(container1));
     files = ContainerLogsUtils.getContainerLogDirs(container1, user, nmContext);
-    Assert.assertTrue(!(files.get(0).toString().contains("file:")));
+    assertTrue(!(files.get(0).toString().contains("file:")));
 
     // Create a new context to check if correct container log dirs are fetched
     // on full disk.
@@ -143,10 +147,11 @@ public class TestContainerLogsPage {
     List<File> dirs =
         ContainerLogsUtils.getContainerLogDirs(container1, user, nmContext);
     File containerLogDir = new File(absLogDir, appId + "/" + container1);
-    Assert.assertTrue(dirs.contains(containerLogDir));
+    assertTrue(dirs.contains(containerLogDir));
   }
 
-  @Test(timeout=30000)
+  @Test
+  @Timeout(value = 30)
   public void testContainerLogFile() throws IOException, YarnException {
     File absLogDir = new File("target",
         TestNMWebServer.class.getSimpleName() + "LogDir").getAbsoluteFile();
@@ -188,12 +193,13 @@ public class TestContainerLogsPage {
     containerLogFile.createNewFile();
     File file = ContainerLogsUtils.getContainerLogFile(containerId,
         fileName, user, nmContext);
-    Assert.assertEquals(containerLogFile.toURI().toString(),
+    assertEquals(containerLogFile.toURI().toString(),
         file.toURI().toString());
     FileUtil.fullyDelete(absLogDir);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testContainerLogPageAccess() throws IOException {
     // SecureIOUtils require Native IO to be enabled. This test will run
     // only if it is enabled.
@@ -316,10 +322,8 @@ public class TestContainerLogsPage {
     List<File> logDirFiles = ContainerLogsUtils.getContainerLogDirs(
       containerId, localDirs);
     
-    Assert.assertTrue("logDir lost drive letter " +
-      logDirFiles.get(0),
-      logDirFiles.get(0).toString().indexOf("F:" + File.separator +
-        "nmlogs") > -1);
+    assertTrue(logDirFiles.get(0).toString().indexOf("F:" + File.separator +
+        "nmlogs") > -1, "logDir lost drive letter " + logDirFiles.get(0));
   }
   
   @Test
@@ -363,9 +367,8 @@ public class TestContainerLogsPage {
     File logFile = ContainerLogsUtils.getContainerLogFile(containerId,
       "fileName", null, context);
       
-    Assert.assertTrue("logFile lost drive letter " +
-      logFile,
-      logFile.toString().indexOf("F:" + File.separator + "nmlogs") > -1);
+    assertTrue(logFile.toString().indexOf("F:" + File.separator + "nmlogs") > -1,
+        "logFile lost drive letter " + logFile);
     
   }
   

+ 7 - 8
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMAppsPage.java

@@ -34,31 +34,30 @@ import org.apache.hadoop.yarn.server.nodemanager.webapp.ApplicationPage.Applicat
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.webapp.YarnWebParams;
 import org.apache.hadoop.yarn.webapp.test.WebAppTests;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
 import com.google.inject.Binder;
 import com.google.inject.Injector;
 import com.google.inject.Module;
 
-@RunWith(Parameterized.class)
 public class TestNMAppsPage {
 
   String applicationid;
 
-  public TestNMAppsPage(String appid) {
+  public void initTestNMAppsPage(String appid) {
     this.applicationid = appid;
   }
 
-  @Parameterized.Parameters
   public static Collection<Object[]> getAppIds() {
     return Arrays.asList(new Object[][] { { "appid" },
         { "application_123123213_0001" }, { "" } });
   }
 
-  @Test
-  public void testNMAppsPage() {
+  @ParameterizedTest
+  @MethodSource("getAppIds")
+  public void testNMAppsPage(String appid) {
+    initTestNMAppsPage(appid);
     Configuration conf = new Configuration();
     final NMContext nmcontext = new NMContext(
         new NMContainerTokenSecretManager(conf), new NMTokenSecretManagerInNM(),

+ 11 - 9
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMContainerWebSocket.java

@@ -31,13 +31,15 @@ import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.eclipse.jetty.websocket.api.Session;
 import org.eclipse.jetty.websocket.api.UpgradeRequest;
 import org.eclipse.jetty.websocket.client.WebSocketClient;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 import java.io.File;
 import java.io.IOException;
 import java.net.URI;
@@ -60,13 +62,13 @@ public class TestNMContainerWebSocket {
       TestNMWebServer.class.getSimpleName() + "LogDir");
   private WebServer server;
 
-  @Before
+  @BeforeEach
   public void setup() {
     TESTROOTDIR.mkdirs();
     testLogDir.mkdir();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     FileUtil.fullyDelete(TESTROOTDIR);
     FileUtil.fullyDelete(testLogDir);
@@ -172,9 +174,9 @@ public class TestNMContainerWebSocket {
     when(aclManager.areACLsEnabled()).thenReturn(false);
     try {
       boolean authorized = ws.checkAuthorization(session, container);
-      Assert.assertTrue("Not authorized", authorized);
+      assertTrue(authorized, "Not authorized");
     } catch (IOException e) {
-      Assert.fail("Should not throw exception.");
+      fail("Should not throw exception.");
     }
   }
 }

+ 6 - 4
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebFilter.java

@@ -18,8 +18,8 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
-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 static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -47,7 +47,8 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
 import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 /**
  * Basic sanity Tests for NMWebFilter.
@@ -58,7 +59,8 @@ public class TestNMWebFilter {
   private static final String LOG_SERVER_URI = "log-server:1999/logs";
   private static final String USER = "testUser";
 
-  @Test(timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testRedirection() throws Exception {
     ApplicationId appId = ApplicationId.newInstance(
         System.currentTimeMillis(), 1);

+ 10 - 9
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java

@@ -55,10 +55,11 @@ import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestNMWebServer {
 
@@ -67,13 +68,13 @@ public class TestNMWebServer {
   private static File testLogDir = new File("target",
       TestNMWebServer.class.getSimpleName() + "LogDir");
 
-  @Before
+  @BeforeEach
   public void setup() {
     testRootDir.mkdirs();
     testLogDir.mkdir(); 
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     FileUtil.fullyDelete(testRootDir);
     FileUtil.fullyDelete(testLogDir);
@@ -137,9 +138,9 @@ public class TestNMWebServer {
   }
 
   private void validatePortVal(int portVal) {
-    Assert.assertTrue("Port is not updated", portVal > 0);
-    Assert.assertTrue("Port is default "+ YarnConfiguration.DEFAULT_NM_PORT,
-        portVal != YarnConfiguration.DEFAULT_NM_PORT);
+    assertTrue(portVal > 0, "Port is not updated");
+    assertTrue(portVal != YarnConfiguration.DEFAULT_NM_PORT,
+        "Port is default "+ YarnConfiguration.DEFAULT_NM_PORT);
   }
 
   @Test

+ 48 - 45
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServices.java

@@ -72,9 +72,10 @@ import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
@@ -105,11 +106,11 @@ import java.util.Iterator;
 
 import static org.apache.hadoop.yarn.webapp.WebServicesTestUtils.assertResponseStatusCode;
 import static org.assertj.core.api.Assertions.assertThat;
-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.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -258,20 +259,20 @@ public class TestNMWebServices extends JerseyTestBase {
 
   private void assertNMResourceInfoResponse(Response response, long value)
       throws JSONException {
-    assertEquals("MediaType of the response is not the expected!",
-        MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
-        response.getMediaType().toString());
+    assertEquals(MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
+        response.getMediaType().toString(),
+        "MediaType of the response is not the expected!");
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("Unexpected value in the json response!", value,
-        json.getJSONObject("nmResourceInfo").getLong("resourceValue"));
+    assertEquals(value, json.getJSONObject("nmResourceInfo").getLong("resourceValue"),
+        "Unexpected value in the json response!");
   }
 
   private void assertEmptyNMResourceInfo(Response response) throws JSONException {
-    assertEquals("MediaType of the response is not the expected!",
-        MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
-        response.getMediaType().toString());
+    assertEquals(MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
+        response.getMediaType().toString(),
+        "MediaType of the response is not the expected!");
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("Unexpected value in the json response!", 1, json.length());
+    assertEquals(1, json.length(), "Unexpected value in the json response!");
   }
 
   private Response getNMResourceResponse(WebTarget target, String resourceName) {
@@ -280,14 +281,14 @@ public class TestNMWebServices extends JerseyTestBase {
         .get();
   }
 
-  @Before
+  @BeforeEach
   public void before() throws Exception {
     testRemoteLogDir.mkdir();
     testRootDir.mkdirs();
     testLogDir.mkdir();
   }
 
-  @AfterClass
+  @AfterAll
   static public void stop() {
     FileUtil.fullyDelete(testRootDir);
     FileUtil.fullyDelete(testLogDir);
@@ -432,11 +433,12 @@ public class TestNMWebServices extends JerseyTestBase {
     InputSource is = new InputSource(new StringReader(xml));
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("nodeInfo");
-    assertEquals("incorrect number of elements", 1, nodes.getLength());
+    assertEquals(1, nodes.getLength(), "incorrect number of elements");
     verifyNodesXML(nodes);
   }
 
-  @Test(timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testContainerLogsWithNewAPI() throws Exception {
     ContainerId containerId0 = BuilderUtils.newContainerId(0, 0, 0, 0);
     WebTarget r0 = targetWithJsonObject();
@@ -451,7 +453,8 @@ public class TestNMWebServices extends JerseyTestBase {
     testContainerLogs(r1, containerId1, "");
   }
 
-  @Test (timeout = 5000)
+  @Test
+  @Timeout(value = 5)
   public void testContainerLogsWithOldAPI() throws Exception {
     final ContainerId containerId2 = BuilderUtils.newContainerId(1, 1, 0, 2);
     WebTarget r = targetWithJsonObject();
@@ -573,17 +576,17 @@ public class TestNMWebServices extends JerseyTestBase {
 
     WebTarget r = targetWithJsonObject();
     Response response = getNMResourceResponse(r, "resource-1");
-    assertEquals("MediaType of the response is not the expected!",
-        MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
-        response.getMediaType().toString());
+    assertEquals(MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8,
+        response.getMediaType().toString(), "MediaType of the response is not the expected!");
     JSONObject nmGpuResourceInfo = response.readEntity(JSONObject.class);
     JSONObject json = nmGpuResourceInfo.getJSONObject("nmGpuResourceInfo");
-    assertEquals("Unexpected driverVersion in the json response!",
-        "1.2.3", json.getJSONObject("gpuDeviceInformation").getString("driver_version"));
-    assertEquals("Unexpected totalGpuDevices in the json response!",
-        3, json.getJSONArray("totalGpuDevices").length());
-    assertEquals("Unexpected assignedGpuDevices in the json response!",
-        2, json.getJSONArray("assignedGpuDevices").length());
+    assertEquals("1.2.3",
+        json.getJSONObject("gpuDeviceInformation").getString("driver_version"),
+        "Unexpected driverVersion in the json response!");
+    assertEquals(3, json.getJSONArray("totalGpuDevices").length(),
+        "Unexpected totalGpuDevices in the json response!");
+    assertEquals(2, json.getJSONArray("assignedGpuDevices").length(),
+        "Unexpected assignedGpuDevices in the json response!");
   }
 
   @SuppressWarnings("checkstyle:methodlength")
@@ -613,7 +616,7 @@ public class TestNMWebServices extends JerseyTestBase {
     if (logFile.getParentFile().exists()) {
       FileUtils.deleteDirectory(logFile.getParentFile());
     }
-    assertTrue("Failed to create log dir", logFile.getParentFile().mkdirs());
+    assertTrue(logFile.getParentFile().mkdirs(), "Failed to create log dir");
     PrintWriter pw = new PrintWriter(logFile);
     pw.print(logMessage);
     pw.close();
@@ -807,9 +810,9 @@ public class TestNMWebServices extends JerseyTestBase {
   }
 
   public void verifyNodeInfo(JSONObject json) throws JSONException, Exception {
-    assertEquals("incorrect number of elements", 1, json.length());
+    assertEquals(1, json.length(), "incorrect number of elements");
     JSONObject info = json.getJSONObject("nodeInfo");
-    assertEquals("incorrect number of elements", 18, info.length());
+    assertEquals(18, info.length(), "incorrect number of elements");
     verifyNodeInfoGeneric(info.getString("id"), info.getString("healthReport"),
         info.getLong("totalVmemAllocatedContainersMB"),
         info.getLong("totalPmemAllocatedContainersMB"),
@@ -840,17 +843,17 @@ public class TestNMWebServices extends JerseyTestBase {
     WebServicesTestUtils.checkStringMatch("id", "testhost.foo.com:8042", id);
     WebServicesTestUtils.checkStringMatch("healthReport", "Healthy",
         healthReport);
-    assertEquals("totalVmemAllocatedContainersMB incorrect", 15872,
-        totalVmemAllocatedContainersMB);
-    assertEquals("totalPmemAllocatedContainersMB incorrect", 16384,
-        totalPmemAllocatedContainersMB);
-    assertEquals("totalVCoresAllocatedContainers incorrect", 4000,
-        totalVCoresAllocatedContainers);
-    assertTrue("vmemCheckEnabled incorrect", vmemCheckEnabled);
-    assertTrue("pmemCheckEnabled incorrect", pmemCheckEnabled);
-    assertEquals("lastNodeUpdateTime incorrect", lastNodeUpdateTime, nmContext
-        .getNodeHealthStatus().getLastHealthReportTime());
-    assertTrue("nodeHealthy isn't true", nodeHealthy);
+    assertEquals(15872,
+        totalVmemAllocatedContainersMB, "totalVmemAllocatedContainersMB incorrect");
+    assertEquals(16384,
+        totalPmemAllocatedContainersMB, "totalPmemAllocatedContainersMB incorrect");
+    assertEquals(4000,
+        totalVCoresAllocatedContainers, "totalVCoresAllocatedContainers incorrect");
+    assertTrue(vmemCheckEnabled, "vmemCheckEnabled incorrect");
+    assertTrue(pmemCheckEnabled, "pmemCheckEnabled incorrect");
+    assertEquals(lastNodeUpdateTime, nmContext
+        .getNodeHealthStatus().getLastHealthReportTime(), "lastNodeUpdateTime incorrect");
+    assertTrue(nodeHealthy, "nodeHealthy isn't true");
     WebServicesTestUtils.checkStringMatch("nodeHostName", "testhost.foo.com",
         nodeHostName);
 

+ 28 - 28
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesApps.java

@@ -19,8 +19,8 @@
 package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
 import static org.apache.hadoop.yarn.webapp.WebServicesTestUtils.assertResponseStatusCode;
-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 static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -69,9 +69,9 @@ import org.apache.hadoop.yarn.webapp.WebServicesTestUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -167,13 +167,13 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     }
   }
 
-  @Before
+  @BeforeEach
   public void before() throws Exception {
     testRootDir.mkdirs();
     testLogDir.mkdir();
   }
 
-  @AfterClass
+  @AfterAll
   static public void cleanup() {
     FileUtil.fullyDelete(testRootDir);
     FileUtil.fullyDelete(testLogDir);
@@ -190,7 +190,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8,
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("apps is not empty", new JSONObject("{apps:\"\"}"), json);
+    assertEquals(new JSONObject("{apps:\"\"}"), json, "apps is not empty");
   }
 
   private HashMap<String, String> addAppContainers(Application app) 
@@ -253,9 +253,9 @@ public class TestNMWebServicesApps extends JerseyTestBase {
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
     JSONObject info = json.getJSONObject("apps");
-    assertEquals("incorrect number of elements", 1, info.length());
+    assertEquals(1, info.length(), "incorrect number of elements");
     JSONArray appInfo = info.getJSONArray("app");
-    assertEquals("incorrect number of elements", 2, appInfo.length());
+    assertEquals(2, appInfo.length(), "incorrect number of elements");
     String id = appInfo.getJSONObject(0).getString("id");
     if (id.matches(app.getAppId().toString())) {
       verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
@@ -284,9 +284,9 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     JSONObject json = response.readEntity(JSONObject.class);
 
     JSONObject info = json.getJSONObject("apps");
-    assertEquals("incorrect number of elements", 1, info.length());
+    assertEquals(1, info.length(), "incorrect number of elements");
     JSONArray appInfo = parseJsonArray(info);
-    assertEquals("incorrect number of elements", 1, appInfo.length());
+    assertEquals(1, appInfo.length(), "incorrect number of elements");
     verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
   }
 
@@ -306,7 +306,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8,
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("apps is not empty", new JSONObject("{apps:\"\"}"), json);
+    assertEquals(new JSONObject("{apps:\"\"}"), json, "apps is not empty");
   }
 
   @Test
@@ -331,7 +331,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -363,9 +363,9 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     JSONObject json = response.readEntity(JSONObject.class);
 
     JSONObject info = json.getJSONObject("apps");
-    assertEquals("incorrect number of elements", 1, info.length());
+    assertEquals(1, info.length(), "incorrect number of elements");
     JSONArray appInfo = parseJsonArray(info);
-    assertEquals("incorrect number of elements", 1, appInfo.length());
+    assertEquals(1, appInfo.length(), "incorrect number of elements");
     verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
 
   }
@@ -387,7 +387,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
 
-    assertEquals("apps is not empty", new JSONObject("{apps:\"\"}"), json);
+    assertEquals(new JSONObject("{apps:\"\"}"), json, "apps is not empty");
   }
 
   @Test
@@ -413,7 +413,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -444,7 +444,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -572,7 +572,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -605,7 +605,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -638,7 +638,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     is.setCharacterStream(new StringReader(xml));
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("app");
-    assertEquals("incorrect number of elements", 2, nodes.getLength());
+    assertEquals(2, nodes.getLength(), "incorrect number of elements");
   }
 
   @Test
@@ -663,7 +663,7 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     is.setCharacterStream(new StringReader(xml));
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("app");
-    assertEquals("incorrect number of elements", 1, nodes.getLength());
+    assertEquals(1, nodes.getLength(), "incorrect number of elements");
     verifyNodeAppInfoXML(nodes, app, hash);
   }
 
@@ -682,15 +682,15 @@ public class TestNMWebServicesApps extends JerseyTestBase {
         Element line = (Element) ids.item(j);
         Node first = line.getFirstChild();
         String val = first.getNodeValue();
-        assertEquals("extra containerid: " + val, val, hash.remove(val));
+        assertEquals(val, hash.remove(val), "extra containerid: " + val);
       }
-      assertTrue("missing containerids", hash.isEmpty());
+      assertTrue(hash.isEmpty(), "missing containerids");
     }
   }
 
   public void verifyNodeAppInfo(JSONObject info, Application app,
       HashMap<String, String> hash) throws JSONException, Exception {
-    assertEquals("incorrect number of elements", 4, info.length());
+    assertEquals(4, info.length(), "incorrect number of elements");
 
     verifyNodeAppInfoGeneric(app, info.getString("id"),
         info.getString("state"), info.getString("user"));
@@ -698,9 +698,9 @@ public class TestNMWebServicesApps extends JerseyTestBase {
     JSONArray containerids = info.getJSONArray("containerids");
     for (int i = 0; i < containerids.length(); i++) {
       String id = containerids.getString(i);
-      assertEquals("extra containerid: " + id, id, hash.remove(id));
+      assertEquals(id, hash.remove(id), "extra containerid: " + id);
     }
-    assertTrue("missing containerids", hash.isEmpty());
+    assertTrue(hash.isEmpty(), "missing containerids");
   }
 
   public void verifyNodeAppInfoGeneric(Application app, String id,

+ 16 - 15
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesAuxServices.java

@@ -19,7 +19,7 @@
 package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
 import static org.apache.hadoop.yarn.webapp.WebServicesTestUtils.assertResponseStatusCode;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -62,9 +62,9 @@ import org.apache.hadoop.yarn.webapp.WebServicesTestUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
@@ -166,18 +166,19 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
     }
   }
 
+  @BeforeEach
   @Override
   public void setUp() throws Exception {
     super.setUp();
   }
 
-  @Before
+  @BeforeEach
   public void before() throws Exception {
     testRootDir.mkdirs();
     testLogDir.mkdir();
   }
 
-  @AfterClass
+  @AfterAll
   static public void cleanup() {
     FileUtil.fullyDelete(testRootDir);
     FileUtil.fullyDelete(testLogDir);
@@ -196,7 +197,7 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
     assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8,
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("aux services isn't empty", "{\"services\":\"\"}", json.toString());
+    assertEquals("{\"services\":\"\"}", json.toString(), "aux services isn't empty");
   }
 
   private void addAuxServices(AuxServiceRecord... records) {
@@ -236,9 +237,9 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
     JSONObject info = json.getJSONObject("services");
-    assertEquals("incorrect number of elements", 1, info.length());
+    assertEquals(1, info.length(), "incorrect number of elements");
     JSONArray auxInfo = info.getJSONArray("service");
-    assertEquals("incorrect number of elements", 2, auxInfo.length());
+    assertEquals(2, auxInfo.length(), "incorrect number of elements");
 
     verifyNodeAuxServiceInfo(auxInfo.getJSONObject(0), r1);
     verifyNodeAuxServiceInfo(auxInfo.getJSONObject(1), r2);
@@ -265,7 +266,7 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
     is.setCharacterStream(new StringReader(xml));
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("service");
-    assertEquals("incorrect number of elements", 2, nodes.getLength());
+    assertEquals(2, nodes.getLength(), "incorrect number of elements");
     verifyAuxServicesInfoXML(nodes, r1, r2);
   }
 
@@ -286,7 +287,7 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -316,8 +317,8 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
     if (info.has("version")) {
       version = info.getString("version");
     }
-    assertEquals("incorrect number of elements",
-        version == null ? 2 : 3, info.length());
+    assertEquals(version == null ? 2 : 3, info.length(),
+        "incorrect number of elements");
     verifyNodeAuxServiceInfoGeneric(r, info.getString("name"),
         version, info.getString("startTime"));
   }
@@ -326,7 +327,7 @@ public class TestNMWebServicesAuxServices extends JerseyTestBase {
       String version, String startTime) {
     assertEquals(r.getName(), name);
     assertEquals(r.getVersion(), version);
-    assertEquals("startTime", dateFormat.format(r.getLaunchTime()),
-        startTime);
+    assertEquals(dateFormat.format(r.getLaunchTime()),
+        startTime, "startTime");
   }
 }

+ 30 - 34
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java

@@ -20,9 +20,9 @@ package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
 import static org.apache.hadoop.yarn.webapp.WebServicesTestUtils.assertResponseStatusCode;
 import static org.apache.hadoop.yarn.util.StringHelper.ujoin;
-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 static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -70,9 +70,9 @@ import org.apache.hadoop.yarn.webapp.WebServicesTestUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
@@ -172,19 +172,19 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
     }
   }
 
-  @Before
+  @BeforeEach
   @Override
   public void setUp() throws Exception {
     super.setUp();
   }
 
-  @Before
+  @BeforeEach
   public void before() throws Exception {
     testRootDir.mkdirs();
     testLogDir.mkdir();
   }
 
-  @AfterClass
+  @AfterAll
   static public void cleanup() {
     FileUtil.fullyDelete(testRootDir);
     FileUtil.fullyDelete(testLogDir);
@@ -202,7 +202,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
     assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8,
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
-    assertEquals("apps isn't empty", "{\"containers\":\"\"}", json.toString());
+    assertEquals("{\"containers\":\"\"}", json.toString(), "apps isn't empty");
   }
 
   private HashMap<String, String> addAppContainers(Application app) 
@@ -277,9 +277,9 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
         response.getMediaType().toString());
     JSONObject json = response.readEntity(JSONObject.class);
     JSONObject info = json.getJSONObject("containers");
-    assertEquals("incorrect number of elements", 1, info.length());
+    assertEquals(1, info.length(), "incorrect number of elements");
     JSONArray conInfo = info.getJSONArray("container");
-    assertEquals("incorrect number of elements", 4, conInfo.length());
+    assertEquals(4, conInfo.length(), "incorrect number of elements");
 
     for (int i = 0; i < conInfo.length(); i++) {
       verifyNodeContainerInfo(conInfo.getJSONObject(i),
@@ -344,7 +344,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -376,7 +376,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -409,7 +409,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
           response.getMediaType().toString());
       JSONObject msg = response.readEntity(JSONObject.class);
       JSONObject exception = msg.getJSONObject("RemoteException");
-      assertEquals("incorrect number of elements", 3, exception.length());
+      assertEquals(3, exception.length(), "incorrect number of elements");
       String message = exception.getString("message");
       String type = exception.getString("exception");
       String classname = exception.getString("javaClassName");
@@ -445,7 +445,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
       is.setCharacterStream(new StringReader(xml));
       Document dom = db.parse(is);
       NodeList nodes = dom.getElementsByTagName("container");
-      assertEquals("incorrect number of elements", 1, nodes.getLength());
+      assertEquals(1, nodes.getLength(), "incorrect number of elements");
       verifyContainersInfoXML(nodes,
           nmContext.getContainers().get(ContainerId.fromString(id)));
 
@@ -474,7 +474,7 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
     is.setCharacterStream(new StringReader(xml));
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("container");
-    assertEquals("incorrect number of elements", 4, nodes.getLength());
+    assertEquals(4, nodes.getLength(), "incorrect number of elements");
   }
 
   public void verifyContainersInfoXML(NodeList nodes, Container cont)
@@ -495,17 +495,16 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
       // verify that the container log files element exists
       List<String> containerLogFiles =
           WebServicesTestUtils.getXmlStrings(element, "containerLogFiles");
-      assertFalse("containerLogFiles missing",containerLogFiles.isEmpty());
+      assertFalse(containerLogFiles.isEmpty(), "containerLogFiles missing");
       assertEquals(2, containerLogFiles.size());
-      assertTrue("syslog and stdout expected",
-          containerLogFiles.contains("syslog") &&
-          containerLogFiles.contains("stdout"));
+      assertTrue(containerLogFiles.contains("syslog") &&
+          containerLogFiles.contains("stdout"), "syslog and stdout expected");
     }
   }
 
   public void verifyNodeContainerInfo(JSONObject info, Container cont)
       throws JSONException, Exception {
-    assertEquals("incorrect number of elements", 11, info.length());
+    assertEquals(11, info.length(), "incorrect number of elements");
 
     verifyNodeContainerInfoGeneric(cont, info.getString("id"),
         info.getString("state"), info.getString("user"),
@@ -515,12 +514,11 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
         info.getString("containerLogsLink"));
     // verify that the container log files element exists
     JSONArray containerLogFilesArr = info.getJSONArray("containerLogFiles");
-    assertTrue("containerLogFiles missing", containerLogFilesArr != null);
+    assertTrue(containerLogFilesArr != null, "containerLogFiles missing");
     assertEquals(2, containerLogFilesArr.length());
     for (int i = 0; i < 2; i++) {
-      assertTrue("syslog and stdout expected",
-          containerLogFilesArr.get(i).equals("syslog") ||
-          containerLogFilesArr.get(i).equals("stdout"));
+      assertTrue(containerLogFilesArr.get(i).equals("syslog") ||
+          containerLogFilesArr.get(i).equals("stdout"), "syslog and stdout expected");
     }
   }
 
@@ -535,21 +533,19 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
         .toString(), state);
     WebServicesTestUtils.checkStringMatch("user", cont.getUser().toString(),
         user);
-    assertEquals("exitCode wrong", 0, exitCode);
+    assertEquals(0, exitCode, "exitCode wrong");
     WebServicesTestUtils
         .checkStringMatch("diagnostics", "testing", diagnostics);
 
     WebServicesTestUtils.checkStringMatch("nodeId", nmContext.getNodeId()
         .toString(), nodeId);
-    assertEquals("totalMemoryNeededMB wrong",
-      YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
-      totalMemoryNeededMB);
-    assertEquals("totalVCoresNeeded wrong",
-      YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES,
-      totalVCoresNeeded);
+    assertEquals(YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
+        totalMemoryNeededMB, "totalMemoryNeededMB wrong");
+    assertEquals(YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES,
+        totalVCoresNeeded, "totalVCoresNeeded wrong");
     String shortLink =
         ujoin("containerlogs", cont.getContainerId().toString(),
             cont.getUser());
-    assertTrue("containerLogsLink wrong", logsLink.contains(shortLink));
+    assertTrue(logsLink.contains(shortLink), "containerLogsLink wrong");
   }
 }

+ 6 - 6
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebTerminal.java

@@ -17,7 +17,7 @@
 */
 package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.io.File;
 import java.io.IOException;
@@ -36,9 +36,9 @@ import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
 import org.apache.hadoop.yarn.server.nodemanager.ResourceView;
 import org.apache.hadoop.yarn.server.nodemanager.health.NodeHealthCheckerService;
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
-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;
 
 /**
  * Unit test for hosting web terminal servlet in node manager.
@@ -96,12 +96,12 @@ public class TestNMWebTerminal {
     return server.getPort();
   }
 
-  @Before
+  @BeforeEach
   public void setUp() {
     port = startNMWebAppServer("0.0.0.0:0");
   }
 
-  @After
+  @AfterEach
   public void tearDown() throws IOException {
     server.close();
     healthChecker.close();

+ 12 - 14
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/gpu/TestGpuDeviceInformationParser.java

@@ -20,23 +20,19 @@ package org.apache.hadoop.yarn.server.nodemanager.webapp.dao.gpu;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.yarn.exceptions.YarnException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
 
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class TestGpuDeviceInformationParser {
   private static final double DELTA = 1e-6;
 
-  @Rule
-  public ExpectedException expected = ExpectedException.none();
-
   @Test
   public void testParse() throws IOException, YarnException {
     File f = new File("src/test/resources/nvidia-smi-sample-output.xml");
@@ -84,16 +80,18 @@ public class TestGpuDeviceInformationParser {
 
   @Test
   public void testParseEmptyString() throws YarnException {
-    expected.expect(YarnException.class);
-    GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
-    parser.parseXml("");
+    assertThrows(YarnException.class, () -> {
+      GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
+      parser.parseXml("");
+    });
   }
 
   @Test
   public void testParseInvalidRootElement() throws YarnException {
-    expected.expect(YarnException.class);
-    GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
-    parser.parseXml("<nvidia_smiiiii></nvidia_smiiiii");
+    assertThrows(YarnException.class, () -> {
+      GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
+      parser.parseXml("<nvidia_smiiiii></nvidia_smiiiii");
+    });
   }
 
   @Test