Selaa lähdekoodia

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

Co-authored-by: Chris Nauroth <cnauroth@apache.org>
Reviewed-by: Chris Nauroth <cnauroth@apache.org>
Signed-off-by: Shilun Fan <slfan1989@apache.org>
slfan1989 4 kuukautta sitten
vanhempi
commit
2550344f4f
93 muutettua tiedostoa jossa 1676 lisäystä ja 1587 poistoa
  1. 33 33
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestClusterTopology.java
  2. 22 17
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestDNS.java
  3. 6 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestDNSDomainNameResolver.java
  4. 5 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestMockDomainNameResolver.java
  5. 31 23
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestNetUtils.java
  6. 9 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestNetworkTopologyWithNodeGroup.java
  7. 12 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestScriptBasedMapping.java
  8. 13 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestScriptBasedMappingWithDependency.java
  9. 6 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestSocketIOWithTimeout.java
  10. 14 19
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestStaticMapping.java
  11. 15 17
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestSwitchMapping.java
  12. 5 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestTableMapping.java
  13. 70 47
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/unix/TestDomainSocket.java
  14. 22 14
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/unix/TestDomainSocketWatcher.java
  15. 10 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestFrameDecoder.java
  16. 6 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcAcceptedReply.java
  17. 14 8
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcCall.java
  18. 16 14
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcCallCache.java
  19. 13 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcDeniedReply.java
  20. 11 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcMessage.java
  21. 11 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcReply.java
  22. 5 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestXDR.java
  23. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/security/TestCredentialsSys.java
  24. 6 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/security/TestRpcAuthInfo.java
  25. 16 13
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/portmap/TestPortmap.java
  26. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ManualTestKeytabLogins.java
  27. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestAuthenticationFilter.java
  28. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestCompositeGroupMapping.java
  29. 44 46
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestCredentials.java
  30. 22 17
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestDoAsEffectiveUser.java
  31. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestGroupFallback.java
  32. 16 16
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestGroupsCaching.java
  33. 7 8
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestHttpCrossOriginFilterInitializer.java
  34. 2 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestIngressPortBasedResolver.java
  35. 4 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestJNIGroupsMapping.java
  36. 13 21
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestKDiag.java
  37. 5 18
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestKDiagNoKDC.java
  38. 25 21
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMapping.java
  39. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingBase.java
  40. 5 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithBindUserSwitch.java
  41. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithFailover.java
  42. 10 8
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithOneQuery.java
  43. 7 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithPosixGroup.java
  44. 5 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestNetgroupCache.java
  45. 7 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestNullGroupsMapping.java
  46. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestProxyUserFromEnv.java
  47. 15 14
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestRuleBasedLdapGroupsMapping.java
  48. 11 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestSecurityUtil.java
  49. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestShellBasedIdMapping.java
  50. 33 44
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestShellBasedUnixGroupsMapping.java
  51. 85 91
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGILoginFromKeytab.java
  52. 12 10
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGIWithExternalKdc.java
  53. 6 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGIWithMiniKdc.java
  54. 4 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUserFromEnv.java
  55. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestWhitelistBasedResolver.java
  56. 20 20
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredShell.java
  57. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredentialProvider.java
  58. 23 27
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredentialProviderFactory.java
  59. 4 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authentication/server/TestProxyUserAuthenticationFilter.java
  60. 11 12
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestAccessControlList.java
  61. 5 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestDefaultImpersonationProvider.java
  62. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestProxyServers.java
  63. 39 43
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestProxyUsers.java
  64. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestServiceAuthorization.java
  65. 89 88
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestCrossOriginFilter.java
  66. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestRestCsrfPreventionFilter.java
  67. 13 17
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestXFrameOptionsFilter.java
  68. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestDelegatingSSLSocketFactory.java
  69. 174 163
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestReloadingX509KeyManager.java
  70. 26 20
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestReloadingX509TrustManager.java
  71. 59 51
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestSSLFactory.java
  72. 89 89
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/TestDtUtilShell.java
  73. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/TestToken.java
  74. 26 24
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/TestDelegationToken.java
  75. 14 15
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/web/TestDelegationTokenManager.java
  76. 97 92
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/web/TestWebDelegationToken.java
  77. 139 109
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestCompositeService.java
  78. 4 4
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestServiceOperations.java
  79. 11 25
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/AbstractServiceLauncherTestBase.java
  80. 6 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceConf.java
  81. 7 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceInterruptHandling.java
  82. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncher.java
  83. 1 1
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncherCreationFailures.java
  84. 3 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncherInnerMethods.java
  85. 7 7
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/testservices/InitInConstructorLaunchableService.java
  86. 2 2
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/testservices/LaunchableRunningService.java
  87. 9 6
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestGenericTestUtils.java
  88. 4 3
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestJUnitSetup.java
  89. 9 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestLambdaTestUtils.java
  90. 11 12
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestMultithreadedTestUtil.java
  91. 12 9
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestTimedOutTestsListener.java
  92. 2 5
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TimedOutTestsListener.java
  93. 14 14
      hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/tools/TestCommandShell.java

+ 33 - 33
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestClusterTopology.java

@@ -26,10 +26,10 @@ import java.util.Arrays;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.commons.math3.stat.inference.ChiSquareTest;
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
 
-public class TestClusterTopology extends Assert {
+public class TestClusterTopology extends Assertions {
 
   public static class NodeElement implements Node {
     private String location;
@@ -96,34 +96,33 @@ public class TestClusterTopology extends Assert {
     // create exclude list
     List<Node> excludedNodes = new ArrayList<Node>();
 
-    assertEquals("4 nodes should be available", 4,
-        cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes));
+    assertEquals(4, cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes),
+        "4 nodes should be available");
     NodeElement deadNode = getNewNode("node5", "/d1/r2");
     excludedNodes.add(deadNode);
-    assertEquals("4 nodes should be available with extra excluded Node", 4,
-        cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes));
+    assertEquals(4, cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes),
+        "4 nodes should be available with extra excluded Node");
     // add one existing node to exclude list
     excludedNodes.add(node4);
-    assertEquals("excluded nodes with ROOT scope should be considered", 3,
-        cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes));
-    assertEquals("excluded nodes without ~ scope should be considered", 2,
-        cluster.countNumOfAvailableNodes("~" + deadNode.getNetworkLocation(),
-            excludedNodes));
-    assertEquals("excluded nodes with rack scope should be considered", 1,
-        cluster.countNumOfAvailableNodes(deadNode.getNetworkLocation(),
-            excludedNodes));
+    assertEquals(3, cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes),
+        "excluded nodes with ROOT scope should be considered");
+    assertEquals(2,
+        cluster.countNumOfAvailableNodes("~" + deadNode.getNetworkLocation(), excludedNodes),
+        "excluded nodes without ~ scope should be considered");
+    assertEquals(1, cluster.countNumOfAvailableNodes(deadNode.getNetworkLocation(),
+        excludedNodes), "excluded nodes with rack scope should be considered");
     // adding the node in excluded scope to excluded list
     excludedNodes.add(node2);
-    assertEquals("excluded nodes with ~ scope should be considered", 2,
-        cluster.countNumOfAvailableNodes("~" + deadNode.getNetworkLocation(),
-            excludedNodes));
+    assertEquals(2,
+        cluster.countNumOfAvailableNodes("~" + deadNode.getNetworkLocation(), excludedNodes),
+        "excluded nodes with ~ scope should be considered");
     // getting count with non-exist scope.
-    assertEquals("No nodes should be considered for non-exist scope", 0,
-        cluster.countNumOfAvailableNodes("/non-exist", excludedNodes));
+    assertEquals(0, cluster.countNumOfAvailableNodes("/non-exist", excludedNodes),
+        "No nodes should be considered for non-exist scope");
     // remove a node from the cluster
     cluster.remove(node1);
-    assertEquals("1 node should be available", 1,
-        cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes));
+    assertEquals(1, cluster.countNumOfAvailableNodes(NodeBase.ROOT, excludedNodes),
+        "1 node should be available");
   }
 
   /**
@@ -160,7 +159,7 @@ public class TestClusterTopology extends Assert {
         }
         histogram.put(randomNode, histogram.get(randomNode) + 1);
       }
-      assertEquals("Random is not selecting all nodes", 4, histogram.size());
+      assertEquals(4, histogram.size(), "Random is not selecting all nodes");
 
       // Check with 99% confidence alpha=0.01 as confidence = 100 * (1 - alpha)
       ChiSquareTest chiSquareTest = new ChiSquareTest();
@@ -181,8 +180,8 @@ public class TestClusterTopology extends Assert {
     }
 
     // Check that they have the proper distribution
-    assertFalse("Random not choosing nodes with proper distribution",
-            chiSquareTestRejectedCounter==3);
+    assertFalse(chiSquareTestRejectedCounter == 3,
+        "Random not choosing nodes with proper distribution");
 
     // Pick random nodes excluding the 2 nodes in /d1/r3
     HashMap<String, Integer> histogram = new HashMap<String, Integer>();
@@ -193,8 +192,8 @@ public class TestClusterTopology extends Assert {
       }
       histogram.put(randomNode, histogram.get(randomNode) + 1);
     }
-    assertEquals("Random is not selecting the nodes it should",
-        2, histogram.size());
+    assertEquals(2, histogram.size(),
+        "Random is not selecting the nodes it should");
 
     Node val = cluster.chooseRandom("/d1", "/d", Collections.emptyList());
     assertNotNull(val);
@@ -268,9 +267,10 @@ public class TestClusterTopology extends Assert {
     for (Pair<Integer, NodeElement> test: new Pair[]{Pair.of(0, node1),
         Pair.of(2, node2), Pair.of(4, node3)}) {
       int expect = test.getLeft();
-      assertEquals(test.toString(), expect, cluster.getWeight(node1, test.getRight()));
-      assertEquals(test.toString(), expect,
-          cluster.getWeightUsingNetworkLocation(node1, test.getRight()));
+      assertEquals(expect, cluster.getWeight(node1, test.getRight()),
+          test.toString());
+      assertEquals(expect, cluster.getWeightUsingNetworkLocation(node1, test.getRight()),
+          test.toString());
     }
     // Reset so that we can have 2 levels
     cluster = NetworkTopology.getInstance(new Configuration());
@@ -281,9 +281,9 @@ public class TestClusterTopology extends Assert {
     for (Pair<Integer, NodeElement> test: new Pair[]{Pair.of(0, node5),
         Pair.of(2, node6), Pair.of(4, node7), Pair.of(6, node8)}) {
       int expect = test.getLeft();
-      assertEquals(test.toString(), expect, cluster.getWeight(node5, test.getRight()));
-      assertEquals(test.toString(), expect,
-          cluster.getWeightUsingNetworkLocation(node5, test.getRight()));
+      assertEquals(expect, cluster.getWeight(node5, test.getRight()), test.toString());
+      assertEquals(expect, cluster.getWeightUsingNetworkLocation(node5, test.getRight()),
+          test.toString());
     }
   }
 }

+ 22 - 17
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestDNS.java

@@ -29,14 +29,18 @@ import javax.naming.ServiceUnavailableException;
 
 import org.apache.hadoop.util.Time;
 
-import org.assertj.core.api.Assertions;
-import org.junit.Assume;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
-import static org.junit.Assert.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 /**
  * Test host name and IP resolution and caching.
@@ -77,9 +81,8 @@ public class TestDNS {
     assertEquals(hostname3, hostname2);
     assertEquals(hostname2, hostname1);
     long interval = t2 - t1;
-    assertTrue(
-        "Took too long to determine local host - caching is not working",
-        interval < 20000);
+    assertTrue(interval < 20000,
+        "Took too long to determine local host - caching is not working");
   }
 
   /**
@@ -103,7 +106,7 @@ public class TestDNS {
   @Test
   public void testNullInterface() throws Exception {
     String host = DNS.getDefaultHost(null);  // should work.
-    Assertions.assertThat(host).isEqualTo(DNS.getDefaultHost(DEFAULT));
+    assertThat(host).isEqualTo(DNS.getDefaultHost(DEFAULT));
     try {
       String ip = DNS.getDefaultIP(null);
       fail("Expected a NullPointerException, got " + ip);
@@ -119,7 +122,7 @@ public class TestDNS {
   @Test
   public void testNullDnsServer() throws Exception {
     String host = DNS.getDefaultHost(getLoopbackInterface(), null);
-    Assertions.assertThat(host)
+    assertThat(host)
         .isEqualTo(DNS.getDefaultHost(getLoopbackInterface()));
   }
 
@@ -130,7 +133,7 @@ public class TestDNS {
   @Test
   public void testDefaultDnsServer() throws Exception {
     String host = DNS.getDefaultHost(getLoopbackInterface(), DEFAULT);
-    Assertions.assertThat(host)
+    assertThat(host)
         .isEqualTo(DNS.getDefaultHost(getLoopbackInterface()));
   }
 
@@ -154,7 +157,7 @@ public class TestDNS {
   @Test
   public void testGetIPWithDefault() throws Exception {
     String[] ips = DNS.getIPs(DEFAULT);
-    assertEquals("Should only return 1 default IP", 1, ips.length);
+    assertEquals(1, ips.length, "Should only return 1 default IP");
     assertEquals(getLocalIPAddr().getHostAddress(), ips[0].toString());
     String ip = DNS.getDefaultIP(DEFAULT);
     assertEquals(ip, ips[0].toString());
@@ -178,7 +181,7 @@ public class TestDNS {
                 + " Loopback=" + localhost.isLoopbackAddress()
                 + " Linklocal=" + localhost.isLinkLocalAddress());
       }
-      Assume.assumeNoException(e);
+      assumeTrue(false, e.getMessage());
     }
   }
 
@@ -196,7 +199,8 @@ public class TestDNS {
    *
    * @throws Exception
    */
-  @Test (timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testLookupWithHostsFallback() throws Exception {
     assumeNotWindows();
     final String oldHostname = DNS.getCachedHostname();
@@ -206,7 +210,7 @@ public class TestDNS {
           getLoopbackInterface(), INVALID_DNS_SERVER, true);
 
       // Expect to get back something other than the cached host name.
-      Assertions.assertThat(hostname).isNotEqualTo(DUMMY_HOSTNAME);
+      assertThat(hostname).isNotEqualTo(DUMMY_HOSTNAME);
     } finally {
       // Restore DNS#cachedHostname for subsequent tests.
       DNS.setCachedHostname(oldHostname);
@@ -219,7 +223,8 @@ public class TestDNS {
    *
    * @throws Exception
    */
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testLookupWithoutHostsFallback() throws Exception {
     final String oldHostname = DNS.getCachedHostname();
     try {
@@ -229,7 +234,7 @@ public class TestDNS {
 
       // Expect to get back the cached host name since there was no hosts
       // file lookup.
-      Assertions.assertThat(hostname).isEqualTo(DUMMY_HOSTNAME);
+      assertThat(hostname).isEqualTo(DUMMY_HOSTNAME);
     } finally {
       // Restore DNS#cachedHostname for subsequent tests.
       DNS.setCachedHostname(oldHostname);
@@ -249,7 +254,7 @@ public class TestDNS {
   @Test
   public void testLocalhostResolves() throws Exception {
     InetAddress localhost = InetAddress.getByName("localhost");
-    assertNotNull("localhost is null", localhost);
+    assertNotNull(localhost, "localhost is null");
     LOG.info("Localhost IPAddr is " + localhost.toString());
   }
 }

+ 6 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestDNSDomainNameResolver.java

@@ -17,16 +17,15 @@
  */
 package org.apache.hadoop.net;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.Objects;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assume.assumeFalse;
-
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
 
 public class TestDNSDomainNameResolver {
 
@@ -35,8 +34,8 @@ public class TestDNSDomainNameResolver {
   @Test
   public void testGetHostNameByIP() throws UnknownHostException {
     InetAddress localhost = InetAddress.getLocalHost();
-    assumeFalse("IP lookup support required",
-        Objects.equals(localhost.getCanonicalHostName(), localhost.getHostAddress()));
+    assumeFalse(Objects.equals(localhost.getCanonicalHostName(), localhost.getHostAddress()),
+        "IP lookup support required");
 
     // Precondition: host name and canonical host name for unresolved returns an IP address.
     InetAddress unresolved = InetAddress.getByAddress(localhost.getHostAddress(),

+ 5 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestMockDomainNameResolver.java

@@ -19,15 +19,15 @@ package org.apache.hadoop.net;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * This class mainly test the MockDomainNameResolver comes working as expected.
@@ -36,7 +36,7 @@ public class TestMockDomainNameResolver {
 
   private Configuration conf;
 
-  @Before
+  @BeforeEach
   public void setup() {
     conf = new Configuration();
     conf.set(CommonConfigurationKeys.HADOOP_DOMAINNAME_RESOLVER_IMPL,

+ 31 - 23
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestNetUtils.java

@@ -17,7 +17,14 @@
  */
 package org.apache.hadoop.net;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 import java.io.EOFException;
 import java.io.IOException;
@@ -47,10 +54,9 @@ import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.test.LambdaTestUtils;
 import org.apache.hadoop.util.Shell;
 
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -145,7 +151,7 @@ public class TestNetUtils {
     if (withChannel) {
       s = NetUtils.getDefaultSocketFactory(new Configuration())
           .createSocket();
-      Assume.assumeNotNull(s.getChannel());
+      assumeTrue(s.getChannel() != null);
     } else {
       s = new Socket();
       assertNull(s.getChannel());
@@ -193,8 +199,8 @@ public class TestNetUtils {
     long durationNano = System.nanoTime() - startNanos;
     long millis = TimeUnit.MILLISECONDS.convert(
         durationNano, TimeUnit.NANOSECONDS);
-    assertTrue("Expected " + expectedMillis + "ms, but took " + millis,
-        Math.abs(millis - expectedMillis) < TIME_FUDGE_MILLIS);
+    assertTrue(Math.abs(millis - expectedMillis) < TIME_FUDGE_MILLIS,
+        "Expected " + expectedMillis + "ms, but took " + millis);
   }
   
   /**
@@ -209,10 +215,12 @@ public class TestNetUtils {
     assertNull(NetUtils.getLocalInetAddress(null));
   }
 
-  @Test(expected=UnknownHostException.class)
+  @Test
   public void testVerifyHostnamesException() throws UnknownHostException {
-    String[] names = {"valid.host.com", "1.com", "invalid host here"};
-    NetUtils.verifyHostnames(names);
+    assertThrows(UnknownHostException.class, ()->{
+      String[] names = {"valid.host.com", "1.com", "invalid host here"};
+      NetUtils.verifyHostnames(names);
+    });
   }  
 
   @Test
@@ -440,7 +448,7 @@ public class TestNetUtils {
   }
 
   private String extractExceptionMessage(Exception e) throws Throwable {
-    assertNotNull("Null Exception", e);
+    assertNotNull(e, "Null Exception");
     String message = e.getMessage();
     if (message == null) {
       throw new AssertionError("Empty text in exception " + e)
@@ -463,7 +471,7 @@ public class TestNetUtils {
   private IOException verifyExceptionClass(IOException e,
                                            Class expectedClass)
       throws Throwable {
-    assertNotNull("Null Exception", e);
+    assertNotNull(e, "Null Exception");
     IOException wrapped = NetUtils.wrapException("desthost", DEST_PORT,
          "localhost", LOCAL_PORT, e);
     LOG.info(wrapped.toString(), wrapped);
@@ -478,12 +486,12 @@ public class TestNetUtils {
   static NetUtilsTestResolver resolver;
   static Configuration config;
   
-  @BeforeClass
+  @BeforeAll
   public static void setupResolver() {
     resolver = NetUtilsTestResolver.install();
   }
   
-  @Before
+  @BeforeEach
   public void resetResolver() {
     resolver.reset();
     config = new Configuration();
@@ -729,7 +737,7 @@ public class TestNetUtils {
     try {
       InetAddress.getByName(oneHost);
     } catch (UnknownHostException e) {
-      Assume.assumeTrue("Network not resolving "+ oneHost, false);
+      assumeTrue(false, "Network not resolving " + oneHost);
     }
     List<String> hosts = Arrays.asList("127.0.0.1",
         "localhost", oneHost, "UnknownHost123");
@@ -737,17 +745,17 @@ public class TestNetUtils {
     String summary = "original [" + StringUtils.join(hosts, ", ") + "]"
         + " normalized [" + StringUtils.join(normalizedHosts, ", ") + "]";
     // when ipaddress is normalized, same address is expected in return
-    assertEquals(summary, hosts.get(0), normalizedHosts.get(0));
+    assertEquals(hosts.get(0), normalizedHosts.get(0), summary);
     // for normalizing a resolvable hostname, resolved ipaddress is expected in return
-    assertFalse("Element 1 equal "+ summary,
-        normalizedHosts.get(1).equals(hosts.get(1)));
-    assertEquals(summary, hosts.get(0), normalizedHosts.get(1));
+    assertFalse(normalizedHosts.get(1).equals(hosts.get(1)),
+        "Element 1 equal "+ summary);
+    assertEquals(hosts.get(0), normalizedHosts.get(1), summary);
     // this address HADOOP-8372: when normalizing a valid resolvable hostname start with numeric, 
     // its ipaddress is expected to return
-    assertFalse("Element 2 equal " + summary,
-        normalizedHosts.get(2).equals(hosts.get(2)));
+    assertFalse(normalizedHosts.get(2).equals(hosts.get(2)),
+        "Element 2 equal " + summary);
     // return the same hostname after normalizing a irresolvable hostname.
-    assertEquals(summary, hosts.get(3), normalizedHosts.get(3));
+    assertEquals(hosts.get(3), normalizedHosts.get(3), summary);
   }
   
   @Test

+ 9 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestNetworkTopologyWithNodeGroup.java

@@ -17,15 +17,15 @@
  */
 package org.apache.hadoop.net;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.util.HashMap;
 import java.util.Map;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestNetworkTopologyWithNodeGroup {
   private final static NetworkTopologyWithNodeGroup cluster = new 
@@ -182,13 +182,13 @@ public class TestNetworkTopologyWithNodeGroup {
   @Test
   public void testNodeGroup() throws Exception {
     String res = cluster.getNodeGroup("");
-    assertTrue("NodeGroup should be NodeBase.ROOT for empty location",
-        res.equals(NodeBase.ROOT));
+    assertTrue(res.equals(NodeBase.ROOT),
+        "NodeGroup should be NodeBase.ROOT for empty location");
     try {
       cluster.getNodeGroup(null);
     } catch (IllegalArgumentException e) {
-      assertTrue("Null Network Location should throw exception!",
-          e.getMessage().contains("Network Location is null"));
+      assertTrue(e.getMessage().contains("Network Location is null"),
+          "Null Network Location should throw exception!");
     }
   }
 

+ 12 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestScriptBasedMapping.java

@@ -19,8 +19,11 @@ package org.apache.hadoop.net;
 
 import java.util.ArrayList;
 import java.util.List;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.hadoop.conf.Configuration;
 
@@ -42,16 +45,16 @@ public class TestScriptBasedMapping {
     names.add("some.machine.name");
     names.add("other.machine.name");
     List<String> result = mapping.resolve(names);
-    assertNull("Expected an empty list", result);
+    assertNull(result, "Expected an empty list");
   }
 
   @Test
   public void testNoFilenameMeansSingleSwitch() throws Throwable {
     Configuration conf = new Configuration();
     ScriptBasedMapping mapping = createMapping(conf);
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
-    assertTrue("Expected to be single switch",
-               AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping));
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
+    assertTrue(AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping),
+        "Expected to be single switch");
   }
 
   @Test
@@ -59,15 +62,15 @@ public class TestScriptBasedMapping {
     Configuration conf = new Configuration();
     conf.set(ScriptBasedMapping.SCRIPT_FILENAME_KEY, "any-filename");
     ScriptBasedMapping mapping = createMapping(conf);
-    assertFalse("Expected to be multi switch", mapping.isSingleSwitch());
+    assertFalse(mapping.isSingleSwitch(), "Expected to be multi switch");
     mapping.setConf(new Configuration());
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
   }
 
   @Test
   public void testNullConfig() throws Throwable {
     ScriptBasedMapping mapping = createMapping(null);
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
 
   }
   private ScriptBasedMapping createMapping(Configuration conf) {

+ 13 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestScriptBasedMappingWithDependency.java

@@ -19,8 +19,11 @@ package org.apache.hadoop.net;
 
 import java.util.ArrayList;
 import java.util.List;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.hadoop.conf.Configuration;
 
@@ -46,18 +49,18 @@ public class TestScriptBasedMappingWithDependency {
     names.add("some.machine.name");
     names.add("other.machine.name");
     List<String> result = mapping.resolve(names);
-    assertNull("Expected an empty list for resolve", result);
+    assertNull(result, "Expected an empty list for resolve");
     result = mapping.getDependency("some.machine.name");
-    assertNull("Expected an empty list for getDependency", result);
+    assertNull(result, "Expected an empty list for getDependency");
   }
 
   @Test
   public void testNoFilenameMeansSingleSwitch() throws Throwable {
     Configuration conf = new Configuration();
     ScriptBasedMapping mapping = createMapping(conf);
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
-    assertTrue("Expected to be single switch",
-               AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping));
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
+    assertTrue(AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping),
+        "Expected to be single switch");
   }
 
   @Test
@@ -65,15 +68,15 @@ public class TestScriptBasedMappingWithDependency {
     Configuration conf = new Configuration();
     conf.set(ScriptBasedMapping.SCRIPT_FILENAME_KEY, "any-filename");
     ScriptBasedMapping mapping = createMapping(conf);
-    assertFalse("Expected to be multi switch", mapping.isSingleSwitch());
+    assertFalse(mapping.isSingleSwitch(), "Expected to be multi switch");
     mapping.setConf(new Configuration());
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
   }
 
   @Test
   public void testNullConfig() throws Throwable {
     ScriptBasedMapping mapping = createMapping(null);
-    assertTrue("Expected to be single switch", mapping.isSingleSwitch());
+    assertTrue(mapping.isSingleSwitch(), "Expected to be single switch");
   }
 
   private ScriptBasedMappingWithDependency createMapping(Configuration conf) {

+ 6 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestSocketIOWithTimeout.java

@@ -38,11 +38,15 @@ import org.apache.hadoop.util.Time;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.io.nativeio.NativeIO;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 /**
  * This tests timeout out from SocketInputStream and

+ 14 - 19
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestStaticMapping.java

@@ -20,8 +20,8 @@ package org.apache.hadoop.net;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -33,7 +33,7 @@ import java.util.Map;
  * Test the static mapping class.
  * Because the map is actually static, this map needs to be reset for every test
  */
-public class TestStaticMapping extends Assert {
+public class TestStaticMapping extends Assertions {
   private static final Logger LOG =
       LoggerFactory.getLogger(TestStaticMapping.class);
 
@@ -78,23 +78,18 @@ public class TestStaticMapping extends Assert {
   }
 
   private void assertSingleSwitch(DNSToSwitchMapping mapping) {
-    assertEquals("Expected a single switch mapping "
-                     + mapping,
-                 true,
-                 AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping));
+    assertEquals(true, AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping),
+        "Expected a single switch mapping " + mapping);
   }
 
   private void assertMultiSwitch(DNSToSwitchMapping mapping) {
-    assertEquals("Expected a multi switch mapping "
-                     + mapping,
-                 false,
-                 AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping));
+    assertEquals(false, AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping),
+        "Expected a multi switch mapping " + mapping);
   }
 
   protected void assertMapSize(AbstractDNSToSwitchMapping switchMapping, int expectedSize) {
-    assertEquals(
-        "Expected two entries in the map " + switchMapping.dumpTopology(),
-        expectedSize, switchMapping.getSwitchMap().size());
+    assertEquals(expectedSize, switchMapping.getSwitchMap().size(),
+        "Expected two entries in the map " + switchMapping.dumpTopology());
   }
 
   private List<String> createQueryList() {
@@ -130,8 +125,8 @@ public class TestStaticMapping extends Assert {
     Map<String, String> switchMap = mapping.getSwitchMap();
     String topology = mapping.dumpTopology();
     LOG.info(topology);
-    assertEquals(topology, 1, switchMap.size());
-    assertEquals(topology, "/r1", switchMap.get("n1"));
+    assertEquals(1, switchMap.size(), topology);
+    assertEquals("/r1", switchMap.get("n1"), topology);
   }
 
   /**
@@ -160,9 +155,9 @@ public class TestStaticMapping extends Assert {
     Map<String, String> switchMap = mapping.getSwitchMap();
     String topology = mapping.dumpTopology();
     LOG.info(topology);
-    assertEquals(topology, 2, switchMap.size());
-    assertEquals(topology, "/r1", switchMap.get("n1"));
-    assertNull(topology, switchMap.get("unknown"));
+    assertEquals(2, switchMap.size(), topology);
+    assertEquals("/r1", switchMap.get("n1"), topology);
+    assertNull(switchMap.get("unknown"), topology);
   }
 
 

+ 15 - 17
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestSwitchMapping.java

@@ -20,15 +20,15 @@ package org.apache.hadoop.net;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
 
 import java.util.List;
 
 /**
  * Test some other details of the switch mapping
  */
-public class TestSwitchMapping extends Assert {
+public class TestSwitchMapping extends Assertions {
 
 
   /**
@@ -40,8 +40,8 @@ public class TestSwitchMapping extends Assert {
   @Test
   public void testStandaloneClassesAssumedMultiswitch() throws Throwable {
     DNSToSwitchMapping mapping = new StandaloneSwitchMapping();
-    assertFalse("Expected to be multi switch " + mapping,
-                AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping));
+    assertFalse(AbstractDNSToSwitchMapping.isMappingSingleSwitch(mapping),
+        "Expected to be multi switch " + mapping);
   }
 
 
@@ -55,8 +55,8 @@ public class TestSwitchMapping extends Assert {
   public void testCachingRelays() throws Throwable {
     CachedDNSToSwitchMapping mapping =
         new CachedDNSToSwitchMapping(new StandaloneSwitchMapping());
-    assertFalse("Expected to be multi switch " + mapping,
-                mapping.isSingleSwitch());
+    assertFalse(mapping.isSingleSwitch(),
+        "Expected to be multi switch " + mapping);
   }
 
 
@@ -73,12 +73,12 @@ public class TestSwitchMapping extends Assert {
     conf.set(CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY,
              scriptname);
     ScriptBasedMapping scriptMapping = new ScriptBasedMapping(conf);
-    assertTrue("Did not find " + scriptname + " in " + scriptMapping,
-               scriptMapping.toString().contains(scriptname));
+    assertTrue(scriptMapping.toString().contains(scriptname),
+        "Did not find " + scriptname + " in " + scriptMapping);
     CachedDNSToSwitchMapping mapping =
         new CachedDNSToSwitchMapping(scriptMapping);
-    assertTrue("Did not find " + scriptname + " in " + mapping,
-               mapping.toString().contains(scriptname));
+    assertTrue(mapping.toString().contains(scriptname),
+        "Did not find " + scriptname + " in " + mapping);
   }
 
   /**
@@ -91,14 +91,12 @@ public class TestSwitchMapping extends Assert {
   public void testCachingRelaysStringOperationsToNullScript() throws Throwable {
     Configuration conf = new Configuration();
     ScriptBasedMapping scriptMapping = new ScriptBasedMapping(conf);
-    assertTrue("Did not find " + ScriptBasedMapping.NO_SCRIPT
-                   + " in " + scriptMapping,
-               scriptMapping.toString().contains(ScriptBasedMapping.NO_SCRIPT));
+    assertTrue(scriptMapping.toString().contains(ScriptBasedMapping.NO_SCRIPT),
+        "Did not find " + ScriptBasedMapping.NO_SCRIPT + " in " + scriptMapping);
     CachedDNSToSwitchMapping mapping =
         new CachedDNSToSwitchMapping(scriptMapping);
-    assertTrue("Did not find " + ScriptBasedMapping.NO_SCRIPT
-                   + " in " + mapping,
-               mapping.toString().contains(ScriptBasedMapping.NO_SCRIPT));
+    assertTrue(mapping.toString().contains(ScriptBasedMapping.NO_SCRIPT),
+        "Did not find " + ScriptBasedMapping.NO_SCRIPT + " in " + mapping);
   }
 
   @Test

+ 5 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestTableMapping.java

@@ -19,7 +19,7 @@ package org.apache.hadoop.net;
 
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.NET_TOPOLOGY_TABLE_MAPPING_FILE_KEY;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import org.apache.hadoop.thirdparty.com.google.common.io.Files;
 
@@ -31,7 +31,8 @@ import java.util.List;
 
 import org.apache.hadoop.conf.Configuration;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class TestTableMapping {
   private String hostName1 = "1.2.3.4";
@@ -162,7 +163,8 @@ public class TestTableMapping {
   }
 
 
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testBadFile() throws IOException {
     File mapFile = File.createTempFile(getClass().getSimpleName() +
         ".testBadFile", ".txt");

+ 70 - 47
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/unix/TestDomainSocket.java

@@ -37,12 +37,11 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.net.unix.DomainSocket.DomainChannel;
@@ -51,23 +50,30 @@ import org.apache.hadoop.util.Shell;
 
 import org.apache.hadoop.thirdparty.com.google.common.io.Files;
 
+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.junit.jupiter.api.Assumptions.assumeTrue;
+
 public class TestDomainSocket {
   private static TemporarySocketDirectory sockDir;
 
-  @BeforeClass
+  @BeforeAll
   public static void init() {
     sockDir = new TemporarySocketDirectory();
     DomainSocket.disableBindPathValidation();
   }
 
-  @AfterClass
+  @AfterAll
   public static void shutdown() throws IOException {
     sockDir.close();
   }
   
-  @Before
+  @BeforeEach
   public void before() {
-    Assume.assumeTrue(DomainSocket.getLoadingFailureReason() == null);
+    assumeTrue(DomainSocket.getLoadingFailureReason() == null);
   }
     
   /**
@@ -76,7 +82,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testSocketCreateAndClose() throws IOException {
     DomainSocket serv = DomainSocket.bindAndListen(
       new File(sockDir.getDir(), "test_sock_create_and_close").
@@ -89,9 +96,10 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testSocketPathSetGet() throws IOException {
-    Assert.assertEquals("/var/run/hdfs/sock.100",
+    assertEquals("/var/run/hdfs/sock.100",
         DomainSocket.getEffectivePath("/var/run/hdfs/sock._PORT", 100));
   }
 
@@ -100,7 +108,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testSocketReadEof() throws Exception {
     final String TEST_PATH = new File(sockDir.getDir(),
         "testSocketReadEof").getAbsolutePath();
@@ -119,7 +128,7 @@ public class TestDomainSocket {
           buf[i] = 0;
         }
         try {
-          Assert.assertEquals(-1, conn.getInputStream().read());
+          assertEquals(-1, conn.getInputStream().read());
         } catch (IOException e) {
           throw new RuntimeException("unexpected IOException", e);
         }
@@ -140,7 +149,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testSocketAcceptAndClose() throws Exception {
     final String TEST_PATH =
         new File(sockDir.getDir(), "test_sock_accept_and_close").getAbsolutePath();
@@ -245,12 +255,14 @@ public class TestDomainSocket {
     serverFuture.get(2, TimeUnit.MINUTES);
   }
   
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testAsyncCloseDuringWrite() throws Exception {
     testAsyncCloseDuringIO(true);
   }
   
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testAsyncCloseDuringRead() throws Exception {
     testAsyncCloseDuringIO(false);
   }
@@ -260,7 +272,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testInvalidOperations() throws IOException {
     try {
       DomainSocket.connect(
@@ -276,7 +289,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testServerOptions() throws Exception {
     final String TEST_PATH = new File(sockDir.getDir(),
         "test_sock_server_options").getAbsolutePath();
@@ -286,19 +300,19 @@ public class TestDomainSocket {
     int newBufSize = bufSize / 2;
     serv.setAttribute(DomainSocket.RECEIVE_BUFFER_SIZE, newBufSize);
     int nextBufSize = serv.getAttribute(DomainSocket.RECEIVE_BUFFER_SIZE);
-    Assert.assertEquals(newBufSize, nextBufSize);
+    assertEquals(newBufSize, nextBufSize);
     // Let's set a server timeout
     int newTimeout = 1000;
     serv.setAttribute(DomainSocket.RECEIVE_TIMEOUT, newTimeout);
     int nextTimeout = serv.getAttribute(DomainSocket.RECEIVE_TIMEOUT);
-    Assert.assertEquals(newTimeout, nextTimeout);
+    assertEquals(newTimeout, nextTimeout);
 
     ExecutorService exeServ = Executors.newSingleThreadExecutor();
     Callable<Void> callable = new Callable<Void>() {
       public Void call() {
         try {
           serv.accept();
-          Assert.fail("expected the accept() to time out and fail");
+          fail("expected the accept() to time out and fail");
         } catch (SocketTimeoutException e) {
           GenericTestUtils.assertExceptionContains("accept(2) error: ", e);
         } catch (AsynchronousCloseException e) {
@@ -313,7 +327,7 @@ public class TestDomainSocket {
     Thread.sleep(500);
     serv.close(true);
     future.get();
-    Assert.assertFalse(serv.isOpen());
+    assertFalse(serv.isOpen());
   }
   
   /**
@@ -454,17 +468,17 @@ public class TestDomainSocket {
           ReadStrategy reader = readStrategyClass.newInstance();
           reader.init(conn);
           reader.readFully(in1, 0, in1.length);
-          Assert.assertTrue(Arrays.equals(clientMsg1, in1));
+          assertTrue(Arrays.equals(clientMsg1, in1));
           WriteStrategy writer = writeStrategyClass.newInstance();
           writer.init(conn);
           writer.write(serverMsg1);
           InputStream connInputStream = conn.getInputStream();
           int in2 = connInputStream.read();
-          Assert.assertEquals((int)clientMsg2, in2);
+          assertEquals((int)clientMsg2, in2);
           conn.close();
         } catch (Throwable e) {
           threadResults.add(e);
-          Assert.fail(e.getMessage());
+          fail(e.getMessage());
         }
         threadResults.add(new Success());
       }
@@ -483,7 +497,7 @@ public class TestDomainSocket {
           reader.init(client);
           byte in1[] = new byte[serverMsg1.length];
           reader.readFully(in1, 0, in1.length);
-          Assert.assertTrue(Arrays.equals(serverMsg1, in1));
+          assertTrue(Arrays.equals(serverMsg1, in1));
           OutputStream clientOutputStream = client.getOutputStream();
           clientOutputStream.write(clientMsg2);
           client.close();
@@ -498,7 +512,7 @@ public class TestDomainSocket {
     for (int i = 0; i < 2; i++) {
       Throwable t = threadResults.take();
       if (!(t instanceof Success)) {
-        Assert.fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
+        fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
       }
     }
     serverThread.join(120000);
@@ -508,37 +522,43 @@ public class TestDomainSocket {
     }
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInStream() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         InputStreamReadStrategy.class, null);
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInStreamWithSocketpair() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         InputStreamReadStrategy.class, DomainSocket.socketpair());
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInDbb() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         DirectByteBufferReadStrategy.class, null);
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInDbbWithSocketpair() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         DirectByteBufferReadStrategy.class, DomainSocket.socketpair());
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInAbb() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         ArrayBackedByteBufferReadStrategy.class, null);
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testClientServerOutStreamInAbbWithSocketpair() throws Exception {
     testClientServer1(OutputStreamWriteStrategy.class,
         ArrayBackedByteBufferReadStrategy.class, DomainSocket.socketpair());
@@ -589,7 +609,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testFdPassing() throws Exception {
     final String TEST_PATH =
         new File(sockDir.getDir(), "test_sock").getAbsolutePath();
@@ -614,14 +635,14 @@ public class TestDomainSocket {
           byte in1[] = new byte[clientMsg1.length];
           InputStream connInputStream = conn.getInputStream();
           IOUtils.readFully(connInputStream, in1, 0, in1.length);
-          Assert.assertTrue(Arrays.equals(clientMsg1, in1));
+          assertTrue(Arrays.equals(clientMsg1, in1));
           DomainSocket domainConn = (DomainSocket)conn;
           domainConn.sendFileDescriptors(passedFds, serverMsg1, 0,
               serverMsg1.length);
           conn.close();
         } catch (Throwable e) {
           threadResults.add(e);
-          Assert.fail(e.getMessage());
+          fail(e.getMessage());
         }
         threadResults.add(new Success());
       }
@@ -640,11 +661,11 @@ public class TestDomainSocket {
           FileInputStream recvFis[] = new FileInputStream[passedFds.length];
           int r = domainConn.
               recvFileInputStreams(recvFis, in1, 0, in1.length - 1);
-          Assert.assertTrue(r > 0);
+          assertTrue(r > 0);
           IOUtils.readFully(clientInputStream, in1, r, in1.length - r);
-          Assert.assertTrue(Arrays.equals(serverMsg1, in1));
+          assertTrue(Arrays.equals(serverMsg1, in1));
           for (int i = 0; i < passedFds.length; i++) {
-            Assert.assertNotNull(recvFis[i]);
+            assertNotNull(recvFis[i]);
             passedFiles[i].checkInputStream(recvFis[i]);
           }
           for (FileInputStream fis : recvFis) {
@@ -662,7 +683,7 @@ public class TestDomainSocket {
     for (int i = 0; i < 2; i++) {
       Throwable t = threadResults.take();
       if (!(t instanceof Success)) {
-        Assert.fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
+        fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
       }
     }
     serverThread.join(120000);
@@ -700,7 +721,8 @@ public class TestDomainSocket {
    *
    * @throws IOException
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testFdPassingPathSecurity() throws Exception {
     TemporarySocketDirectory tmp = new TemporarySocketDirectory();
     try {
@@ -739,7 +761,8 @@ public class TestDomainSocket {
     }
   }
 
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testShutdown() throws Exception {
     final AtomicInteger bytesRead = new AtomicInteger(0);
     final AtomicBoolean failed = new AtomicBoolean(false);
@@ -765,11 +788,11 @@ public class TestDomainSocket {
     socks[0].getOutputStream().write(1);
     socks[0].getOutputStream().write(2);
     socks[0].getOutputStream().write(3);
-    Assert.assertTrue(readerThread.isAlive());
+    assertTrue(readerThread.isAlive());
     socks[0].shutdown();
     readerThread.join();
-    Assert.assertFalse(failed.get());
-    Assert.assertEquals(3, bytesRead.get());
+    assertFalse(failed.get());
+    assertEquals(3, bytesRead.get());
     IOUtils.cleanupWithLogger(null, socks);
   }
 }

+ 22 - 14
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/unix/TestDomainSocketWatcher.java

@@ -17,7 +17,7 @@
  */
 package org.apache.hadoop.net.unix;
 
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 
 import java.util.ArrayList;
 import java.util.Random;
@@ -26,27 +26,29 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.ReentrantLock;
 
-import org.junit.After;
-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;
 
 import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.Uninterruptibles;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
 public class TestDomainSocketWatcher {
   static final Logger LOG =
       LoggerFactory.getLogger(TestDomainSocketWatcher.class);
 
   private Throwable trappedException = null;
 
-  @Before
+  @BeforeEach
   public void before() {
-    Assume.assumeTrue(DomainSocket.getLoadingFailureReason() == null);
+    assumeTrue(DomainSocket.getLoadingFailureReason() == null);
   }
 
-  @After
+  @AfterEach
   public void after() {
     if (trappedException != null) {
       throw new IllegalStateException(
@@ -58,7 +60,8 @@ public class TestDomainSocketWatcher {
   /**
    * Test that we can create a DomainSocketWatcher and then shut it down.
    */
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testCreateShutdown() throws Exception {
     DomainSocketWatcher watcher = newDomainSocketWatcher(10000000);
     watcher.close();
@@ -67,7 +70,8 @@ public class TestDomainSocketWatcher {
   /**
    * Test that we can get notifications out a DomainSocketWatcher.
    */
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testDeliverNotifications() throws Exception {
     DomainSocketWatcher watcher = newDomainSocketWatcher(10000000);
     DomainSocket pair[] = DomainSocket.socketpair();
@@ -87,7 +91,8 @@ public class TestDomainSocketWatcher {
   /**
    * Test that a java interruption can stop the watcher thread
    */
-  @Test(timeout=60000)
+  @Test
+  @Timeout(value = 60)
   public void testInterruption() throws Exception {
     final DomainSocketWatcher watcher = newDomainSocketWatcher(10);
     watcher.watcherThread.interrupt();
@@ -98,7 +103,8 @@ public class TestDomainSocketWatcher {
   /**
    * Test that domain sockets are closed when the watcher is closed.
    */
-  @Test(timeout=300000)
+  @Test
+  @Timeout(value = 300)
   public void testCloseSocketOnWatcherClose() throws Exception {
     final DomainSocketWatcher watcher = newDomainSocketWatcher(10000000);
     DomainSocket pair[] = DomainSocket.socketpair();
@@ -113,7 +119,8 @@ public class TestDomainSocketWatcher {
     assertFalse(pair[1].isOpen());
   }
   
-  @Test(timeout=300000)
+  @Test
+  @Timeout(value = 300)
   public void testStress() throws Exception {
     final int SOCKET_NUM = 250;
     final ReentrantLock lock = new ReentrantLock();
@@ -183,7 +190,8 @@ public class TestDomainSocketWatcher {
     watcher.close();
   }
 
-  @Test(timeout = 300000)
+  @Test
+  @Timeout(value = 300)
   public void testStressInterruption() throws Exception {
     final int SOCKET_NUM = 250;
     final ReentrantLock lock = new ReentrantLock();

+ 10 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestFrameDecoder.java

@@ -18,9 +18,9 @@
 
 package org.apache.hadoop.oncrpc;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -35,10 +35,11 @@ import org.apache.hadoop.oncrpc.RpcUtil.RpcFrameDecoder;
 import org.apache.hadoop.oncrpc.security.CredentialsNone;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
 import org.slf4j.event.Level;
 
+import static org.mockito.Mockito.mock;
+
 public class TestFrameDecoder {
 
   static {
@@ -103,7 +104,7 @@ public class TestFrameDecoder {
     ByteBuf buf = Unpooled.directBuffer(1);
     List<Object> outputBufs = new ArrayList<>();
     decoder.decode(
-        Mockito.mock(ChannelHandlerContext.class), buf,
+        mock(ChannelHandlerContext.class), buf,
         outputBufs);
     assertTrue(outputBufs.isEmpty());
 
@@ -122,7 +123,7 @@ public class TestFrameDecoder {
     buf.writeBytes(fragment);
     outputBufs = new ArrayList<>();
     decoder.decode(
-        Mockito.mock(ChannelHandlerContext.class), buf,
+        mock(ChannelHandlerContext.class), buf,
         outputBufs);
     assertTrue(decoder.isLast());
     buf.release();
@@ -147,7 +148,7 @@ public class TestFrameDecoder {
     ByteBuf buf = Unpooled.directBuffer(4 + 10, 4 + 10);
     buf.writeBytes(fragment1);
     decoder.decode(
-        Mockito.mock(ChannelHandlerContext.class), buf,
+        mock(ChannelHandlerContext.class), buf,
         outputBufs);
 
     byte[] fragment2 = new byte[4 + 10];
@@ -162,7 +163,7 @@ public class TestFrameDecoder {
     buf = Unpooled.directBuffer(4 + 10, 4 + 10);
     buf.writeBytes(fragment2);
     decoder.decode(
-        Mockito.mock(ChannelHandlerContext.class), buf,
+        mock(ChannelHandlerContext.class), buf,
         outputBufs);
     // Expect two completed frames each 10 bytes
     decoder.isLast();

+ 6 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcAcceptedReply.java

@@ -17,13 +17,14 @@
  */
 package org.apache.hadoop.oncrpc;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import org.apache.hadoop.oncrpc.RpcAcceptedReply.AcceptState;
 import org.apache.hadoop.oncrpc.RpcReply.ReplyState;
 import org.apache.hadoop.oncrpc.security.Verifier;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Test for {@link RpcAcceptedReply}
@@ -39,9 +40,10 @@ public class TestRpcAcceptedReply {
     assertEquals(AcceptState.SYSTEM_ERR, AcceptState.fromValue(5));
   }
 
-  @Test(expected = IndexOutOfBoundsException.class)
+  @Test
   public void testAcceptStateFromInvalidValue() {
-    AcceptState.fromValue(6);
+    assertThrows(IndexOutOfBoundsException.class, () ->
+        AcceptState.fromValue(6));
   }
 
   @Test

+ 14 - 8
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcCall.java

@@ -17,13 +17,14 @@
  */
 package org.apache.hadoop.oncrpc;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import org.apache.hadoop.oncrpc.security.CredentialsNone;
 import org.apache.hadoop.oncrpc.security.Credentials;
 import org.apache.hadoop.oncrpc.security.Verifier;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Tests for {@link RpcCall}
@@ -50,15 +51,20 @@ public class TestRpcCall {
     assertEquals(verifier, call.getVerifier());
   }
 
-  @Test(expected=IllegalArgumentException.class)
+  @Test
   public void testInvalidRpcVersion() {
-    int invalidRpcVersion = 3;
-    new RpcCall(0, RpcMessage.Type.RPC_CALL, invalidRpcVersion, 2, 3, 4, null, null);
+    assertThrows(IllegalArgumentException.class, () -> {
+      int invalidRpcVersion = 3;
+      new RpcCall(0, RpcMessage.Type.RPC_CALL, invalidRpcVersion, 2, 3, 4, null, null);
+    });
   }
 
-  @Test(expected=IllegalArgumentException.class)
+  @Test
   public void testInvalidRpcMessageType() {
-    RpcMessage.Type invalidMessageType = RpcMessage.Type.RPC_REPLY; // Message typ is not RpcMessage.RPC_CALL
-    new RpcCall(0, invalidMessageType, RpcCall.RPC_VERSION, 2, 3, 4, null, null);
+    assertThrows(IllegalArgumentException.class, () -> {
+      // Message typ is not RpcMessage.RPC_CALL
+      RpcMessage.Type invalidMessageType = RpcMessage.Type.RPC_REPLY;
+      new RpcCall(0, invalidMessageType, RpcCall.RPC_VERSION, 2, 3, 4, null, null);
+    });
   }
 }

+ 16 - 14
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcCallCache.java

@@ -17,12 +17,6 @@
  */
 package org.apache.hadoop.oncrpc;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.Iterator;
@@ -30,23 +24,31 @@ import java.util.Map.Entry;
 
 import org.apache.hadoop.oncrpc.RpcCallCache.CacheEntry;
 import org.apache.hadoop.oncrpc.RpcCallCache.ClientRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+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.assertTrue;
+import static org.mockito.Mockito.mock;
 
 /**
  * Unit tests for {@link RpcCallCache}
  */
 public class TestRpcCallCache {
 
-  @Test(expected=IllegalArgumentException.class)
-  public void testRpcCallCacheConstructorIllegalArgument0(){
-    new RpcCallCache("test", 0);
+  @Test
+  public void testRpcCallCacheConstructorIllegalArgument0() {
+    assertThrows(IllegalArgumentException.class, () ->
+        new RpcCallCache("test", 0));
   }
 
-  @Test(expected=IllegalArgumentException.class)
-  public void testRpcCallCacheConstructorIllegalArgumentNegative(){
-    new RpcCallCache("test", -1);
+  @Test
+  public void testRpcCallCacheConstructorIllegalArgumentNegative() {
+    assertThrows(IllegalArgumentException.class, () ->
+        new RpcCallCache("test", -1));
   }
 
   @Test

+ 13 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcDeniedReply.java

@@ -20,8 +20,10 @@ package org.apache.hadoop.oncrpc;
 import org.apache.hadoop.oncrpc.RpcDeniedReply.RejectState;
 import org.apache.hadoop.oncrpc.RpcReply.ReplyState;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Test for {@link RpcDeniedReply}
@@ -29,22 +31,23 @@ import org.junit.Test;
 public class TestRpcDeniedReply {
   @Test
   public void testRejectStateFromValue() {
-    Assert.assertEquals(RejectState.RPC_MISMATCH, RejectState.fromValue(0));
-    Assert.assertEquals(RejectState.AUTH_ERROR, RejectState.fromValue(1));
+    assertEquals(RejectState.RPC_MISMATCH, RejectState.fromValue(0));
+    assertEquals(RejectState.AUTH_ERROR, RejectState.fromValue(1));
   }
 
-  @Test(expected=IndexOutOfBoundsException.class)
+  @Test
   public void testRejectStateFromInvalidValue1() {
-    RejectState.fromValue(2);
+    assertThrows(IndexOutOfBoundsException.class, () ->
+        RejectState.fromValue(2));
   }
 
   @Test
   public void testConstructor() {
     RpcDeniedReply reply = new RpcDeniedReply(0, ReplyState.MSG_ACCEPTED,
         RejectState.AUTH_ERROR, new VerifierNone());
-    Assert.assertEquals(0, reply.getXid());
-    Assert.assertEquals(RpcMessage.Type.RPC_REPLY, reply.getMessageType());
-    Assert.assertEquals(ReplyState.MSG_ACCEPTED, reply.getState());
-    Assert.assertEquals(RejectState.AUTH_ERROR, reply.getRejectState());
+    assertEquals(0, reply.getXid());
+    assertEquals(RpcMessage.Type.RPC_REPLY, reply.getMessageType());
+    assertEquals(ReplyState.MSG_ACCEPTED, reply.getState());
+    assertEquals(RejectState.AUTH_ERROR, reply.getRejectState());
   }
 }

+ 11 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcMessage.java

@@ -17,8 +17,10 @@
  */
 package org.apache.hadoop.oncrpc;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Test for {@link RpcMessage}
@@ -36,8 +38,8 @@ public class TestRpcMessage {
   @Test
   public void testRpcMessage() {
     RpcMessage msg = getRpcMessage(0, RpcMessage.Type.RPC_CALL);
-    Assert.assertEquals(0, msg.getXid());
-    Assert.assertEquals(RpcMessage.Type.RPC_CALL, msg.getMessageType());
+    assertEquals(0, msg.getXid());
+    assertEquals(RpcMessage.Type.RPC_CALL, msg.getMessageType());
   }
 
   @Test
@@ -46,9 +48,11 @@ public class TestRpcMessage {
     msg.validateMessageType(RpcMessage.Type.RPC_CALL);
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testValidateMessageException() {
-    RpcMessage msg = getRpcMessage(0, RpcMessage.Type.RPC_CALL);
-    msg.validateMessageType(RpcMessage.Type.RPC_REPLY);
+    assertThrows(IllegalArgumentException.class, () -> {
+      RpcMessage msg = getRpcMessage(0, RpcMessage.Type.RPC_CALL);
+      msg.validateMessageType(RpcMessage.Type.RPC_REPLY);
+    });
   }
 }

+ 11 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestRpcReply.java

@@ -20,8 +20,10 @@ package org.apache.hadoop.oncrpc;
 
 import org.apache.hadoop.oncrpc.RpcReply.ReplyState;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Test for {@link RpcReply}
@@ -29,13 +31,13 @@ import org.junit.Test;
 public class TestRpcReply {
   @Test
   public void testReplyStateFromValue() {
-    Assert.assertEquals(ReplyState.MSG_ACCEPTED, ReplyState.fromValue(0));
-    Assert.assertEquals(ReplyState.MSG_DENIED, ReplyState.fromValue(1));
+    assertEquals(ReplyState.MSG_ACCEPTED, ReplyState.fromValue(0));
+    assertEquals(ReplyState.MSG_DENIED, ReplyState.fromValue(1));
   }
 
-  @Test(expected=IndexOutOfBoundsException.class)
+  @Test
   public void testReplyStateFromInvalidValue1() {
-    ReplyState.fromValue(2);
+    assertThrows(IndexOutOfBoundsException.class, () -> ReplyState.fromValue(2));
   }
 
   @Test
@@ -47,8 +49,8 @@ public class TestRpcReply {
             return null;
           }
     };
-    Assert.assertEquals(0, reply.getXid());
-    Assert.assertEquals(RpcMessage.Type.RPC_REPLY, reply.getMessageType());
-    Assert.assertEquals(ReplyState.MSG_ACCEPTED, reply.getState());
+    assertEquals(0, reply.getXid());
+    assertEquals(RpcMessage.Type.RPC_REPLY, reply.getMessageType());
+    assertEquals(ReplyState.MSG_ACCEPTED, reply.getState());
   }
 }

+ 5 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/TestXDR.java

@@ -17,8 +17,9 @@
  */
 package org.apache.hadoop.oncrpc;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestXDR {
   static final int WRITE_VALUE=23;
@@ -29,8 +30,7 @@ public class TestXDR {
 
     XDR r = w.asReadOnlyWrap();
     for (int i = 0; i < times; ++i)
-      Assert.assertEquals(
-              WRITE_VALUE,r.readInt());
+      assertEquals(WRITE_VALUE, r.readInt());
   }
 
   private void serializeLong(int times) {
@@ -40,7 +40,7 @@ public class TestXDR {
 
     XDR r = w.asReadOnlyWrap();
     for (int i = 0; i < times; ++i)
-      Assert.assertEquals(WRITE_VALUE, r.readHyper());
+      assertEquals(WRITE_VALUE, r.readHyper());
   }
 
   @Test

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/security/TestCredentialsSys.java

@@ -17,11 +17,11 @@
  */
 package org.apache.hadoop.oncrpc.security;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import org.apache.hadoop.oncrpc.XDR;
 import org.apache.hadoop.oncrpc.security.CredentialsSys;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Test for {@link CredentialsSys}

+ 6 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/security/TestRpcAuthInfo.java

@@ -17,11 +17,12 @@
  */
 package org.apache.hadoop.oncrpc.security;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import org.apache.hadoop.oncrpc.security.RpcAuthInfo;
 import org.apache.hadoop.oncrpc.security.RpcAuthInfo.AuthFlavor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Tests for {@link RpcAuthInfo}
@@ -36,8 +37,9 @@ public class TestRpcAuthInfo {
     assertEquals(AuthFlavor.RPCSEC_GSS, AuthFlavor.fromValue(6));
   }
 
-  @Test(expected=IllegalArgumentException.class)
+  @Test
   public void testInvalidAuthFlavor() {
-    assertEquals(AuthFlavor.AUTH_NONE, AuthFlavor.fromValue(4));
+    assertThrows(IllegalArgumentException.class, ()->
+        assertEquals(AuthFlavor.AUTH_NONE, AuthFlavor.fromValue(4)));
   }
 }

+ 16 - 13
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/portmap/TestPortmap.java

@@ -27,17 +27,18 @@ import java.util.Arrays;
 import java.util.Map;
 
 import org.apache.hadoop.oncrpc.RpcReply;
-import org.junit.Assert;
 
 import org.apache.hadoop.oncrpc.RpcCall;
 import org.apache.hadoop.oncrpc.XDR;
 import org.apache.hadoop.oncrpc.security.CredentialsNone;
 import org.apache.hadoop.oncrpc.security.VerifierNone;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestPortmap {
   private static Portmap pm = new Portmap();
@@ -45,18 +46,19 @@ public class TestPortmap {
   private static final int RETRY_TIMES = 5;
   private int xid;
 
-  @BeforeClass
+  @BeforeAll
   public static void setup() throws InterruptedException {
     pm.start(SHORT_TIMEOUT_MILLISECONDS, new InetSocketAddress("localhost", 0),
         new InetSocketAddress("localhost", 0));
   }
 
-  @AfterClass
+  @AfterAll
   public static void tearDown() {
     pm.shutdown();
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testIdle() throws InterruptedException, IOException {
     Socket s = new Socket();
     try {
@@ -68,17 +70,18 @@ public class TestPortmap {
         Thread.sleep(SHORT_TIMEOUT_MILLISECONDS);
       }
 
-      Assert.assertTrue("Failed to connect to the server", s.isConnected()
-          && i < RETRY_TIMES);
+      assertTrue(s.isConnected() && i < RETRY_TIMES,
+          "Failed to connect to the server");
 
       int b = s.getInputStream().read();
-      Assert.assertTrue("The server failed to disconnect", b == -1);
+      assertTrue(b == -1, "The server failed to disconnect");
     } finally {
       s.close();
     }
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testRegistration() throws IOException, InterruptedException, IllegalAccessException {
     XDR req = new XDR();
     RpcCall.getInstance(++xid, RpcProgramPortmap.PROGRAM,
@@ -125,6 +128,6 @@ public class TestPortmap {
         break;
       }
     }
-    Assert.assertTrue("Registration failed", found);
+    assertTrue(found, "Registration failed");
   }
 }

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ManualTestKeytabLogins.java

@@ -18,7 +18,7 @@
 package org.apache.hadoop.security;
 
 import org.apache.hadoop.security.UserGroupInformation;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * Regression test for HADOOP-6947 which can be run manually in

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestAuthenticationFilter.java

@@ -16,15 +16,15 @@
  */
 package org.apache.hadoop.security;
 
-
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.mockito.ArgumentMatchers.any;
 
 import org.apache.hadoop.http.HttpServer2;
 import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.http.FilterContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestCompositeGroupMapping.java

@@ -17,7 +17,7 @@
  */
 package org.apache.hadoop.security;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
 import java.util.ArrayList;
@@ -29,7 +29,7 @@ import java.util.Set;
 import org.apache.hadoop.conf.Configurable;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 44 - 46
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestCredentials.java

@@ -42,21 +42,24 @@ import org.apache.hadoop.io.Text;
 import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.security.token.TokenIdentifier;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestCredentials {
   private static final String DEFAULT_HMAC_ALGORITHM = "HmacSHA1";
   private static final File tmpDir = GenericTestUtils.getTestDir("mapred");
 
-  @Before
+  @BeforeEach
   public void setUp() {
     tmpDir.mkdir();
   }
 
-  @After
+  @AfterEach
   public void tearDown() {
     tmpDir.delete();
   }
@@ -111,29 +114,27 @@ public class TestCredentials {
 
     // get the tokens and compare the services
     Map<Text, Token<? extends TokenIdentifier>> tokenMap = ts.getTokenMap();
-    assertEquals("getTokenMap should return collection of size 2", 2,
-        tokenMap.size());
-    assertTrue("Token for alias " + alias1 + " must be present",
-        tokenMap.containsKey(alias1));
-    assertTrue("Token for alias " + alias2 + " must be present",
-        tokenMap.containsKey(alias2));
-    assertEquals("Token for service " + service1 + " must be present", service1,
-        tokenMap.get(alias1).getService());
-    assertEquals("Token for service " + service2 + " must be present", service2,
-        tokenMap.get(alias2).getService());
+    assertEquals(2, tokenMap.size(),
+        "getTokenMap should return collection of size 2");
+    assertTrue(tokenMap.containsKey(alias1),
+        "Token for alias " + alias1 + " must be present");
+    assertTrue(tokenMap.containsKey(alias2), "Token for alias " + alias2 + " must be present");
+    assertEquals(service1, tokenMap.get(alias1).getService(),
+        "Token for service " + service1 + " must be present");
+    assertEquals(service2,
+        tokenMap.get(alias2).getService(), "Token for service " + service2 + " must be present");
 
 
     // compare secret keys
     Map<Text, byte[]> secretKeyMap = ts.getSecretKeyMap();
-    assertEquals("wrong number of keys in the Storage", m.size(),
-        ts.numberOfSecretKeys());
+    assertEquals(m.size(), ts.numberOfSecretKeys(),
+        "wrong number of keys in the Storage");
 
     for (Map.Entry<Text, byte[]> entry : m.entrySet()) {
       byte[] key = secretKeyMap.get(entry.getKey());
-      assertNotNull("Secret key for alias " + entry.getKey() + " not found",
-          key);
-      assertTrue("Keys don't match for alias " + entry.getKey(),
-          Arrays.equals(key, entry.getValue()));
+      assertNotNull(key, "Secret key for alias " + entry.getKey() + " not found");
+      assertTrue(Arrays.equals(key, entry.getValue()),
+          "Keys don't match for alias " + entry.getKey());
     }
 
     tmpFileName.delete();
@@ -146,8 +147,8 @@ public class TestCredentials {
     Credentials ts = new Credentials();
     writeCredentialsProto(ts, testname);
     Credentials ts2 = readCredentialsProto(testname);
-    assertEquals("test empty tokens", 0, ts2.numberOfTokens());
-    assertEquals("test empty keys", 0, ts2.numberOfSecretKeys());
+    assertEquals(0, ts2.numberOfTokens(), "test empty tokens");
+    assertEquals(0, ts2.numberOfSecretKeys(), "test empty keys");
   }
 
   @Test
@@ -171,8 +172,8 @@ public class TestCredentials {
     Credentials ts = new Credentials();
     writeCredentialsStream(ts, testname);
     Credentials ts2 = readCredentialsStream(testname);
-    assertEquals("test empty tokens", 0, ts2.numberOfTokens());
-    assertEquals("test empty keys", 0, ts2.numberOfSecretKeys());
+    assertEquals(0, ts2.numberOfTokens(), "test empty tokens");
+    assertEquals(0, ts2.numberOfSecretKeys(), "test empty keys");
   }
 
   @Test
@@ -201,10 +202,10 @@ public class TestCredentials {
     Credentials ts2 = new Credentials();
     writeCredentialsProtos(ts, ts2, testname);
     List<Credentials> clist = readCredentialsProtos(testname);
-    assertEquals("test empty tokens 0", 0, clist.get(0).numberOfTokens());
-    assertEquals("test empty keys 0", 0, clist.get(0).numberOfSecretKeys());
-    assertEquals("test empty tokens 1", 0, clist.get(1).numberOfTokens());
-    assertEquals("test empty keys 1", 0, clist.get(1).numberOfSecretKeys());
+    assertEquals(0, clist.get(0).numberOfTokens(), "test empty tokens 0");
+    assertEquals(0, clist.get(0).numberOfSecretKeys(), "test empty keys 0");
+    assertEquals(0, clist.get(1).numberOfTokens(), "test empty tokens 1");
+    assertEquals(0, clist.get(1).numberOfSecretKeys(), "test empty keys 1");
   }
 
   @Test
@@ -245,22 +246,19 @@ public class TestCredentials {
 
   private void assertCredentials(String tag, Text alias, Text keykey,
                                  Credentials a, Credentials b) {
-    assertEquals(tag + ": test token count", a.numberOfTokens(),
-                                             b.numberOfTokens());
-    assertEquals(tag + ": test service", a.getToken(alias).getService(),
-                                         b.getToken(alias).getService());
-    assertEquals(tag + ": test kind", a.getToken(alias).getKind(),
-                                      b.getToken(alias).getKind());
-    assertTrue(tag + ": test password",
-        Arrays.equals(a.getToken(alias).getPassword(),
-                      b.getToken(alias).getPassword()));
-    assertTrue(tag + ": test identifier",
-        Arrays.equals(a.getToken(alias).getIdentifier(),
-                      b.getToken(alias).getIdentifier()));
-    assertEquals(tag + ": test number of keys", a.numberOfSecretKeys(),
-                                                b.numberOfSecretKeys());
-    assertTrue(tag + ":test key values", Arrays.equals(a.getSecretKey(keykey),
-                                                       b.getSecretKey(keykey)));
+    assertEquals(a.numberOfTokens(), b.numberOfTokens(), tag + ": test token count");
+    assertEquals(a.getToken(alias).getService(),
+        b.getToken(alias).getService(), tag + ": test service");
+    assertEquals(a.getToken(alias).getKind(),
+        b.getToken(alias).getKind(), tag + ": test kind");
+    assertTrue(Arrays.equals(a.getToken(alias).getPassword(),
+        b.getToken(alias).getPassword()), tag + ": test password");
+    assertTrue(Arrays.equals(a.getToken(alias).getIdentifier(),
+        b.getToken(alias).getIdentifier()), tag + ": test identifier");
+    assertEquals(a.numberOfSecretKeys(),
+        b.numberOfSecretKeys(), tag + ": test number of keys");
+    assertTrue(Arrays.equals(a.getSecretKey(keykey),
+        b.getSecretKey(keykey)), tag + ":test key values");
   }
 
   private void writeCredentialsStream(Credentials creds, String filename)

+ 22 - 17
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestDoAsEffectiveUser.java

@@ -29,9 +29,9 @@ import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
 import org.apache.hadoop.security.authorize.DefaultImpersonationProvider;
 import org.apache.hadoop.security.authorize.ProxyUsers;
 import org.apache.hadoop.security.token.Token;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -42,6 +42,9 @@ import java.security.PrivilegedExceptionAction;
 import java.util.ArrayList;
 import java.util.Enumeration;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
 /**
  * Test do as effective user.
  */
@@ -69,7 +72,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
         + "DEFAULT");
   }
 
-  @Before
+  @BeforeEach
   public void setMasterConf() throws IOException {
     UserGroupInformation.setConfiguration(masterConf);
     refreshConf(masterConf);
@@ -120,7 +123,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
             return UserGroupInformation.getCurrentUser();
           }
         });
-    Assert.assertEquals(
+    assertEquals(
         PROXY_USER_NAME + " (auth:PROXY) via " + REAL_USER_NAME + " (auth:SIMPLE)",
         curUGI.toString());
   }
@@ -136,14 +139,15 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
         String serverRemoteUser = client.getServerRemoteUser(null,
             newEmptyRequest()).getUser();
 
-        Assert.assertEquals(ugi.toString(), currentUser);
-        Assert.assertEquals(ugi.toString(), serverRemoteUser);
+        assertEquals(ugi.toString(), currentUser);
+        assertEquals(ugi.toString(), serverRemoteUser);
         return null;
       }
     });    
   }
   
-  @Test(timeout=4000)
+  @Test
+  @Timeout(value = 4)
   public void testRealUserSetup() throws IOException {
     final Configuration conf = new Configuration();
     conf.setStrings(DefaultImpersonationProvider.getTestProvider().
@@ -167,13 +171,14 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
       checkRemoteUgi(proxyUserUgi, conf);
     } catch (Exception e) {
       e.printStackTrace();
-      Assert.fail();
+      fail();
     } finally {
       stop(server, client);
     }
   }
 
-  @Test(timeout=4000)
+  @Test
+  @Timeout(value = 4)
   public void testRealUserAuthorizationSuccess() throws IOException {
     final Configuration conf = new Configuration();
     configureSuperUserIPAddresses(conf, REAL_USER_SHORT_NAME);
@@ -196,7 +201,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
       checkRemoteUgi(proxyUserUgi, conf);
     } catch (Exception e) {
       e.printStackTrace();
-      Assert.fail();
+      fail();
     } finally {
       stop(server, client);
     }
@@ -237,7 +242,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
             }
           });
 
-      Assert.fail("The RPC must have failed " + retVal);
+      fail("The RPC must have failed " + retVal);
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
@@ -273,7 +278,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
             }
           });
 
-      Assert.fail("The RPC must have failed " + retVal);
+      fail("The RPC must have failed " + retVal);
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
@@ -306,7 +311,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
             }
           });
 
-      Assert.fail("The RPC must have failed " + retVal);
+      fail("The RPC must have failed " + retVal);
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
@@ -344,7 +349,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
             }
           });
 
-      Assert.fail("The RPC must have failed " + retVal);
+      fail("The RPC must have failed " + retVal);
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
@@ -397,7 +402,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
       }
     });
     //The user returned by server must be the one in the token.
-    Assert.assertEquals(REAL_USER_NAME + " (auth:TOKEN) via SomeSuperUser (auth:SIMPLE)", retVal);
+    assertEquals(REAL_USER_NAME + " (auth:TOKEN) via SomeSuperUser (auth:SIMPLE)", retVal);
   }
 
   /*
@@ -441,7 +446,7 @@ public class TestDoAsEffectiveUser extends TestRpcBase {
       }
     });
     String expected = REAL_USER_NAME + " (auth:TOKEN) via SomeSuperUser (auth:SIMPLE)";
-    Assert.assertEquals(retVal + "!=" + expected, expected, retVal);
+    assertEquals(expected, retVal, retVal + "!=" + expected);
   }
   
   //

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestGroupFallback.java

@@ -17,14 +17,14 @@
  */
 package org.apache.hadoop.security;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.List;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.event.Level;

+ 16 - 16
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestGroupsCaching.java

@@ -31,15 +31,15 @@ import java.util.concurrent.TimeoutException;
 
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.FakeTimer;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 import java.util.function.Supplier;
 
-import static org.junit.Assert.assertEquals;
-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.assertEquals;
+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 org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
@@ -54,7 +54,7 @@ public class TestGroupsCaching {
   private static String[] myGroups = {"grp1", "grp2"};
   private Configuration conf;
 
-  @Before
+  @BeforeEach
   public void setup() throws IOException {
     FakeGroupMapping.clearAll();
     ExceptionalGroupMapping.resetRequestCount();
@@ -271,25 +271,25 @@ public class TestGroupsCaching {
     conf.set(CommonConfigurationKeys.HADOOP_USER_GROUP_STATIC_OVERRIDES, "me=;user1=group1;user2=group1,group2");
     Groups groups = new Groups(conf);
     List<String> userGroups = groups.getGroups("me");
-    assertTrue("non-empty groups for static user", userGroups.isEmpty());
-    assertFalse("group lookup done for static user",
-        FakeunPrivilegedGroupMapping.invoked);
+    assertTrue(userGroups.isEmpty(), "non-empty groups for static user");
+    assertFalse(FakeunPrivilegedGroupMapping.invoked,
+        "group lookup done for static user");
     
     List<String> expected = new ArrayList<String>();
     expected.add("group1");
 
     FakeunPrivilegedGroupMapping.invoked = false;
     userGroups = groups.getGroups("user1");
-    assertTrue("groups not correct", expected.equals(userGroups));
-    assertFalse("group lookup done for unprivileged user",
-        FakeunPrivilegedGroupMapping.invoked);
+    assertTrue(expected.equals(userGroups), "groups not correct");
+    assertFalse(FakeunPrivilegedGroupMapping.invoked,
+        "group lookup done for unprivileged user");
 
     expected.add("group2");
     FakeunPrivilegedGroupMapping.invoked = false;
     userGroups = groups.getGroups("user2");
-    assertTrue("groups not correct", expected.equals(userGroups));
-    assertFalse("group lookup done for unprivileged user",
-        FakeunPrivilegedGroupMapping.invoked);
+    assertTrue(expected.equals(userGroups), "groups not correct");
+    assertFalse(FakeunPrivilegedGroupMapping.invoked,
+        "group lookup done for unprivileged user");
 
   }
 

+ 7 - 8
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestHttpCrossOriginFilterInitializer.java

@@ -22,8 +22,10 @@ import java.util.Map;
 
 import org.apache.hadoop.conf.Configuration;
 
-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.assertNull;
 
 public class TestHttpCrossOriginFilterInitializer {
 
@@ -48,11 +50,8 @@ public class TestHttpCrossOriginFilterInitializer {
     String outofscopeparam = filterParameters.get("outofscopeparam");
 
     // verify expected values are in place
-    Assert.assertEquals("Could not find filter parameter", "rootvalue",
-        rootvalue);
-    Assert.assertEquals("Could not find filter parameter", "nestedvalue",
-        nestedvalue);
-    Assert.assertNull("Found unexpected value in filter parameters",
-        outofscopeparam);
+    assertEquals("rootvalue", rootvalue, "Could not find filter parameter");
+    assertEquals("nestedvalue", nestedvalue, "Could not find filter parameter");
+    assertNull(outofscopeparam, "Found unexpected value in filter parameters");
   }
 }

+ 2 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestIngressPortBasedResolver.java

@@ -19,10 +19,9 @@ package org.apache.hadoop.security;
 
 import javax.security.sasl.Sasl;
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 /**
  * Test class for IngressPortBasedResolver.

+ 4 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestJNIGroupsMapping.java

@@ -17,7 +17,7 @@
  */
 package org.apache.hadoop.security;
 import static org.junit.Assume.assumeTrue;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.util.Arrays;
 import java.util.List;
@@ -26,14 +26,14 @@ import org.apache.hadoop.security.JniBasedUnixGroupsMapping;
 import org.apache.hadoop.security.ShellBasedUnixGroupsMapping;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.util.NativeCodeLoader;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 
 
 public class TestJNIGroupsMapping {
   
-  @Before
+  @BeforeEach
   public void isNativeCodeLoaded() {
     assumeTrue(NativeCodeLoader.isNativeCodeLoaded());
   }

+ 13 - 21
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestKDiag.java

@@ -22,14 +22,12 @@ import org.apache.commons.io.IOUtils;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.minikdc.MiniKdc;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.AfterAll;
+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.junit.jupiter.api.Assertions;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,25 +36,19 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.util.Properties;
-import java.util.concurrent.TimeUnit;
 
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION;
 import static org.apache.hadoop.security.KDiag.*;
 
-public class TestKDiag extends Assert {
+@Timeout(30)
+public class TestKDiag extends Assertions {
   private static final Logger LOG = LoggerFactory.getLogger(TestKDiag.class);
 
   public static final String KEYLEN = "128";
   public static final String HDFS_SITE_XML
       = "org/apache/hadoop/security/secure-hdfs-site.xml";
 
-  @Rule
-  public TestName methodName = new TestName();
-
-  @Rule
-  public Timeout testTimeout = new Timeout(30000, TimeUnit.MILLISECONDS);
-
-  @BeforeClass
+  @BeforeAll
   public static void nameThread() {
     Thread.currentThread().setName("JUnit");
   }
@@ -67,7 +59,7 @@ public class TestKDiag extends Assert {
   private static Properties securityProperties;
   private static Configuration conf;
 
-  @BeforeClass
+  @BeforeAll
   public static void startMiniKdc() throws Exception {
     workDir = GenericTestUtils.getTestDir(TestKDiag.class.getSimpleName());
     securityProperties = MiniKdc.createConf();
@@ -78,7 +70,7 @@ public class TestKDiag extends Assert {
     conf.set(HADOOP_SECURITY_AUTHENTICATION, "KERBEROS");
   }
 
-  @AfterClass
+  @AfterAll
   public static synchronized void stopMiniKdc() {
     if (kdc != null) {
       kdc.stop();
@@ -86,7 +78,7 @@ public class TestKDiag extends Assert {
     }
   }
 
-  @Before
+  @BeforeEach
   public void reset() {
     UserGroupInformation.reset();
   }
@@ -155,7 +147,7 @@ public class TestKDiag extends Assert {
 
   @Test
   public void testConfIsSecure() throws Throwable {
-    Assert.assertFalse(SecurityUtil.getAuthenticationMethod(conf)
+    assertFalse(SecurityUtil.getAuthenticationMethod(conf)
         .equals(UserGroupInformation.AuthenticationMethod.SIMPLE));
   }
 

+ 5 - 18
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestKDiagNoKDC.java

@@ -20,18 +20,10 @@ package org.apache.hadoop.security;
 
 import org.apache.hadoop.conf.Configuration;
 
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.concurrent.TimeUnit;
-
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_TOKEN_FILES;
 import static org.apache.hadoop.security.KDiag.ARG_KEYLEN;
 import static org.apache.hadoop.security.KDiag.ARG_NOFAIL;
@@ -41,18 +33,13 @@ import static org.apache.hadoop.security.KDiag.CAT_TOKEN;
 import static org.apache.hadoop.security.KDiag.KerberosDiagsFailure;
 import static org.apache.hadoop.security.KDiag.exec;
 
-public class TestKDiagNoKDC extends Assert {
+@Timeout(30)
+public class TestKDiagNoKDC extends Assertions {
   private static final Logger LOG = LoggerFactory.getLogger(TestKDiagNoKDC.class);
 
   public static final String KEYLEN = "128";
 
-  @Rule
-  public TestName methodName = new TestName();
-
-  @Rule
-  public Timeout testTimeout = new Timeout(30000, TimeUnit.MILLISECONDS);
-
-  @BeforeClass
+  @BeforeAll
   public static void nameThread() {
     Thread.currentThread().setName("JUnit");
   }
@@ -60,7 +47,7 @@ public class TestKDiagNoKDC extends Assert {
   private static Configuration conf = new Configuration();
 
 
-  @Before
+  @BeforeEach
   public void reset() {
     UserGroupInformation.reset();
   }

+ 25 - 21
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMapping.java

@@ -22,10 +22,11 @@ import static org.apache.hadoop.security.LdapGroupsMapping.GROUP_SEARCH_FILTER_P
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_NUM_ATTEMPTS_KEY;
 import static org.apache.hadoop.security.LdapGroupsMapping.READ_TIMEOUT;
 import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -59,9 +60,9 @@ import org.apache.hadoop.security.alias.CredentialProviderFactory;
 import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
 import org.apache.hadoop.test.GenericTestUtils;
 
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import org.mockito.Mockito;
 import org.slf4j.Logger;
@@ -90,7 +91,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
 
   private static final String TEST_LDAP_URL = "ldap://test";
 
-  @Before
+  @BeforeEach
   public void setupMocks() {
     when(getUserSearchResult().getNameInNamespace()).
         thenReturn(userDN);
@@ -165,7 +166,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
 
     // Check the group filter got resolved and get the desired values.
     List<String> groups = groupsMapping.getGroups(userName);
-    Assert.assertEquals(Arrays.asList(getTestGroups()), groups);
+    assertEquals(Arrays.asList(getTestGroups()), groups);
   }
 
   /**
@@ -190,7 +191,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
         .thenReturn(getUserNames(), getGroupNames());
 
     List<String> groups = groupsMapping.getGroups(userName);
-    Assert.assertEquals(Arrays.asList(getTestGroups()), groups);
+    assertEquals(Arrays.asList(getTestGroups()), groups);
 
     // We should have searched for the username and groups with default base dn
     verify(getContext(), times(1)).search(userBaseDN,
@@ -258,7 +259,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
     // regardless of input
     List<String> groups = groupsMapping.getGroups("some_user");
     
-    Assert.assertEquals(expectedGroups, groups);
+    assertEquals(expectedGroups, groups);
     
     // We should have searched for a user, and then two groups
     verify(getContext(), times(searchTimes)).search(anyString(),
@@ -278,7 +279,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
     List<String> groups = groupsMapping.getGroups("some_user");
 
     // compare lists, ignoring the order
-    Assert.assertEquals(new HashSet<>(expectedGroups), new HashSet<>(groups));
+    assertEquals(new HashSet<>(expectedGroups), new HashSet<>(groups));
 
     // We should have searched for a user, and group
     verify(getContext(), times(searchTimesGroup)).search(anyString(),
@@ -298,7 +299,7 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
     writer.close();
     
     LdapGroupsMapping mapping = new LdapGroupsMapping();
-    Assert.assertEquals("hadoop",
+    assertEquals("hadoop",
         mapping.extractPassword(secretFile.getPath()));
   }
 
@@ -344,15 +345,15 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
         LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY).getCredential());
 
     LdapGroupsMapping mapping = new LdapGroupsMapping();
-    Assert.assertEquals("bindpass",
+    assertEquals("bindpass",
         mapping.getPassword(conf, LdapGroupsMapping.BIND_PASSWORD_KEY, ""));
-    Assert.assertEquals("storepass",
+    assertEquals("storepass",
         mapping.getPassword(conf, LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY,
             ""));
     // let's make sure that a password that doesn't exist returns an
     // empty string as currently expected and used to trigger a call to
     // extract password
-    Assert.assertEquals("", mapping.getPassword(conf,"invalid-alias", ""));
+    assertEquals("", mapping.getPassword(conf, "invalid-alias", ""));
   }
 
   @Test
@@ -387,11 +388,11 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
         bindpassAlias).getCredential());
 
     LdapGroupsMapping mapping = new LdapGroupsMapping();
-    Assert.assertEquals("bindpass",
+    assertEquals("bindpass",
         mapping.getPasswordFromCredentialProviders(conf, bindpassAlias, ""));
 
     // Empty for an invalid alias
-    Assert.assertEquals("", mapping.getPasswordFromCredentialProviders(
+    assertEquals("", mapping.getPasswordFromCredentialProviders(
         conf, "invalid-alias", ""));
   }
 
@@ -402,7 +403,8 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
    * @throws IOException
    * @throws InterruptedException
    */
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testLdapConnectionTimeout()
       throws IOException, InterruptedException {
     final int connectionTimeoutMs = 3 * 1000; // 3s
@@ -456,7 +458,8 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
    * @throws IOException
    * @throws InterruptedException
    */
-  @Test(timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testLdapReadTimeout() throws IOException, InterruptedException {
     final int readTimeoutMs = 4 * 1000; // 4s
     try (ServerSocket serverSock = new ServerSocket(0)) {
@@ -511,7 +514,8 @@ public class TestLdapGroupsMapping extends TestLdapGroupsMappingBase {
    *
    * @throws Exception
    */
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testSetConf() throws Exception {
     Configuration conf = getBaseConf(TEST_LDAP_URL);
     Configuration mockConf = Mockito.spy(conf);

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingBase.java

@@ -21,7 +21,7 @@ package org.apache.hadoop.security;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_CTX_FACTORY_CLASS_DEFAULT;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_CTX_FACTORY_CLASS_KEY;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_URL_KEY;
-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;
 
@@ -39,7 +39,7 @@ import javax.naming.ldap.InitialLdapContext;
 import javax.naming.spi.InitialContextFactory;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
@@ -67,7 +67,7 @@ public class TestLdapGroupsMappingBase {
   private String[] testParentGroups =
       new String[] {"group1", "group2", "group1_1"};
 
-  @Before
+  @BeforeEach
   public void setupMocksBase() throws NamingException {
     DummyLdapCtxFactory.reset();
     MockitoAnnotations.initMocks(this);

+ 5 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithBindUserSwitch.java

@@ -25,7 +25,7 @@ import org.apache.hadoop.security.alias.CredentialProvider;
 import org.apache.hadoop.security.alias.CredentialProviderFactory;
 import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import javax.naming.AuthenticationException;
 import javax.naming.NamingException;
@@ -44,10 +44,10 @@ import static org.apache.hadoop.security.LdapGroupsMapping.BIND_PASSWORD_SUFFIX;
 import static org.apache.hadoop.security.LdapGroupsMapping.BIND_USERS_KEY;
 import static org.apache.hadoop.security.LdapGroupsMapping.BIND_USER_SUFFIX;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_NUM_ATTEMPTS_KEY;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.times;

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithFailover.java

@@ -19,7 +19,7 @@
 package org.apache.hadoop.security;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -33,7 +33,7 @@ import java.util.concurrent.atomic.AtomicInteger;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_NUM_ATTEMPTS_BEFORE_FAILOVER_KEY;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_NUM_ATTEMPTS_KEY;
 import static org.apache.hadoop.security.LdapGroupsMapping.LDAP_URL_KEY;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.times;

+ 10 - 8
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithOneQuery.java

@@ -31,10 +31,12 @@ import javax.naming.directory.SearchControls;
 import javax.naming.directory.SearchResult;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.mockito.stubbing.Stubber;
 
+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.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -114,9 +116,9 @@ public class TestLdapGroupsMappingWithOneQuery
     // regardless of input
     List<String> groups = groupsMapping.getGroups("some_user");
 
-    Assert.assertEquals(expectedGroups, groups);
-    Assert.assertFalse("Second LDAP query should NOT have been called.",
-            groupsMapping.isSecondaryQueryCalled());
+    assertEquals(expectedGroups, groups);
+    assertFalse(groupsMapping.isSecondaryQueryCalled(),
+        "Second LDAP query should NOT have been called.");
 
     // We should have only made one query because single-query lookup is enabled
     verify(getContext(), times(1)).search(anyString(), anyString(),
@@ -144,11 +146,11 @@ public class TestLdapGroupsMappingWithOneQuery
     List<String> groups = groupsMapping.getGroups("some_user");
 
     // expected to be empty due to invalid memberOf
-    Assert.assertEquals(0, groups.size());
+    assertEquals(0, groups.size());
 
     // expect secondary query to be called: getGroups()
-    Assert.assertTrue("Second LDAP query should have been called.",
-            groupsMapping.isSecondaryQueryCalled());
+    assertTrue(groupsMapping.isSecondaryQueryCalled(),
+        "Second LDAP query should have been called.");
 
     // We should have fallen back to the second query because first threw
     // NamingException expected count is 3 since testGetGroups calls

+ 7 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestLdapGroupsMappingWithPosixGroup.java

@@ -37,15 +37,16 @@ import javax.naming.directory.Attributes;
 import javax.naming.directory.SearchControls;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 @SuppressWarnings("unchecked")
 public class TestLdapGroupsMappingWithPosixGroup
   extends TestLdapGroupsMappingBase {
 
-  @Before
+  @BeforeEach
   public void setupMocks() throws NamingException {
     Attribute uidNumberAttr = mock(Attribute.class);
     Attribute gidNumberAttr = mock(Attribute.class);
@@ -90,11 +91,11 @@ public class TestLdapGroupsMappingWithPosixGroup
     // regardless of input
     List<String> groups = groupsMapping.getGroups("some_user");
 
-    Assert.assertEquals(expectedGroups, groups);
+    assertEquals(expectedGroups, groups);
 
     groupsMapping.getConf().set(LdapGroupsMapping.POSIX_UID_ATTR_KEY, "uid");
 
-    Assert.assertEquals(expectedGroups, groups);
+    assertEquals(expectedGroups, groups);
 
     // We should have searched for a user, and then two groups
     verify(getContext(), times(searchTimes)).search(anyString(),

+ 5 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestNetgroupCache.java

@@ -16,14 +16,14 @@
  */
 package org.apache.hadoop.security;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.ArrayList;
 import java.util.List;
 
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
 
 public class TestNetgroupCache {
 
@@ -33,7 +33,7 @@ public class TestNetgroupCache {
   private static final String GROUP1 = "group1";
   private static final String GROUP2 = "group2";
 
-  @After
+  @AfterEach
   public void teardown() {
     NetgroupCache.clear();
   }

+ 7 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestNullGroupsMapping.java

@@ -18,9 +18,9 @@ package org.apache.hadoop.security;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 /**
  * Test that the {@link NullGroupsMapping} really does nothing.
@@ -28,7 +28,7 @@ import static org.junit.Assert.*;
 public class TestNullGroupsMapping {
   private NullGroupsMapping ngm;
 
-  @Before
+  @BeforeEach
   public void setUp() {
     this.ngm = new NullGroupsMapping();
   }
@@ -42,19 +42,16 @@ public class TestNullGroupsMapping {
     List<String> expResult = Collections.emptyList();
     List<String> result = ngm.getGroups(user);
 
-    assertEquals("No groups should be returned",
-        expResult, result);
+    assertEquals(expResult, result, "No groups should be returned");
 
     ngm.cacheGroupsAdd(Arrays.asList(new String[] {"group1", "group2"}));
     result = ngm.getGroups(user);
 
-    assertEquals("No groups should be returned",
-        expResult, result);
+    assertEquals(expResult, result, "No groups should be returned");
 
     ngm.cacheGroupsRefresh();
     result = ngm.getGroups(user);
 
-    assertEquals("No groups should be returned",
-        expResult, result);
+    assertEquals(expResult, result, "No groups should be returned");
   }
 }

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestProxyUserFromEnv.java

@@ -17,14 +17,14 @@
 
 package org.apache.hadoop.security;
 
-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 java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestProxyUserFromEnv {
   /** Test HADOOP_PROXY_USER for impersonation */

+ 15 - 14
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestRuleBasedLdapGroupsMapping.java

@@ -18,9 +18,7 @@
 package org.apache.hadoop.security;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Assert;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Test;
 
 import javax.naming.NamingException;
 import java.util.ArrayList;
@@ -30,8 +28,11 @@ import java.util.Set;
 
 import static org.apache.hadoop.security.RuleBasedLdapGroupsMapping
     .CONVERSION_RULE_KEY;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.spy;
 
 /**
  * Test cases to verify the rules supported by RuleBasedLdapGroupsMapping.
@@ -40,12 +41,12 @@ public class TestRuleBasedLdapGroupsMapping  {
 
   @Test
   public void testGetGroupsToUpper() throws NamingException {
-    RuleBasedLdapGroupsMapping groupsMapping = Mockito.spy(
+    RuleBasedLdapGroupsMapping groupsMapping = spy(
         new RuleBasedLdapGroupsMapping());
     Set<String> groups = new LinkedHashSet<>();
     groups.add("group1");
     groups.add("group2");
-    Mockito.doReturn(groups).when((LdapGroupsMapping) groupsMapping)
+    doReturn(groups).when((LdapGroupsMapping) groupsMapping)
         .doGetGroups(eq("admin"), anyInt());
 
     Configuration conf = new Configuration();
@@ -56,17 +57,17 @@ public class TestRuleBasedLdapGroupsMapping  {
     List<String> groupsUpper = new ArrayList<>();
     groupsUpper.add("GROUP1");
     groupsUpper.add("GROUP2");
-    Assert.assertEquals(groupsUpper, groupsMapping.getGroups("admin"));
+    assertEquals(groupsUpper, groupsMapping.getGroups("admin"));
   }
 
   @Test
   public void testGetGroupsToLower() throws NamingException {
-    RuleBasedLdapGroupsMapping groupsMapping = Mockito.spy(
+    RuleBasedLdapGroupsMapping groupsMapping = spy(
         new RuleBasedLdapGroupsMapping());
     Set<String> groups = new LinkedHashSet<>();
     groups.add("GROUP1");
     groups.add("GROUP2");
-    Mockito.doReturn(groups).when((LdapGroupsMapping) groupsMapping)
+    doReturn(groups).when((LdapGroupsMapping) groupsMapping)
         .doGetGroups(eq("admin"), anyInt());
 
     Configuration conf = new Configuration();
@@ -77,17 +78,17 @@ public class TestRuleBasedLdapGroupsMapping  {
     List<String> groupsLower = new ArrayList<>();
     groupsLower.add("group1");
     groupsLower.add("group2");
-    Assert.assertEquals(groupsLower, groupsMapping.getGroups("admin"));
+    assertEquals(groupsLower, groupsMapping.getGroups("admin"));
   }
 
   @Test
   public void testGetGroupsInvalidRule() throws NamingException {
-    RuleBasedLdapGroupsMapping groupsMapping = Mockito.spy(
+    RuleBasedLdapGroupsMapping groupsMapping = spy(
         new RuleBasedLdapGroupsMapping());
     Set<String> groups = new LinkedHashSet<>();
     groups.add("group1");
     groups.add("GROUP2");
-    Mockito.doReturn(groups).when((LdapGroupsMapping) groupsMapping)
+    doReturn(groups).when((LdapGroupsMapping) groupsMapping)
         .doGetGroups(eq("admin"), anyInt());
 
     Configuration conf = new Configuration();
@@ -95,7 +96,7 @@ public class TestRuleBasedLdapGroupsMapping  {
     conf.set(CONVERSION_RULE_KEY, "none");
     groupsMapping.setConf(conf);
 
-    Assert.assertEquals(groups, groupsMapping.getGroupsSet("admin"));
+    assertEquals(groups, groupsMapping.getGroupsSet("admin"));
   }
 
 }

+ 11 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestSecurityUtil.java

@@ -19,7 +19,11 @@ package org.apache.hadoop.security;
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION;
 import static org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.*;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.File;
 import java.io.IOException;
@@ -42,8 +46,8 @@ import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.security.token.TokenIdentifier;
 import org.apache.hadoop.util.StringUtils;
 import org.apache.hadoop.util.ZKUtil.ZKAuthInfo;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 
 import org.apache.hadoop.thirdparty.com.google.common.io.Files;
@@ -52,7 +56,7 @@ public class TestSecurityUtil {
 
   private static final String ZK_AUTH_VALUE = "a_scheme:a_password";
 
-  @BeforeClass
+  @BeforeAll
   public static void unsetKerberosRealm() {
     // prevent failures if kinit-ed or on os x with no realm
     System.setProperty("java.security.krb5.kdc", "");
@@ -145,7 +149,7 @@ public class TestSecurityUtil {
       // expected
       gotException=true;
     }
-    assertTrue("Exception for empty keytabfile name was expected", gotException);
+    assertTrue(gotException, "Exception for empty keytabfile name was expected");
   }
   
   @Test
@@ -238,7 +242,7 @@ public class TestSecurityUtil {
     } catch (IllegalArgumentException e) {
       bad = true;
     } finally {
-      assertTrue("should be bad: '"+arg+"'", bad);
+      assertTrue(bad, "should be bad: '"+arg+"'");
     }
     for (int port : ports) {
       if (validIfPosPort && port > 0) continue;
@@ -249,7 +253,7 @@ public class TestSecurityUtil {
       } catch (IllegalArgumentException e) {
         bad = true;
       } finally {
-        assertTrue("should be bad: '"+arg+"' (default port:"+port+")", bad);
+        assertTrue(bad, "should be bad: '"+arg+"' (default port:"+port+")");
       }
     }
   }

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestShellBasedIdMapping.java

@@ -18,8 +18,8 @@
 package org.apache.hadoop.security;
 
 import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -30,7 +30,7 @@ import java.util.Map;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.security.ShellBasedIdMapping.PassThroughMap;
 import org.apache.hadoop.security.ShellBasedIdMapping.StaticMapping;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.thirdparty.com.google.common.collect.BiMap;
 import org.apache.hadoop.thirdparty.com.google.common.collect.HashBiMap;

+ 33 - 44
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestShellBasedUnixGroupsMapping.java

@@ -27,11 +27,15 @@ import org.apache.hadoop.util.ReflectionUtils;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.util.Shell.ExitCodeException;
 import org.apache.hadoop.util.Shell.ShellCommandExecutor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
@@ -189,19 +193,16 @@ public class TestShellBasedUnixGroupsMapping {
   public void testShellTimeOutConf() {
 
     // Test a 1 second max-runtime timeout
-    assertEquals(
-        "Expected the group names executor to carry the configured timeout",
-        1000L, getTimeoutInterval("1s"));
+    assertEquals(1000L, getTimeoutInterval("1s"),
+        "Expected the group names executor to carry the configured timeout");
 
     // Test a 1 minute max-runtime timeout
-    assertEquals(
-        "Expected the group names executor to carry the configured timeout",
-        60000L, getTimeoutInterval("1m"));
+    assertEquals(60000L, getTimeoutInterval("1m"),
+        "Expected the group names executor to carry the configured timeout");
 
     // Test a 1 millisecond max-runtime timeout
-    assertEquals(
-        "Expected the group names executor to carry the configured timeout",
-        1L, getTimeoutInterval("1"));
+    assertEquals(1L, getTimeoutInterval("1"),
+        "Expected the group names executor to carry the configured timeout");
   }
 
   private class TestGroupResolvable
@@ -274,7 +275,8 @@ public class TestShellBasedUnixGroupsMapping {
     }
   }
 
-  @Test(timeout=4000)
+  @Test
+  @Timeout(value = 4)
   public void testFiniteGroupResolutionTime() throws Exception {
     Configuration conf = new Configuration();
     String userName = "foobarnonexistinguser";
@@ -292,26 +294,19 @@ public class TestShellBasedUnixGroupsMapping {
         ReflectionUtils.newInstance(TestDelayedGroupCommand.class, conf);
 
     ShellCommandExecutor executor = mapping.createGroupExecutor(userName);
-    assertEquals(
-        "Expected the group names executor to carry the configured timeout",
-        testTimeout,
-        executor.getTimeoutInterval());
+    assertEquals(testTimeout, executor.getTimeoutInterval(),
+        "Expected the group names executor to carry the configured timeout");
 
     executor = mapping.createGroupIDExecutor(userName);
-    assertEquals(
-        "Expected the group ID executor to carry the configured timeout",
-        testTimeout,
-        executor.getTimeoutInterval());
-
-    assertEquals(
-        "Expected no groups to be returned given a shell command timeout",
-        0,
-        mapping.getGroups(userName).size());
-    assertTrue(
+    assertEquals(testTimeout, executor.getTimeoutInterval(),
+        "Expected the group ID executor to carry the configured timeout");
+
+    assertEquals(0, mapping.getGroups(userName).size(),
+        "Expected no groups to be returned given a shell command timeout");
+    assertTrue(shellMappingLog.getOutput().contains(commandTimeoutMessage),
         "Expected the logs to carry " +
-            "a message about command timeout but was: " +
-            shellMappingLog.getOutput(),
-        shellMappingLog.getOutput().contains(commandTimeoutMessage));
+        "a message about command timeout but was: " +
+        shellMappingLog.getOutput());
     shellMappingLog.clearOutput();
 
     // Test also the parent Groups framework for expected behaviour
@@ -325,11 +320,10 @@ public class TestShellBasedUnixGroupsMapping {
           "The groups framework call should " +
               "have failed with a command timeout");
     } catch (IOException e) {
-      assertTrue(
+      assertTrue(shellMappingLog.getOutput().contains(commandTimeoutMessage),
           "Expected the logs to carry " +
-              "a message about command timeout but was: " +
-              shellMappingLog.getOutput(),
-          shellMappingLog.getOutput().contains(commandTimeoutMessage));
+          "a message about command timeout but was: " +
+          shellMappingLog.getOutput());
     }
     shellMappingLog.clearOutput();
 
@@ -343,22 +337,17 @@ public class TestShellBasedUnixGroupsMapping {
         ReflectionUtils.newInstance(TestDelayedGroupCommand.class, conf);
 
     executor = mapping.createGroupExecutor(userName);
-    assertEquals(
-        "Expected the group names executor to carry the default timeout",
-        defaultTimeout,
-        executor.getTimeoutInterval());
+    assertEquals(defaultTimeout, executor.getTimeoutInterval(),
+        "Expected the group names executor to carry the default timeout");
 
     executor = mapping.createGroupIDExecutor(userName);
-    assertEquals(
-        "Expected the group ID executor to carry the default timeout",
-        defaultTimeout,
-        executor.getTimeoutInterval());
+    assertEquals(defaultTimeout, executor.getTimeoutInterval(),
+        "Expected the group ID executor to carry the default timeout");
 
     mapping.getGroups(userName);
-    assertFalse(
+    assertFalse(shellMappingLog.getOutput().contains(commandTimeoutMessage),
         "Didn't expect a timeout of command in execution but logs carry it: " +
-            shellMappingLog.getOutput(),
-        shellMappingLog.getOutput().contains(commandTimeoutMessage));
+        shellMappingLog.getOutput());
   }
 }
 

+ 85 - 91
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGILoginFromKeytab.java

@@ -24,12 +24,11 @@ import org.apache.hadoop.minikdc.MiniKdc;
 import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.Time;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+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.junit.jupiter.api.io.TempDir;
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
@@ -37,13 +36,19 @@ import org.slf4j.event.Level;
 
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_KEYTAB_LOGIN_AUTORENEWAL_ENABLED;
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 import java.security.Principal;
 import java.security.PrivilegedExceptionAction;
 import java.util.Iterator;
@@ -73,11 +78,8 @@ public class TestUGILoginFromKeytab {
   private File workDir;
   private ExecutorService executor;
 
-  @Rule
-  public final TemporaryFolder folder = new TemporaryFolder();
-
-  @Before
-  public void startMiniKdc() throws Exception {
+  @BeforeEach
+  public void startMiniKdc(@TempDir Path tempDir) throws Exception {
     // This setting below is required. If not enabled, UGI will abort
     // any attempt to loginUserFromKeytab.
     Configuration conf = new Configuration();
@@ -85,14 +87,14 @@ public class TestUGILoginFromKeytab {
         "kerberos");
     UserGroupInformation.setConfiguration(conf);
     UserGroupInformation.setShouldRenewImmediatelyForTests(true);
-    workDir = folder.getRoot();
+    workDir = tempDir.toFile();
     kdc = new MiniKdc(MiniKdc.createConf(), workDir);
     kdc.start();
     executor = Executors.newCachedThreadPool();
 
   }
 
-  @After
+  @AfterEach
   public void stopMiniKdc() {
     if (kdc != null) {
       kdc.stop();
@@ -114,15 +116,15 @@ public class TestUGILoginFromKeytab {
 
     UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath());
     UserGroupInformation ugi = UserGroupInformation.getLoginUser();
-    Assert.assertTrue("UGI should be configured to login from keytab",
-        ugi.isFromKeytab());
+    assertTrue(ugi.isFromKeytab(),
+        "UGI should be configured to login from keytab");
 
     User user = getUser(ugi.getSubject());
-    Assert.assertNotNull(user.getLogin());
+    assertNotNull(user.getLogin());
  
-    Assert.assertTrue("User login time is less than before login time, "
-        + "beforeLoginTime:" + beforeLogin + " userLoginTime:" + user.getLastLogin(),
-            user.getLastLogin() > beforeLogin);
+    assertTrue(user.getLastLogin() > beforeLogin,
+        "User login time is less than before login time, "
+        + "beforeLoginTime:" + beforeLogin + " userLoginTime:" + user.getLastLogin());
   }
 
   /**
@@ -137,14 +139,13 @@ public class TestUGILoginFromKeytab {
 
     UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath());
     UserGroupInformation ugi = UserGroupInformation.getLoginUser();
-    Assert.assertTrue("UGI should be configured to login from keytab",
-        ugi.isFromKeytab());
+    assertTrue(ugi.isFromKeytab(), "UGI should be configured to login from keytab");
 
     // Verify relogin from keytab.
     User user = getUser(ugi.getSubject());
     final long firstLogin = user.getLastLogin();
     final LoginContext login1 = user.getLogin();
-    Assert.assertNotNull(login1);
+    assertNotNull(login1);
 
     // Sleep for 2 secs to have a difference between first and second login
     Thread.sleep(2000);
@@ -152,10 +153,10 @@ public class TestUGILoginFromKeytab {
     ugi.reloginFromKeytab();
     final long secondLogin = user.getLastLogin();
     final LoginContext login2 = user.getLogin();
-    Assert.assertTrue("User should have been able to relogin from keytab",
-        secondLogin > firstLogin);
-    Assert.assertNotNull(login2);
-    Assert.assertNotSame(login1, login2);
+    assertTrue(secondLogin > firstLogin,
+        "User should have been able to relogin from keytab");
+    assertNotNull(login2);
+    assertNotSame(login1, login2);
   }
 
   /**
@@ -172,14 +173,13 @@ public class TestUGILoginFromKeytab {
 
     UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath());
     UserGroupInformation ugi = UserGroupInformation.getLoginUser();
-    Assert.assertTrue("UGI should be configured to login from keytab",
-        ugi.isFromKeytab());
+    assertTrue(ugi.isFromKeytab(), "UGI should be configured to login from keytab");
 
     // Verify relogin from keytab.
     User user = getUser(ugi.getSubject());
     final long firstLogin = user.getLastLogin();
     final LoginContext login1 = user.getLogin();
-    Assert.assertNotNull(login1);
+    assertNotNull(login1);
 
     // Sleep for 2 secs to have a difference between first and second login
     Thread.sleep(2000);
@@ -188,10 +188,10 @@ public class TestUGILoginFromKeytab {
     ugi.forceReloginFromKeytab();
     final long secondLogin = user.getLastLogin();
     final LoginContext login2 = user.getLogin();
-    Assert.assertTrue("User should have been able to relogin from keytab",
-        secondLogin > firstLogin);
-    Assert.assertNotNull(login2);
-    Assert.assertNotSame(login1, login2);
+    assertTrue(secondLogin > firstLogin,
+        "User should have been able to relogin from keytab");
+    assertNotNull(login2);
+    assertNotSame(login1, login2);
   }
 
   @Test
@@ -205,14 +205,14 @@ public class TestUGILoginFromKeytab {
         principal.getName(), keytab.getPath());
     Subject subject = ugi1.getSubject();
     User user = getUser(subject);
-    Assert.assertNotNull(user);
+    assertNotNull(user);
     LoginContext login = user.getLogin();
-    Assert.assertNotNull(login);
+    assertNotNull(login);
 
     // User instance and/or login context should not change.
     UserGroupInformation ugi2 = UserGroupInformation.getUGIFromSubject(subject);
-    Assert.assertSame(user, getUser(ugi2.getSubject()));
-    Assert.assertSame(login, user.getLogin());
+    assertSame(user, getUser(ugi2.getSubject()));
+    assertSame(login, user.getLogin());
   }
 
   @Test
@@ -230,17 +230,17 @@ public class TestUGILoginFromKeytab {
     // first call to get the ugi should add the User instance w/o a login
     // context.
     UserGroupInformation ugi1 = UserGroupInformation.getUGIFromSubject(subject);
-    Assert.assertSame(subject, ugi1.getSubject());
+    assertSame(subject, ugi1.getSubject());
     User user = getUser(subject);
-    Assert.assertNotNull(user);
-    Assert.assertEquals(principal.getName(), user.getName());
-    Assert.assertNull(user.getLogin());
+    assertNotNull(user);
+    assertEquals(principal.getName(), user.getName());
+    assertNull(user.getLogin());
 
     // subsequent call should not change the existing User instance.
     UserGroupInformation ugi2 = UserGroupInformation.getUGIFromSubject(subject);
-    Assert.assertSame(subject, ugi2.getSubject());
-    Assert.assertSame(user, getUser(ugi2.getSubject()));
-    Assert.assertNull(user.getLogin());
+    assertSame(subject, ugi2.getSubject());
+    assertSame(user, getUser(ugi2.getSubject()));
+    assertNull(user.getLogin());
   }
 
   @Test
@@ -261,9 +261,9 @@ public class TestUGILoginFromKeytab {
 
     // nothing should change.
     UserGroupInformation ugi2 = UserGroupInformation.getUGIFromSubject(subject);
-    Assert.assertSame(subject, ugi2.getSubject());
-    Assert.assertSame(user, getUser(ugi2.getSubject()));
-    Assert.assertSame(dummyLogin, user.getLogin());
+    assertSame(subject, ugi2.getSubject());
+    assertSame(user, getUser(ugi2.getSubject()));
+    assertSame(dummyLogin, user.getLogin());
   }
 
   @Test
@@ -282,14 +282,12 @@ public class TestUGILoginFromKeytab {
 
     UserGroupInformation ugi = UserGroupInformation.getLoginUser();
 
-    Assert.assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS,
+    assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS,
         ugi.getAuthenticationMethod());
-    Assert.assertTrue(ugi.isFromKeytab());
-    Assert.assertTrue(
-            UserGroupInformation.isKerberosKeyTabLoginRenewalEnabled());
-    Assert.assertTrue(
-            UserGroupInformation.getKerberosLoginRenewalExecutor()
-                    .isPresent());
+    assertTrue(ugi.isFromKeytab());
+    assertTrue(UserGroupInformation.isKerberosKeyTabLoginRenewalEnabled());
+    assertTrue(UserGroupInformation.getKerberosLoginRenewalExecutor()
+        .isPresent());
   }
 
   @Test
@@ -309,14 +307,12 @@ public class TestUGILoginFromKeytab {
     UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath());
 
     UserGroupInformation ugi = UserGroupInformation.getLoginUser();
-    Assert.assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS,
-            ugi.getAuthenticationMethod());
-    Assert.assertTrue(ugi.isFromKeytab());
-    Assert.assertFalse(
-            UserGroupInformation.isKerberosKeyTabLoginRenewalEnabled());
-    Assert.assertFalse(
-            UserGroupInformation.getKerberosLoginRenewalExecutor()
-                    .isPresent());
+    assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS,
+        ugi.getAuthenticationMethod());
+    assertTrue(ugi.isFromKeytab());
+    assertFalse(UserGroupInformation.isKerberosKeyTabLoginRenewalEnabled());
+    assertFalse(UserGroupInformation.getKerberosLoginRenewalExecutor()
+        .isPresent());
   }
 
   private static KerberosTicket getTicket(UserGroupInformation ugi) {
@@ -329,13 +325,11 @@ public class TestUGILoginFromKeytab {
   // the expected principal.
   private static KerberosTicket checkTicketAndKeytab(UserGroupInformation ugi,
       KerberosPrincipal principal, boolean expectIsKeytab) {
-    Assert.assertEquals("wrong principal",
-      principal.getName(), ugi.getUserName());
-    Assert.assertEquals("is not keytab",
-      expectIsKeytab, ugi.isFromKeytab());
+    assertEquals(principal.getName(), ugi.getUserName(), "wrong principal");
+    assertEquals(expectIsKeytab, ugi.isFromKeytab(), "is not keytab");
     KerberosTicket ticket = getTicket(ugi);
-    Assert.assertNotNull("no ticket", ticket);
-    Assert.assertEquals("wrong principal", principal, ticket.getClient());
+    assertNotNull(ticket, "no ticket");
+    assertEquals(principal, ticket.getClient(), "wrong principal");
     return ticket;
   }
 
@@ -377,16 +371,16 @@ public class TestUGILoginFromKeytab {
         loginUser.reloginFromKeytab();
         KerberosTicket newLoginTicket =
             checkTicketAndKeytab(loginUser, principal1, true);
-        Assert.assertNotEquals(loginTicket.getAuthTime(),
+        assertNotEquals(loginTicket.getAuthTime(),
             newLoginTicket.getAuthTime());
 
         // verify an "external" subject ticket does not change.
         extSubjectUser.reloginFromKeytab();
-        Assert.assertSame(ticket,
+        assertSame(ticket,
             checkTicketAndKeytab(extSubjectUser, principal2, false));
 
         // verify subject ugi relogin did not affect the login user.
-        Assert.assertSame(newLoginTicket,
+        assertSame(newLoginTicket,
             checkTicketAndKeytab(loginUser, principal1, true));
 
         return null;
@@ -409,7 +403,7 @@ public class TestUGILoginFromKeytab {
         principal1.getName(), keytab1.getPath());
     final UserGroupInformation originalLoginUser =
         UserGroupInformation.getLoginUser();
-    Assert.assertNotNull(getUser(originalLoginUser.getSubject()).getLogin());
+    assertNotNull(getUser(originalLoginUser.getSubject()).getLogin());
 
     originalLoginUser.doAs(new PrivilegedExceptionAction<Void>() {
       @Override
@@ -426,7 +420,7 @@ public class TestUGILoginFromKeytab {
 
         // verify the new login user is external.
         UserGroupInformation.loginUserFromSubject(subject);
-        Assert.assertNull(getUser(subject).getLogin());
+        assertNull(getUser(subject).getLogin());
         UserGroupInformation extLoginUser =
           UserGroupInformation.getLoginUser();
         KerberosTicket extLoginUserTicket =
@@ -435,17 +429,17 @@ public class TestUGILoginFromKeytab {
         // verify subject-based login user does not get a new ticket, and
         // original login user not affected.
         extLoginUser.reloginFromKeytab();
-        Assert.assertSame(extLoginUserTicket,
-          checkTicketAndKeytab(extLoginUser, principal2, false));
-        Assert.assertSame(originalLoginUserTicket,
-          checkTicketAndKeytab(originalLoginUser, principal1, true));
+        assertSame(extLoginUserTicket,
+            checkTicketAndKeytab(extLoginUser, principal2, false));
+        assertSame(originalLoginUserTicket,
+            checkTicketAndKeytab(originalLoginUser, principal1, true));
 
         // verify original login user gets a new ticket, new login user
         // not affected.
         originalLoginUser.reloginFromKeytab();
-        Assert.assertNotSame(originalLoginUserTicket,
+        assertNotSame(originalLoginUserTicket,
             checkTicketAndKeytab(originalLoginUser, principal1, true));
-        Assert.assertSame(extLoginUserTicket,
+        assertSame(extLoginUserTicket,
             checkTicketAndKeytab(extLoginUser, principal2, false));
         return null;
       }
@@ -465,27 +459,28 @@ public class TestUGILoginFromKeytab {
     checkTicketAndKeytab(loginUser, principal, true);
 
     // move the keytab to induce a relogin failure.
-    Assert.assertTrue(keytab.renameTo(keytabBackup));
+    assertTrue(keytab.renameTo(keytabBackup));
     try {
       loginUser.reloginFromKeytab();
-      Assert.fail("relogin should fail");
+      fail("relogin should fail");
     } catch (KerberosAuthException kae) {
       // expected.
     }
 
     // even though no KeyTab object, ugi should know it's keytab based.
-    Assert.assertTrue(loginUser.isFromKeytab());
-    Assert.assertNull(getTicket(loginUser));
+    assertTrue(loginUser.isFromKeytab());
+    assertNull(getTicket(loginUser));
 
     // move keytab back to enable relogin to succeed.
-    Assert.assertTrue(keytabBackup.renameTo(keytab));
+    assertTrue(keytabBackup.renameTo(keytab));
     loginUser.reloginFromKeytab();
     checkTicketAndKeytab(loginUser, principal, true);
   }
 
   // verify getting concurrent relogins blocks to avoid indeterminate
   // credentials corruption, but getting a ugi for the subject does not block.
-  @Test(timeout=180000)
+  @Test
+  @Timeout(value = 180)
   public void testConcurrentRelogin() throws Exception {
     final CyclicBarrier barrier = new CyclicBarrier(2);
     final CountDownLatch latch = new CountDownLatch(1);
@@ -537,8 +532,7 @@ public class TestUGILoginFromKeytab {
         });
     // wait for the thread to block on the barrier in the logout of the
     // relogin.
-    assertTrue("first relogin didn't block",
-      latch.await(2, TimeUnit.SECONDS));
+    assertTrue(latch.await(2, TimeUnit.SECONDS), "first relogin didn't block");
 
     // although the logout removed the keytab instance, verify the ugi
     // knows from its login params that it is supposed to be from a keytab.

+ 12 - 10
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGIWithExternalKdc.java

@@ -18,15 +18,17 @@ package org.apache.hadoop.security;
 
 import java.io.IOException;
 
-import org.junit.Assert;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
 import static org.apache.hadoop.security.SecurityUtilTestHelper.isExternalKdcRunning;
 import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 /**
  * Tests kerberos keytab login using a user-specified external KDC
@@ -39,17 +41,17 @@ import org.junit.Test;
  */
 public class TestUGIWithExternalKdc {
 
-  @Before
+  @BeforeEach
   public void testExternalKdcRunning() {
-    Assume.assumeTrue(isExternalKdcRunning());
+    assumeTrue(isExternalKdcRunning());
   }
 
   @Test
   public void testLogin() throws IOException {
     String userPrincipal = System.getProperty("user.principal");
     String userKeyTab = System.getProperty("user.keytab");
-    Assert.assertNotNull("User principal was not specified", userPrincipal);
-    Assert.assertNotNull("User keytab was not specified", userKeyTab);
+    assertNotNull(userPrincipal, "User principal was not specified");
+    assertNotNull(userKeyTab, "User keytab was not specified");
 
     Configuration conf = new Configuration();
     conf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
@@ -59,13 +61,13 @@ public class TestUGIWithExternalKdc {
     UserGroupInformation ugi = UserGroupInformation
         .loginUserFromKeytabAndReturnUGI(userPrincipal, userKeyTab);
 
-    Assert.assertEquals(AuthenticationMethod.KERBEROS,
+    assertEquals(AuthenticationMethod.KERBEROS,
         ugi.getAuthenticationMethod());
     
     try {
       UserGroupInformation
       .loginUserFromKeytabAndReturnUGI("bogus@EXAMPLE.COM", userKeyTab);
-      Assert.fail("Login should have failed");
+      fail("Login should have failed");
     } catch (Exception ex) {
       ex.printStackTrace();
     }

+ 6 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGIWithMiniKdc.java

@@ -22,8 +22,9 @@ import org.apache.hadoop.minikdc.MiniKdc;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.test.LambdaTestUtils;
 
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.event.Level;
 
 import javax.security.auth.kerberos.KerberosPrincipal;
@@ -43,7 +44,7 @@ public class TestUGIWithMiniKdc {
 
   private static MiniKdc kdc;
 
-  @After
+  @AfterEach
   public void teardown() {
     UserGroupInformation.reset();
     if (kdc != null) {
@@ -63,7 +64,8 @@ public class TestUGIWithMiniKdc {
     kdc.start();
   }
 
-  @Test(timeout = 120000)
+  @Test
+  @Timeout(value = 120)
   public void testAutoRenewalThreadRetryWithKdc() throws Exception {
     GenericTestUtils.setLogLevel(UserGroupInformation.LOG, Level.DEBUG);
     final Configuration conf = new Configuration();

+ 4 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUserFromEnv.java

@@ -18,15 +18,16 @@
 package org.apache.hadoop.security;
 
 import java.io.IOException;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TestUserFromEnv {
 
   @Test
   public void testUserFromEnvironment() throws IOException {
     System.setProperty(UserGroupInformation.HADOOP_USER_NAME, "randomUser");
-    Assert.assertEquals("randomUser", UserGroupInformation.getLoginUser()
+    assertEquals("randomUser", UserGroupInformation.getLoginUser()
         .getUserName());
   }
 }

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestWhitelistBasedResolver.java

@@ -21,8 +21,8 @@ import java.io.IOException;
 import java.net.InetAddress;
 import java.util.Map;
 
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.util.TestFileBasedIPList;

+ 20 - 20
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredShell.java

@@ -17,9 +17,9 @@
  */
 package org.apache.hadoop.security.alias;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -33,8 +33,8 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.security.ProviderUtils;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.assertj.core.api.Assertions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class TestCredShell {
   private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@@ -49,7 +49,7 @@ public class TestCredShell {
       .contains(expected);
   }
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     System.setOut(new PrintStream(outContent));
     System.setErr(new PrintStream(errContent));
@@ -67,7 +67,7 @@ public class TestCredShell {
     CredentialShell cs = new CredentialShell();
     cs.setConf(new Configuration());
     rc = cs.run(args1);
-    assertEquals(outContent.toString(), 0, rc);
+    assertEquals(0, rc, outContent.toString());
     assertTrue(outContent.toString().contains("credential1 has been successfully " +
     		"created."));
     assertTrue(outContent.toString()
@@ -97,7 +97,7 @@ public class TestCredShell {
         jceksProvider};
     rc = cs.run(args5);
     assertEquals(0, rc);
-    assertFalse(outContent.toString(), outContent.toString().contains("credential1"));
+    assertFalse(outContent.toString().contains("credential1"), outContent.toString());
   }
 
   @Test
@@ -123,13 +123,13 @@ public class TestCredShell {
     CredentialShell cs = new CredentialShell();
     cs.setConf(new Configuration());
     rc = cs.run(args1);
-    assertEquals(outContent.toString(), 0, rc);
+    assertEquals(0, rc, outContent.toString());
     assertTrue(outContent.toString().contains("WARNING: you are modifying a " +
     		"transient provider."));
 
     String[] args2 = {"delete", "credential1", "-f", "-provider", "user:///"};
     rc = cs.run(args2);
-    assertEquals(outContent.toString(), 0, rc);
+    assertEquals(0, rc, outContent.toString());
     assertTrue(outContent.toString().contains("credential1 has been successfully " +
         "deleted."));
   }
@@ -161,7 +161,7 @@ public class TestCredShell {
     shell.setConf(new Configuration());
     shell.setPasswordReader(new MockPasswordReader(passwords));
     rc = shell.run(args1);
-    assertEquals(outContent.toString(), 1, rc);
+    assertEquals(1, rc, outContent.toString());
     assertTrue(outContent.toString().contains("Passwords don't match"));
   }
 
@@ -249,8 +249,8 @@ public class TestCredShell {
     for (String cmd : Arrays.asList("create", "list", "delete")) {
       CredentialShell shell = new CredentialShell();
       shell.setConf(new Configuration());
-      assertEquals("Expected help argument on " + cmd + " to return 0",
-              0, shell.init(new String[] {cmd, "-help"}));
+      assertEquals(0, shell.init(new String[] {cmd, "-help"}),
+          "Expected help argument on " + cmd + " to return 0");
     }
   }
 
@@ -258,13 +258,13 @@ public class TestCredShell {
   public void testEmptyArgForCommands() throws Exception {
     CredentialShell shell = new CredentialShell();
     String[] command = { "list", "-provider" };
-    assertEquals("Expected empty argument on " + command + " to return 1", 1,
-        shell.init(command));
+    assertEquals(1,
+        shell.init(command), "Expected empty argument on " + command + " to return 1");
 
     for (String cmd : Arrays.asList("create", "delete")) {
       shell.setConf(new Configuration());
-      assertEquals("Expected empty argument on " + cmd + " to return 1", 1,
-          shell.init(new String[] { cmd }));
+      assertEquals(1, shell.init(new String[]{cmd}),
+          "Expected empty argument on " + cmd + " to return 1");
     }
   }
 
@@ -277,7 +277,7 @@ public class TestCredShell {
     CredentialShell cs = new CredentialShell();
     cs.setConf(new Configuration());
     rc = cs.run(args1);
-    assertEquals(outContent.toString(), 1, rc);
+    assertEquals(1, rc, outContent.toString());
     assertFalse(outContent.toString().contains("credential1 has been " +
         "successfully created."));
     assertTrue(outContent.toString()
@@ -294,7 +294,7 @@ public class TestCredShell {
     CredentialShell cs = new CredentialShell();
     cs.setConf(new Configuration());
     rc = cs.run(args1);
-    assertEquals(outContent.toString(), 0, rc);
+    assertEquals(0, rc, outContent.toString());
     assertTrue(outContent.toString().contains("Usage"));
   }
 
@@ -306,7 +306,7 @@ public class TestCredShell {
     CredentialShell cs = new CredentialShell();
     cs.setConf(new Configuration());
     rc = cs.run(args1);
-    assertEquals(outContent.toString(), 0, rc);
+    assertEquals(0, rc, outContent.toString());
     assertTrue(outContent.toString().contains("Usage"));
   }
 }

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredentialProvider.java

@@ -19,12 +19,12 @@ package org.apache.hadoop.security.alias;
 
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.security.ProviderUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import java.net.URI;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 
 public class TestCredentialProvider {
 

+ 23 - 27
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/alias/TestCredentialProviderFactory.java

@@ -33,28 +33,24 @@ import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.security.ProviderUtils;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class TestCredentialProviderFactory {
   public static final Logger LOG =
       LoggerFactory.getLogger(TestCredentialProviderFactory.class);
 
-  @Rule
-  public final TestName test = new TestName();
-
-  @Before
-  public void announce() {
-    LOG.info("Running test " + test.getMethodName());
+  @BeforeEach
+  public void announce(TestInfo testInfo) {
+    LOG.info("Running test " + testInfo.getDisplayName());
   }
 
   private static char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
@@ -90,7 +86,7 @@ public class TestCredentialProviderFactory {
     try {
       List<CredentialProvider> providers = 
           CredentialProviderFactory.getProviders(conf);
-      assertTrue("should throw!", false);
+      assertTrue(false, "should throw!");
     } catch (IOException e) {
       assertEquals("No CredentialProviderFactory for unknown:/// in " +
           CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
@@ -105,7 +101,7 @@ public class TestCredentialProviderFactory {
     try {
       List<CredentialProvider> providers = 
           CredentialProviderFactory.getProviders(conf);
-      assertTrue("should throw!", false);
+      assertTrue(false, "should throw!");
     } catch (IOException e) {
       assertEquals("Bad configuration of " +
           CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH +
@@ -143,14 +139,14 @@ public class TestCredentialProviderFactory {
     // try recreating pass
     try {
       provider.createCredentialEntry("pass", passwd);
-      assertTrue("should throw", false);
+      assertTrue(false, "should throw");
     } catch (IOException e) {
       assertEquals("Credential pass already exists in " + ourUrl, e.getMessage());
     }
     provider.deleteCredentialEntry("pass");
     try {
       provider.deleteCredentialEntry("pass");
-      assertTrue("should throw", false);
+      assertTrue(false, "should throw");
     } catch (IOException e) {
       assertEquals("Credential pass does not exist in " + ourUrl, e.getMessage());
     }
@@ -183,9 +179,9 @@ public class TestCredentialProviderFactory {
     assertArrayEquals(passwd, provider.getCredentialEntry("pass").getCredential());
 
     List<String> creds = provider.getAliases();
-    assertTrue("Credentials should have been returned.", creds.size() == 2);
-    assertTrue("Returned Credentials should have included pass.", creds.contains("pass"));
-    assertTrue("Returned Credentials should have included pass2.", creds.contains("pass2"));
+    assertTrue(creds.size() == 2, "Credentials should have been returned.");
+    assertTrue(creds.contains("pass"), "Returned Credentials should have included pass.");
+    assertTrue(creds.contains("pass2"), "Returned Credentials should have included pass2.");
   }
 
   @Test
@@ -216,7 +212,7 @@ public class TestCredentialProviderFactory {
     FileSystem fs = path.getFileSystem(conf);
     FileStatus s = fs.getFileStatus(path);
     assertEquals("rw-------", s.getPermission().toString());
-    assertTrue(file + " should exist", file.isFile());
+    assertTrue(file.isFile(), file + " should exist");
 
     // check permission retention after explicit change
     fs.setPermission(path, new FsPermission("777"));
@@ -237,9 +233,9 @@ public class TestCredentialProviderFactory {
     Path path = ProviderUtils.unnestUri(new URI(ourUrl));
     FileSystem fs = path.getFileSystem(conf);
     FileStatus s = fs.getFileStatus(path);
-    assertEquals("Unexpected permissions: " + s.getPermission().toString(),
-        "rw-------", s.getPermission().toString());
-    assertTrue(file + " should exist", file.isFile());
+    assertEquals("rw-------", s.getPermission().toString(),
+        "Unexpected permissions: " + s.getPermission().toString());
+    assertTrue(file.isFile(), file + " should exist");
 
     // check permission retention after explicit change
     fs.setPermission(path, new FsPermission("777"));
@@ -280,7 +276,7 @@ public class TestCredentialProviderFactory {
 
     FileSystem fs = path.getFileSystem(conf);
     FileStatus s = fs.getFileStatus(path);
-    assertEquals("Permissions should have been retained from the preexisting " +
-        "keystore.", "rwxrwxrwx", s.getPermission().toString());
+    assertEquals("rwxrwxrwx", s.getPermission().toString(),
+        "Permissions should have been retained from the preexisting keystore.");
   }
 }

+ 4 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authentication/server/TestProxyUserAuthenticationFilter.java

@@ -39,7 +39,8 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.mockito.Mockito;
 
 
@@ -271,7 +272,8 @@ public class TestProxyUserAuthenticationFilter {
   }
 
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testFilter() throws Exception {
     Map<String, String> params = new HashMap<String, String>();
     params.put("proxyuser.knox.users", "testuser");

+ 11 - 12
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestAccessControlList.java

@@ -17,8 +17,8 @@
  */
 package org.apache.hadoop.security.authorize;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.Collection;
 import java.util.Iterator;
@@ -31,7 +31,7 @@ import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
 import org.apache.hadoop.security.Groups;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.util.NativeCodeLoader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -461,15 +461,14 @@ public class TestAccessControlList {
 
   private void assertUserAllowed(UserGroupInformation ugi,
       AccessControlList acl) {
-    assertTrue("User " + ugi + " is not granted the access-control!!",
-        acl.isUserAllowed(ugi));
+    assertTrue(acl.isUserAllowed(ugi),
+        "User " + ugi + " is not granted the access-control!!");
   }
 
   private void assertUserNotAllowed(UserGroupInformation ugi,
       AccessControlList acl) {
-    assertFalse("User " + ugi
-        + " is incorrectly granted the access-control!!",
-        acl.isUserAllowed(ugi));
+    assertFalse(acl.isUserAllowed(ugi), "User " + ugi
+        + " is incorrectly granted the access-control!!");
   }
 
   @Test
@@ -481,12 +480,12 @@ public class TestAccessControlList {
     UserGroupInformation user1 =
         UserGroupInformation.createProxyUserForTesting("regularJane",
             realUserUgi, new String [] {"group1"});
-    assertFalse("User " + user1 + " should not have been granted access.",
-        acl.isUserAllowed(user1));
+    assertFalse(acl.isUserAllowed(user1),
+        "User " + user1 + " should not have been granted access.");
 
     acl = new AccessControlList(AccessControlList.USE_REAL_ACLS + realUser);
 
-    assertTrue("User " + user1 + " should have access but was denied.",
-        acl.isUserAllowed(user1));
+    assertTrue(acl.isUserAllowed(user1),
+        "User " + user1 + " should have access but was denied.");
   }
 }

+ 5 - 5
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestDefaultImpersonationProvider.java

@@ -22,10 +22,10 @@ import static org.mockito.Mockito.when;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
 import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.junit.rules.Timeout;
 import org.mockito.Mockito;
 
@@ -47,7 +47,7 @@ public class TestDefaultImpersonationProvider {
   @Rule
   public Timeout globalTimeout = new Timeout(10000, TimeUnit.MILLISECONDS);
 
-  @Before
+  @BeforeEach
   public void setup() {
     conf = new Configuration();
     provider = new DefaultImpersonationProvider();
@@ -91,7 +91,7 @@ public class TestDefaultImpersonationProvider {
         provider.authorize(userGroupInformation, "2.2.2.2"));
   }
 
-  @After
+  @AfterEach
   public void clear() {
     provider = null;
     conf = null;

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestProxyServers.java

@@ -17,11 +17,11 @@
  */
 package org.apache.hadoop.security.authorize;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.hadoop.conf.Configuration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestProxyServers {
 

+ 39 - 43
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestProxyUsers.java

@@ -17,9 +17,6 @@
  */
 package org.apache.hadoop.security.authorize;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -33,10 +30,12 @@ import org.apache.hadoop.security.Groups;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.util.NativeCodeLoader;
 import org.apache.hadoop.util.StringUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static org.junit.jupiter.api.Assertions.*;
+
 
 public class TestProxyUsers {
   private static final Logger LOG =
@@ -336,43 +335,39 @@ public class TestProxyUsers {
     assertNotAuthorized(proxyUserUgi, "10.221.0.0");
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testNullUser() throws Exception {
-    Configuration conf = new Configuration();
-    conf.set(
-        DefaultImpersonationProvider.getTestProvider().
-            getProxySuperuserGroupConfKey(REAL_USER_NAME),
-        "*");
-    conf.set(
-        DefaultImpersonationProvider.getTestProvider().
-            getProxySuperuserIpConfKey(REAL_USER_NAME),
-        PROXY_IP_RANGE);
-    ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
-    // user is null
-    ProxyUsers.authorize(null, "10.222.0.0");
+    assertThrows(IllegalArgumentException.class, () -> {
+      Configuration conf = new Configuration();
+      conf.set(DefaultImpersonationProvider.getTestProvider().
+          getProxySuperuserGroupConfKey(REAL_USER_NAME), "*");
+      conf.set(DefaultImpersonationProvider.getTestProvider().
+          getProxySuperuserIpConfKey(REAL_USER_NAME), PROXY_IP_RANGE);
+      ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
+      // user is null
+      ProxyUsers.authorize(null, "10.222.0.0");
+    });
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testNullIpAddress() throws Exception {
-    Configuration conf = new Configuration();
-    conf.set(
-        DefaultImpersonationProvider.getTestProvider().
-            getProxySuperuserGroupConfKey(REAL_USER_NAME),
-        "*");
-    conf.set(
-        DefaultImpersonationProvider.getTestProvider().
-            getProxySuperuserIpConfKey(REAL_USER_NAME),
-        PROXY_IP_RANGE);
-    ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
-
-    // First try proxying a group that's allowed
-    UserGroupInformation realUserUgi = UserGroupInformation
-        .createRemoteUser(REAL_USER_NAME);
-    UserGroupInformation proxyUserUgi = UserGroupInformation.createProxyUserForTesting(
-        PROXY_USER_NAME, realUserUgi, GROUP_NAMES);
-
-    // remote address is null
-    ProxyUsers.authorize(proxyUserUgi, (InetAddress) null);
+    assertThrows(IllegalArgumentException.class, () -> {
+      Configuration conf = new Configuration();
+      conf.set(DefaultImpersonationProvider.getTestProvider().
+          getProxySuperuserGroupConfKey(REAL_USER_NAME), "*");
+      conf.set(DefaultImpersonationProvider.getTestProvider().
+          getProxySuperuserIpConfKey(REAL_USER_NAME), PROXY_IP_RANGE);
+      ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
+
+      // First try proxying a group that's allowed
+      UserGroupInformation realUserUgi = UserGroupInformation
+          .createRemoteUser(REAL_USER_NAME);
+      UserGroupInformation proxyUserUgi = UserGroupInformation.createProxyUserForTesting(
+          PROXY_USER_NAME, realUserUgi, GROUP_NAMES);
+
+      // remote address is null
+      ProxyUsers.authorize(proxyUserUgi, (InetAddress) null);
+    });
   }
 
   @Test
@@ -476,16 +471,17 @@ public class TestProxyUsers {
     assertEquals (GROUP_NAMES.length, groupsToBeProxied.size());
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testProxyUsersWithNullPrefix() throws Exception {
-    ProxyUsers.refreshSuperUserGroupsConfiguration(new Configuration(false), 
-        null);
+    assertThrows(IllegalArgumentException.class,
+        ()-> ProxyUsers.refreshSuperUserGroupsConfiguration(new Configuration(false), null));
   }
 
-  @Test(expected = IllegalArgumentException.class)
+  @Test
   public void testProxyUsersWithEmptyPrefix() throws Exception {
-    ProxyUsers.refreshSuperUserGroupsConfiguration(new Configuration(false), 
-        "");
+    assertThrows(IllegalArgumentException.class, () -> {
+      ProxyUsers.refreshSuperUserGroupsConfiguration(new Configuration(false), "");
+    });
   }
 
   @Test

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestServiceAuthorization.java

@@ -17,8 +17,8 @@
  */
 package org.apache.hadoop.security.authorize;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.lang.annotation.Annotation;
 import java.net.InetAddress;
@@ -32,7 +32,7 @@ import org.apache.hadoop.security.SecurityInfo;
 import org.apache.hadoop.security.SecurityUtil;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.TokenInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestServiceAuthorization {
 

+ 89 - 88
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestCrossOriginFilter.java

@@ -32,9 +32,14 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.hadoop.security.http.CrossOriginFilter;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import static org.apache.hadoop.test.MockitoUtil.verifyZeroInteractions;
 
@@ -49,12 +54,12 @@ public class TestCrossOriginFilter {
     FilterConfig filterConfig = new FilterConfigTest(conf);
 
     // Origin is not specified for same origin requests
-    HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
-    Mockito.when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn(null);
+    HttpServletRequest mockReq = mock(HttpServletRequest.class);
+    when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn(null);
 
     // Objects to verify interactions based on request
-    HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
-    FilterChain mockChain = Mockito.mock(FilterChain.class);
+    HttpServletResponse mockRes = mock(HttpServletResponse.class);
+    FilterChain mockChain = mock(FilterChain.class);
 
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
@@ -62,7 +67,7 @@ public class TestCrossOriginFilter {
     filter.doFilter(mockReq, mockRes, mockChain);
 
     verifyZeroInteractions(mockRes);
-    Mockito.verify(mockChain).doFilter(mockReq, mockRes);
+    verify(mockChain).doFilter(mockReq, mockRes);
   }
 
   @Test
@@ -76,28 +81,28 @@ public class TestCrossOriginFilter {
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
     filter.init(filterConfig);
-    Assert.assertTrue(filter.areOriginsAllowed("example.com"));
+    assertTrue(filter.areOriginsAllowed("example.com"));
   }
 
   @Test
   public void testEncodeHeaders() {
     String validOrigin = "http://localhost:12345";
     String encodedValidOrigin = CrossOriginFilter.encodeHeader(validOrigin);
-    Assert.assertEquals("Valid origin encoding should match exactly",
-        validOrigin, encodedValidOrigin);
+    assertEquals(validOrigin, encodedValidOrigin,
+        "Valid origin encoding should match exactly");
 
     String httpResponseSplitOrigin = validOrigin + " \nSecondHeader: value";
     String encodedResponseSplitOrigin =
       CrossOriginFilter.encodeHeader(httpResponseSplitOrigin);
-    Assert.assertEquals("Http response split origin should be protected against",
-        validOrigin, encodedResponseSplitOrigin);
+    assertEquals(validOrigin, encodedResponseSplitOrigin,
+        "Http response split origin should be protected against");
 
     // Test Origin List
     String validOriginList = "http://foo.example.com:12345 http://bar.example.com:12345";
     String encodedValidOriginList = CrossOriginFilter
         .encodeHeader(validOriginList);
-    Assert.assertEquals("Valid origin list encoding should match exactly",
-        validOriginList, encodedValidOriginList);
+    assertEquals(validOriginList, encodedValidOriginList,
+        "Valid origin list encoding should match exactly");
   }
 
   @Test
@@ -113,17 +118,17 @@ public class TestCrossOriginFilter {
     filter.init(filterConfig);
 
     // match multiple sub-domains
-    Assert.assertFalse(filter.areOriginsAllowed("example.com"));
-    Assert.assertFalse(filter.areOriginsAllowed("foo:example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.bar.example.com"));
+    assertFalse(filter.areOriginsAllowed("example.com"));
+    assertFalse(filter.areOriginsAllowed("foo:example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.bar.example.com"));
 
     // First origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example.com foo.nomatch.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example.com foo.nomatch.com"));
     // Second origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example.com"));
     // No origin in list is allowed
-    Assert.assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
+    assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
   }
 
   @Test
@@ -139,17 +144,17 @@ public class TestCrossOriginFilter {
     filter.init(filterConfig);
 
     // match multiple sub-domains
-    Assert.assertFalse(filter.areOriginsAllowed("example.com"));
-    Assert.assertFalse(filter.areOriginsAllowed("foo:example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.bar.example.com"));
+    assertFalse(filter.areOriginsAllowed("example.com"));
+    assertFalse(filter.areOriginsAllowed("foo:example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.bar.example.com"));
 
     // First origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example.com foo.nomatch.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example.com foo.nomatch.com"));
     // Second origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example.com"));
+    assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example.com"));
     // No origin in list is allowed
-    Assert.assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
+    assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
   }
 
   @Test
@@ -164,13 +169,13 @@ public class TestCrossOriginFilter {
     CrossOriginFilter filter = new CrossOriginFilter();
     filter.init(filterConfig);
 
-    Assert.assertTrue(filter.areOriginsAllowed("http://sub1.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("https://sub1.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("http://sub1.example.com:1234"));
-    Assert.assertTrue(filter.areOriginsAllowed("https://sub1.example.com:8080"));
+    assertTrue(filter.areOriginsAllowed("http://sub1.example.com"));
+    assertTrue(filter.areOriginsAllowed("https://sub1.example.com"));
+    assertTrue(filter.areOriginsAllowed("http://sub1.example.com:1234"));
+    assertTrue(filter.areOriginsAllowed("https://sub1.example.com:8080"));
 
     // No origin in list is allowed
-    Assert.assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
+    assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
   }
 
   @Test
@@ -186,23 +191,23 @@ public class TestCrossOriginFilter {
     CrossOriginFilter filter = new CrossOriginFilter();
     filter.init(filterConfig);
 
-    Assert.assertTrue(filter.areOriginsAllowed("http://sub1.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("https://sub1.example.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("http://sub1.example.com:1234"));
-    Assert.assertTrue(filter.areOriginsAllowed("https://sub1.example.com:8080"));
+    assertTrue(filter.areOriginsAllowed("http://sub1.example.com"));
+    assertTrue(filter.areOriginsAllowed("https://sub1.example.com"));
+    assertTrue(filter.areOriginsAllowed("http://sub1.example.com:1234"));
+    assertTrue(filter.areOriginsAllowed("https://sub1.example.com:8080"));
 
     // match multiple sub-domains
-    Assert.assertFalse(filter.areOriginsAllowed("example2.com"));
-    Assert.assertFalse(filter.areOriginsAllowed("foo:example2.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example2.com"));
-    Assert.assertTrue(filter.areOriginsAllowed("foo.bar.example2.com"));
+    assertFalse(filter.areOriginsAllowed("example2.com"));
+    assertFalse(filter.areOriginsAllowed("foo:example2.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example2.com"));
+    assertTrue(filter.areOriginsAllowed("foo.bar.example2.com"));
 
     // First origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.example2.com foo.nomatch.com"));
+    assertTrue(filter.areOriginsAllowed("foo.example2.com foo.nomatch.com"));
     // Second origin is allowed
-    Assert.assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example2.com"));
+    assertTrue(filter.areOriginsAllowed("foo.nomatch.com foo.example2.com"));
     // No origin in list is allowed
-    Assert.assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
+    assertFalse(filter.areOriginsAllowed("foo.nomatch1.com foo.nomatch2.com"));
   }
 
   @Test
@@ -214,12 +219,12 @@ public class TestCrossOriginFilter {
     FilterConfig filterConfig = new FilterConfigTest(conf);
 
     // Origin is not specified for same origin requests
-    HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
-    Mockito.when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.org");
+    HttpServletRequest mockReq = mock(HttpServletRequest.class);
+    when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.org");
 
     // Objects to verify interactions based on request
-    HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
-    FilterChain mockChain = Mockito.mock(FilterChain.class);
+    HttpServletResponse mockRes = mock(HttpServletResponse.class);
+    FilterChain mockChain = mock(FilterChain.class);
 
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
@@ -227,7 +232,7 @@ public class TestCrossOriginFilter {
     filter.doFilter(mockReq, mockRes, mockChain);
 
     verifyZeroInteractions(mockRes);
-    Mockito.verify(mockChain).doFilter(mockReq, mockRes);
+    verify(mockChain).doFilter(mockReq, mockRes);
   }
 
   @Test
@@ -239,15 +244,15 @@ public class TestCrossOriginFilter {
     FilterConfig filterConfig = new FilterConfigTest(conf);
 
     // Origin is not specified for same origin requests
-    HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
-    Mockito.when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
-    Mockito.when(
+    HttpServletRequest mockReq = mock(HttpServletRequest.class);
+    when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
+    when(
         mockReq.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD))
         .thenReturn("DISALLOWED_METHOD");
 
     // Objects to verify interactions based on request
-    HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
-    FilterChain mockChain = Mockito.mock(FilterChain.class);
+    HttpServletResponse mockRes = mock(HttpServletResponse.class);
+    FilterChain mockChain = mock(FilterChain.class);
 
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
@@ -255,7 +260,7 @@ public class TestCrossOriginFilter {
     filter.doFilter(mockReq, mockRes, mockChain);
 
     verifyZeroInteractions(mockRes);
-    Mockito.verify(mockChain).doFilter(mockReq, mockRes);
+    verify(mockChain).doFilter(mockReq, mockRes);
   }
 
   @Test
@@ -267,18 +272,18 @@ public class TestCrossOriginFilter {
     FilterConfig filterConfig = new FilterConfigTest(conf);
 
     // Origin is not specified for same origin requests
-    HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
-    Mockito.when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
-    Mockito.when(
+    HttpServletRequest mockReq = mock(HttpServletRequest.class);
+    when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
+    when(
         mockReq.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD))
         .thenReturn("GET");
-    Mockito.when(
+    when(
         mockReq.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS))
         .thenReturn("Disallowed-Header");
 
     // Objects to verify interactions based on request
-    HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
-    FilterChain mockChain = Mockito.mock(FilterChain.class);
+    HttpServletResponse mockRes = mock(HttpServletResponse.class);
+    FilterChain mockChain = mock(FilterChain.class);
 
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
@@ -286,7 +291,7 @@ public class TestCrossOriginFilter {
     filter.doFilter(mockReq, mockRes, mockChain);
 
     verifyZeroInteractions(mockRes);
-    Mockito.verify(mockChain).doFilter(mockReq, mockRes);
+    verify(mockChain).doFilter(mockReq, mockRes);
   }
 
   @Test
@@ -298,34 +303,34 @@ public class TestCrossOriginFilter {
     FilterConfig filterConfig = new FilterConfigTest(conf);
 
     // Origin is not specified for same origin requests
-    HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
-    Mockito.when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
-    Mockito.when(
+    HttpServletRequest mockReq = mock(HttpServletRequest.class);
+    when(mockReq.getHeader(CrossOriginFilter.ORIGIN)).thenReturn("example.com");
+    when(
         mockReq.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD))
         .thenReturn("GET");
-    Mockito.when(
+    when(
         mockReq.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS))
         .thenReturn("X-Requested-With");
 
     // Objects to verify interactions based on request
-    HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
-    FilterChain mockChain = Mockito.mock(FilterChain.class);
+    HttpServletResponse mockRes = mock(HttpServletResponse.class);
+    FilterChain mockChain = mock(FilterChain.class);
 
     // Object under test
     CrossOriginFilter filter = new CrossOriginFilter();
     filter.init(filterConfig);
     filter.doFilter(mockReq, mockRes, mockChain);
 
-    Mockito.verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN,
+    verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN,
         "example.com");
-    Mockito.verify(mockRes).setHeader(
+    verify(mockRes).setHeader(
         CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS,
         Boolean.TRUE.toString());
-    Mockito.verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS,
+    verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS,
         filter.getAllowedMethodsHeader());
-    Mockito.verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS,
+    verify(mockRes).setHeader(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS,
         filter.getAllowedHeadersHeader());
-    Mockito.verify(mockChain).doFilter(mockReq, mockRes);
+    verify(mockChain).doFilter(mockReq, mockRes);
   }
 
   @Test
@@ -343,13 +348,11 @@ public class TestCrossOriginFilter {
     filter.init(filterConfig);
 
     //verify filter values
-    Assert.assertTrue("Allowed headers do not match",
-        filter.getAllowedHeadersHeader()
-        .compareTo("X-Requested-With,Accept") == 0);
-    Assert.assertTrue("Allowed methods do not match",
-        filter.getAllowedMethodsHeader()
-        .compareTo("GET,POST") == 0);
-    Assert.assertTrue(filter.areOriginsAllowed("example.com"));
+    assertTrue(filter.getAllowedHeadersHeader().
+        compareTo("X-Requested-With,Accept") == 0, "Allowed headers do not match");
+    assertTrue(filter.getAllowedMethodsHeader().
+        compareTo("GET,POST") == 0, "Allowed methods do not match");
+    assertTrue(filter.areOriginsAllowed("example.com"));
 
     //destroy filter values and clear conf
     filter.destroy();
@@ -365,13 +368,11 @@ public class TestCrossOriginFilter {
     filter.init(filterConfig);
 
     //verify filter values
-    Assert.assertTrue("Allowed headers do not match",
-        filter.getAllowedHeadersHeader()
-        .compareTo("Content-Type,Origin") == 0);
-    Assert.assertTrue("Allowed methods do not match",
-        filter.getAllowedMethodsHeader()
-        .compareTo("GET,HEAD") == 0);
-    Assert.assertTrue(filter.areOriginsAllowed("newexample.com"));
+    assertTrue(filter.getAllowedHeadersHeader().compareTo("Content-Type,Origin") == 0,
+        "Allowed headers do not match");
+    assertTrue(filter.getAllowedMethodsHeader().compareTo("GET,HEAD") == 0,
+        "Allowed methods do not match");
+    assertTrue(filter.areOriginsAllowed("newexample.com"));
 
     //destroy filter values
     filter.destroy();

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestRestCsrfPreventionFilter.java

@@ -29,7 +29,7 @@ import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 
 import static org.apache.hadoop.test.MockitoUtil.verifyZeroInteractions;

+ 13 - 17
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/http/TestXFrameOptionsFilter.java

@@ -24,15 +24,16 @@ import javax.servlet.FilterConfig;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.any;
 
 /**
  * Test the default and customized behaviors of XFrameOptionsFilter.
@@ -57,10 +58,8 @@ public class TestXFrameOptionsFilter {
         @Override
         public Object answer(InvocationOnMock invocation) throws Throwable {
           Object[] args = invocation.getArguments();
-          Assert.assertTrue(
-              "header should be visible inside chain and filters.",
-              ((HttpServletResponse)args[1]).
-              containsHeader(X_FRAME_OPTIONS));
+          assertTrue(((HttpServletResponse)args[1]).containsHeader(X_FRAME_OPTIONS),
+              "header should be visible inside chain and filters.");
             return null;
           }
         }
@@ -71,9 +70,8 @@ public class TestXFrameOptionsFilter {
         @Override
         public Object answer(InvocationOnMock invocation) throws Throwable {
             Object[] args = invocation.getArguments();
-            Assert.assertTrue(
-                "Options value incorrect should be DENY but is: "
-                + args[1], "DENY".equals(args[1]));
+            assertTrue("DENY".equals(args[1]),
+                "Options value incorrect should be DENY but is: " + args[1]);
             headers.add((String)args[1]);
             return null;
           }
@@ -108,12 +106,11 @@ public class TestXFrameOptionsFilter {
         public Object answer(InvocationOnMock invocation) throws Throwable {
           Object[] args = invocation.getArguments();
           HttpServletResponse resp = (HttpServletResponse) args[1];
-          Assert.assertTrue(
-              "Header should be visible inside chain and filters.",
-              resp.containsHeader(X_FRAME_OPTIONS));
+          assertTrue(resp.containsHeader(X_FRAME_OPTIONS),
+              "Header should be visible inside chain and filters.");
           // let's try and set another value for the header and make
           // sure that it doesn't overwrite the configured value
-          Assert.assertTrue(resp instanceof
+          assertTrue(resp instanceof
               XFrameOptionsFilter.XFrameOptionsResponseWrapper);
           resp.setHeader(X_FRAME_OPTIONS, "LJM");
           return null;
@@ -126,9 +123,8 @@ public class TestXFrameOptionsFilter {
         @Override
         public Object answer(InvocationOnMock invocation) throws Throwable {
             Object[] args = invocation.getArguments();
-            Assert.assertEquals(
-                "Options value incorrect should be SAMEORIGIN but is: "
-                + args[1], "SAMEORIGIN", args[1]);
+            assertEquals("SAMEORIGIN", args[1],
+                "Options value incorrect should be SAMEORIGIN but is: " + args[1]);
             headers.add((String)args[1]);
             return null;
           }

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestDelegatingSSLSocketFactory.java

@@ -21,7 +21,7 @@ package org.apache.hadoop.security.ssl;
 import java.io.IOException;
 import java.util.Arrays;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import org.apache.hadoop.util.NativeCodeLoader;
 

+ 174 - 163
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestReloadingX509KeyManager.java

@@ -19,8 +19,9 @@ package org.apache.hadoop.security.ssl;
 
 import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.test.GenericTestUtils;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -34,172 +35,182 @@ import java.util.concurrent.TimeoutException;
 import java.util.function.Supplier;
 
 import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class TestReloadingX509KeyManager {
 
-    private static final String BASEDIR = GenericTestUtils.getTempPath(
-            TestReloadingX509TrustManager.class.getSimpleName());
-
-    private final GenericTestUtils.LogCapturer reloaderLog = GenericTestUtils.LogCapturer.captureLogs(
-            FileMonitoringTimerTask.LOG);
-
-    @BeforeClass
-    public static void setUp() throws Exception {
-        File base = new File(BASEDIR);
-        FileUtil.fullyDelete(base);
-        base.mkdirs();
-    }
-
-    @Test(expected = IOException.class)
-    public void testLoadMissingKeyStore() throws Exception {
-        String keystoreLocation = BASEDIR + "/testmissing.jks";
-
-        ReloadingX509KeystoreManager tm =
-                new ReloadingX509KeystoreManager("jks", keystoreLocation,
-                        "password",
-                        "password");
-    }
-
-    @Test(expected = IOException.class)
-    public void testLoadCorruptKeyStore() throws Exception {
-        String keystoreLocation = BASEDIR + "/testcorrupt.jks";
-        OutputStream os = new FileOutputStream(keystoreLocation);
-        os.write(1);
-        os.close();
-
-        ReloadingX509KeystoreManager tm =
-                new ReloadingX509KeystoreManager("jks", keystoreLocation,
-                        "password",
-                        "password");
+  private static final String BASEDIR = GenericTestUtils.getTempPath(
+      TestReloadingX509TrustManager.class.getSimpleName());
+
+  private final GenericTestUtils.LogCapturer reloaderLog = GenericTestUtils.LogCapturer.captureLogs(
+      FileMonitoringTimerTask.LOG);
+
+  @BeforeAll
+  public static void setUp() throws Exception {
+    File base = new File(BASEDIR);
+    FileUtil.fullyDelete(base);
+    base.mkdirs();
+  }
+
+  @Test
+  public void testLoadMissingKeyStore() throws Exception {
+    assertThrows(IOException.class, () -> {
+      String keystoreLocation = BASEDIR + "/testmissing.jks";
+
+      ReloadingX509KeystoreManager tm =
+          new ReloadingX509KeystoreManager("jks", keystoreLocation,
+          "password",
+          "password");
+    });
+  }
+
+  @Test
+  public void testLoadCorruptKeyStore() throws Exception {
+    assertThrows(IOException.class, () -> {
+      String keystoreLocation = BASEDIR + "/testcorrupt.jks";
+      OutputStream os = new FileOutputStream(keystoreLocation);
+      os.write(1);
+      os.close();
+
+      ReloadingX509KeystoreManager tm =
+          new ReloadingX509KeystoreManager("jks", keystoreLocation,
+          "password", "password");
+    });
+  }
+
+  @Test
+  @Timeout(value = 3000)
+  public void testReload() throws Exception {
+    KeyPair kp = generateKeyPair("RSA");
+    X509Certificate sCert = generateCertificate("CN=localhost, O=server", kp, 30,
+        "SHA1withRSA");
+    String keystoreLocation = BASEDIR + "/testreload.jks";
+    createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), sCert);
+
+    long reloadInterval = 10;
+    Timer fileMonitoringTimer =
+        new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
+    ReloadingX509KeystoreManager tm =
+        new ReloadingX509KeystoreManager("jks", keystoreLocation,
+        "password", "password");
+    try {
+      fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
+          Paths.get(keystoreLocation), tm::loadFrom, null), reloadInterval, reloadInterval);
+      assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
+
+      // Wait so that the file modification time is different
+      Thread.sleep((reloadInterval+ 1000));
+
+      // Change the certificate with a new keypair
+      final KeyPair anotherKP = generateKeyPair("RSA");
+      sCert = KeyStoreTestUtil.generateCertificate("CN=localhost, O=server", anotherKP, 30,
+          "SHA1withRSA");
+      createKeyStore(keystoreLocation, "password", "cert1", anotherKP.getPrivate(), sCert);
+
+      GenericTestUtils.waitFor(new Supplier<Boolean>() {
+          @Override
+          public Boolean get() {
+            return tm.getPrivateKey("cert1").equals(kp.getPrivate());
+          }
+      }, (int) reloadInterval, 100000);
+    } finally {
+      fileMonitoringTimer.cancel();
     }
-
-    @Test (timeout = 3000000)
-    public void testReload() throws Exception {
-        KeyPair kp = generateKeyPair("RSA");
-        X509Certificate sCert = generateCertificate("CN=localhost, O=server", kp, 30,
-                        "SHA1withRSA");
-        String keystoreLocation = BASEDIR + "/testreload.jks";
-        createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), sCert);
-
-        long reloadInterval = 10;
-        Timer fileMonitoringTimer = new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
-        ReloadingX509KeystoreManager tm =
-                new ReloadingX509KeystoreManager("jks", keystoreLocation,
-                        "password",
-                        "password");
-        try {
-            fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
-                    Paths.get(keystoreLocation), tm::loadFrom,null), reloadInterval, reloadInterval);
-            assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
-
-            // Wait so that the file modification time is different
-            Thread.sleep((reloadInterval+ 1000));
-
-            // Change the certificate with a new keypair
-            final KeyPair anotherKP = generateKeyPair("RSA");
-            sCert = KeyStoreTestUtil.generateCertificate("CN=localhost, O=server", anotherKP, 30,
-                            "SHA1withRSA");
-            createKeyStore(keystoreLocation, "password", "cert1", anotherKP.getPrivate(), sCert);
-
-            GenericTestUtils.waitFor(new Supplier<Boolean>() {
-                @Override
-                public Boolean get() {
-                    return tm.getPrivateKey("cert1").equals(kp.getPrivate());
-                }
-            }, (int) reloadInterval, 100000);
-        } finally {
-            fileMonitoringTimer.cancel();
-        }
+  }
+
+  @Test
+  @Timeout(value = 30)
+  public void testReloadMissingTrustStore() throws Exception {
+    KeyPair kp = generateKeyPair("RSA");
+    X509Certificate cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
+    String keystoreLocation = BASEDIR + "/testmissing.jks";
+    createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), cert1);
+
+    long reloadInterval = 10;
+    Timer fileMonitoringTimer =
+        new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
+    ReloadingX509KeystoreManager tm =
+        new ReloadingX509KeystoreManager("jks", keystoreLocation,
+        "password",
+        "password");
+
+    try {
+      fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
+          Paths.get(keystoreLocation), tm::loadFrom, null), reloadInterval, reloadInterval);
+      assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
+
+      assertFalse(reloaderLog.getOutput().contains(
+          FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE));
+
+      // Wait for the first reload to happen so we actually detect a change after the delete
+      Thread.sleep((reloadInterval+ 1000));
+
+      new File(keystoreLocation).delete();
+
+      // Wait for the reload to happen and log to get written to
+      Thread.sleep((reloadInterval+ 1000));
+
+      waitForFailedReloadAtLeastOnce((int) reloadInterval);
+
+      assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
+    } finally {
+      reloaderLog.stopCapturing();
+      fileMonitoringTimer.cancel();
     }
-
-    @Test (timeout = 30000)
-    public void testReloadMissingTrustStore() throws Exception {
-        KeyPair kp = generateKeyPair("RSA");
-        X509Certificate cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
-        String keystoreLocation = BASEDIR + "/testmissing.jks";
-        createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), cert1);
-
-        long reloadInterval = 10;
-        Timer fileMonitoringTimer = new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
-        ReloadingX509KeystoreManager tm =
-                new ReloadingX509KeystoreManager("jks", keystoreLocation,
-                        "password",
-                        "password");
-        try {
-            fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
-                    Paths.get(keystoreLocation), tm::loadFrom,null), reloadInterval, reloadInterval);
-            assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
-
-            assertFalse(reloaderLog.getOutput().contains(
-                    FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE));
-
-            // Wait for the first reload to happen so we actually detect a change after the delete
-            Thread.sleep((reloadInterval+ 1000));
-
-            new File(keystoreLocation).delete();
-
-            // Wait for the reload to happen and log to get written to
-            Thread.sleep((reloadInterval+ 1000));
-
-            waitForFailedReloadAtLeastOnce((int) reloadInterval);
-
-            assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
-        } finally {
-            reloaderLog.stopCapturing();
-            fileMonitoringTimer.cancel();
-        }
+  }
+
+  @Test
+  @Timeout(value = 30)
+  public void testReloadCorruptTrustStore() throws Exception {
+    KeyPair kp = generateKeyPair("RSA");
+    X509Certificate cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
+    String keystoreLocation = BASEDIR + "/testmissing.jks";
+    createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), cert1);
+
+    long reloadInterval = 10;
+    Timer fileMonitoringTimer =
+        new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
+    ReloadingX509KeystoreManager tm =
+        new ReloadingX509KeystoreManager("jks", keystoreLocation,
+        "password",
+        "password");
+
+    try {
+      fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
+          Paths.get(keystoreLocation), tm::loadFrom, null), reloadInterval, reloadInterval);
+      assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
+
+      // Wait so that the file modification time is different
+      Thread.sleep((reloadInterval + 1000));
+
+      assertFalse(reloaderLog.getOutput().contains(
+          FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE));
+      OutputStream os = new FileOutputStream(keystoreLocation);
+      os.write(1);
+      os.close();
+
+      waitForFailedReloadAtLeastOnce((int) reloadInterval);
+
+      assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
+    } finally {
+      reloaderLog.stopCapturing();
+      fileMonitoringTimer.cancel();
     }
-
-
-    @Test (timeout = 30000)
-    public void testReloadCorruptTrustStore() throws Exception {
-        KeyPair kp = generateKeyPair("RSA");
-        X509Certificate cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
-        String keystoreLocation = BASEDIR + "/testmissing.jks";
-        createKeyStore(keystoreLocation, "password", "cert1", kp.getPrivate(), cert1);
-
-        long reloadInterval = 10;
-        Timer fileMonitoringTimer = new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
-        ReloadingX509KeystoreManager tm =
-                new ReloadingX509KeystoreManager("jks", keystoreLocation,
-                        "password",
-                        "password");
-        try {
-            fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
-                    Paths.get(keystoreLocation), tm::loadFrom,null), reloadInterval, reloadInterval);
-            assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
-
-            // Wait so that the file modification time is different
-            Thread.sleep((reloadInterval + 1000));
-
-            assertFalse(reloaderLog.getOutput().contains(
-                    FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE));
-            OutputStream os = new FileOutputStream(keystoreLocation);
-            os.write(1);
-            os.close();
-
-            waitForFailedReloadAtLeastOnce((int) reloadInterval);
-
-            assertEquals(kp.getPrivate(), tm.getPrivateKey("cert1"));
-        } finally {
-            reloaderLog.stopCapturing();
-            fileMonitoringTimer.cancel();
+  }
+
+  /**Wait for the reloader thread to load the configurations at least once
+  * by probing the log of the thread if the reload fails.
+  */
+  private void waitForFailedReloadAtLeastOnce(int reloadInterval)
+      throws InterruptedException, TimeoutException {
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+        @Override
+        public Boolean get() {
+            return reloaderLog.getOutput().contains(
+                    FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE);
         }
-    }
-
-    /**Wait for the reloader thread to load the configurations at least once
-     * by probing the log of the thread if the reload fails.
-     */
-    private void waitForFailedReloadAtLeastOnce(int reloadInterval)
-            throws InterruptedException, TimeoutException {
-        GenericTestUtils.waitFor(new Supplier<Boolean>() {
-            @Override
-            public Boolean get() {
-                return reloaderLog.getOutput().contains(
-                        FileMonitoringTimerTask.PROCESS_ERROR_MESSAGE);
-            }
-        }, reloadInterval, 10 * 1000);
-    }
+    }, reloadInterval, 10 * 1000);
+  }
 }

+ 26 - 20
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestReloadingX509TrustManager.java

@@ -23,8 +23,9 @@ import org.apache.hadoop.test.GenericTestUtils.LogCapturer;
 
 import java.util.function.Supplier;
 
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -38,11 +39,10 @@ import java.util.Map;
 import java.util.Timer;
 import java.util.concurrent.TimeoutException;
 
-import static org.junit.Assert.assertEquals;
 import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.createTrustStore;
 import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.generateCertificate;
 import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.generateKeyPair;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
 
 public class TestReloadingX509TrustManager {
 
@@ -54,33 +54,37 @@ public class TestReloadingX509TrustManager {
   private final LogCapturer reloaderLog = LogCapturer.captureLogs(
       FileMonitoringTimerTask.LOG);
 
-  @BeforeClass
+  @BeforeAll
   public static void setUp() throws Exception {
     File base = new File(BASEDIR);
     FileUtil.fullyDelete(base);
     base.mkdirs();
   }
 
-  @Test(expected = IOException.class)
+  @Test
   public void testLoadMissingTrustStore() throws Exception {
-    String truststoreLocation = BASEDIR + "/testmissing.jks";
-
-    ReloadingX509TrustManager tm =
-            new ReloadingX509TrustManager("jks", truststoreLocation, "password");
+    assertThrows(IOException.class, () -> {
+      String truststoreLocation = BASEDIR + "/testmissing.jks";
+      ReloadingX509TrustManager tm =
+          new ReloadingX509TrustManager("jks", truststoreLocation, "password");
+    });
   }
 
-  @Test(expected = IOException.class)
+  @Test
   public void testLoadCorruptTrustStore() throws Exception {
-    String truststoreLocation = BASEDIR + "/testcorrupt.jks";
-    OutputStream os = new FileOutputStream(truststoreLocation);
-    os.write(1);
-    os.close();
+    assertThrows(IOException.class, () -> {
+      String truststoreLocation = BASEDIR + "/testcorrupt.jks";
+      OutputStream os = new FileOutputStream(truststoreLocation);
+      os.write(1);
+      os.close();
 
-    ReloadingX509TrustManager tm =
-      new ReloadingX509TrustManager("jks", truststoreLocation, "password");
+      ReloadingX509TrustManager tm =
+          new ReloadingX509TrustManager("jks", truststoreLocation, "password");
+    });
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testReload() throws Exception {
     KeyPair kp = generateKeyPair("RSA");
     cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
@@ -117,7 +121,8 @@ public class TestReloadingX509TrustManager {
     }
   }
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testReloadMissingTrustStore() throws Exception {
     KeyPair kp = generateKeyPair("RSA");
     cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
@@ -157,7 +162,8 @@ public class TestReloadingX509TrustManager {
   }
 
 
-  @Test (timeout = 30000)
+  @Test
+  @Timeout(value = 30)
   public void testReloadCorruptTrustStore() throws Exception {
     KeyPair kp = generateKeyPair("RSA");
     cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");

+ 59 - 51
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/TestSSLFactory.java

@@ -24,10 +24,14 @@ import static org.apache.hadoop.security.ssl.KeyStoreTestUtil.TRUST_STORE_PASSWO
 import static org.apache.hadoop.security.ssl.SSLFactory.Mode.CLIENT;
 import static org.apache.hadoop.security.ssl.SSLFactory.SSL_CLIENT_CONF_KEY;
 import static org.apache.hadoop.security.ssl.SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-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.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileUtil;
@@ -36,11 +40,10 @@ import org.apache.hadoop.security.alias.CredentialProviderFactory;
 import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.StringUtils;
-import org.junit.After;
-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.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.event.Level;
@@ -80,7 +83,7 @@ public class TestSSLFactory {
           "keystorePassword", "keyPassword",
           "trustStoreLocation", "trustStorePassword");
 
-  @BeforeClass
+  @BeforeAll
   public static void setUp() throws Exception {
     File base = new File(BASEDIR);
     FileUtil.fullyDelete(base);
@@ -96,8 +99,8 @@ public class TestSSLFactory {
     return conf;
   }
 
-  @After
-  @Before
+  @AfterEach
+  @BeforeEach
   public void cleanUp() throws Exception {
     sslConfsDir = KeyStoreTestUtil.getClasspathDir(TestSSLFactory.class);
     KeyStoreTestUtil.cleanupSSLConfig(KEYSTORES_DIR, sslConfsDir);
@@ -152,18 +155,20 @@ public class TestSSLFactory {
     assertNotEquals(conf, sslConfLoaded);
   }
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void clientMode() throws Exception {
-    Configuration conf = createConfiguration(false, true);
-    SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
-    try {
-      sslFactory.init();
-      Assert.assertNotNull(sslFactory.createSSLSocketFactory());
-      Assert.assertNotNull(sslFactory.getHostnameVerifier());
-      sslFactory.createSSLServerSocketFactory();
-    } finally {
-      sslFactory.destroy();
-    }
+    assertThrows(IllegalStateException.class, () -> {
+      Configuration conf = createConfiguration(false, true);
+      SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
+      try {
+        sslFactory.init();
+        assertNotNull(sslFactory.createSSLSocketFactory());
+        assertNotNull(sslFactory.getHostnameVerifier());
+        sslFactory.createSSLServerSocketFactory();
+      } finally {
+        sslFactory.destroy();
+      }
+    });
   }
 
   private void serverMode(boolean clientCert, boolean socket) throws Exception {
@@ -171,8 +176,8 @@ public class TestSSLFactory {
     SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
     try {
       sslFactory.init();
-      Assert.assertNotNull(sslFactory.createSSLServerSocketFactory());
-      Assert.assertEquals(clientCert, sslFactory.isClientCertRequired());
+      assertNotNull(sslFactory.createSSLServerSocketFactory());
+      assertEquals(clientCert, sslFactory.isClientCertRequired());
       if (socket) {
         sslFactory.createSSLSocketFactory();
       } else {
@@ -184,24 +189,25 @@ public class TestSSLFactory {
   }
 
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void serverModeWithoutClientCertsSocket() throws Exception {
-    serverMode(false, true);
+    assertThrows(IllegalStateException.class,
+        () -> serverMode(false, true));
   }
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void serverModeWithClientCertsSocket() throws Exception {
-    serverMode(true, true);
+    assertThrows(IllegalStateException.class, () -> serverMode(true, true));
   }
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void serverModeWithoutClientCertsVerifier() throws Exception {
-    serverMode(false, false);
+    assertThrows(IllegalStateException.class, () -> serverMode(false, false));
   }
 
-  @Test(expected = IllegalStateException.class)
+  @Test
   public void serverModeWithClientCertsVerifier() throws Exception {
-    serverMode(true, false);
+    assertThrows(IllegalStateException.class, ()-> serverMode(true, false));
   }
 
   private void runDelegatedTasks(SSLEngineResult result, SSLEngine engine)
@@ -228,7 +234,7 @@ public class TestSSLFactory {
     throws Exception {
     a.flip();
     b.flip();
-    assertTrue("transfer did not complete", a.equals(b));
+    assertTrue(a.equals(b), "transfer did not complete");
 
     a.position(a.limit());
     b.position(b.limit());
@@ -299,7 +305,7 @@ public class TestSSLFactory {
           dataDone = true;
         }
       }
-      Assert.fail("The exception was not thrown");
+      fail("The exception was not thrown");
     } catch (SSLHandshakeException e) {
       GenericTestUtils.assertExceptionContains("no cipher suites in common", e);
     }
@@ -326,47 +332,49 @@ public class TestSSLFactory {
     SSLFactory sslFactory = new
       SSLFactory(SSLFactory.Mode.CLIENT, conf);
     sslFactory.init();
-    Assert.assertEquals("DEFAULT", sslFactory.getHostnameVerifier().toString());
+    assertEquals("DEFAULT", sslFactory.getHostnameVerifier().toString());
     sslFactory.destroy();
 
     conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL");
     sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
     sslFactory.init();
-    Assert.assertEquals("ALLOW_ALL",
+    assertEquals("ALLOW_ALL",
                         sslFactory.getHostnameVerifier().toString());
     sslFactory.destroy();
 
     conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "DEFAULT_AND_LOCALHOST");
     sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
     sslFactory.init();
-    Assert.assertEquals("DEFAULT_AND_LOCALHOST",
+    assertEquals("DEFAULT_AND_LOCALHOST",
                         sslFactory.getHostnameVerifier().toString());
     sslFactory.destroy();
 
     conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "STRICT");
     sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
     sslFactory.init();
-    Assert.assertEquals("STRICT", sslFactory.getHostnameVerifier().toString());
+    assertEquals("STRICT", sslFactory.getHostnameVerifier().toString());
     sslFactory.destroy();
 
     conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "STRICT_IE6");
     sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
     sslFactory.init();
-    Assert.assertEquals("STRICT_IE6",
+    assertEquals("STRICT_IE6",
                         sslFactory.getHostnameVerifier().toString());
     sslFactory.destroy();
   }
 
-  @Test(expected = GeneralSecurityException.class)
+  @Test
   public void invalidHostnameVerifier() throws Exception {
-    Configuration conf = createConfiguration(false, true);
-    conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "foo");
-    SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
-    try {
-      sslFactory.init();
-    } finally {
-      sslFactory.destroy();
-    }
+    assertThrows(GeneralSecurityException.class, () -> {
+      Configuration conf = createConfiguration(false, true);
+      conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "foo");
+      SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
+      try {
+        sslFactory.init();
+      } finally {
+        sslFactory.destroy();
+      }
+    });
   }
 
   @Test
@@ -392,10 +400,10 @@ public class TestSSLFactory {
       sslFactory.init();
       HttpsURLConnection sslConn =
           (HttpsURLConnection) new URL("https://foo").openConnection();
-      Assert.assertNotSame("STRICT_IE6",
+      assertNotSame("STRICT_IE6",
                            sslConn.getHostnameVerifier().toString());
       sslFactory.configure(sslConn);
-      Assert.assertEquals("STRICT_IE6",
+      assertEquals("STRICT_IE6",
                           sslConn.getHostnameVerifier().toString());
     } finally {
       sslFactory.destroy();

+ 89 - 89
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/TestDtUtilShell.java

@@ -30,13 +30,13 @@ import org.apache.hadoop.io.Text;
 import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.test.GenericTestUtils;
 
-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 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.mockito.Mockito;
 
@@ -89,7 +89,7 @@ public class TestDtUtilShell {
   private DtUtilShell dt = null;
   private int rc = 0;
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     localFs.mkdirs(localFs.makeQualified(workDir));
     makeTokenFile(tokenFile, false, null);
@@ -102,7 +102,7 @@ public class TestDtUtilShell {
     rc = 0;
   }
 
-  @After
+  @AfterEach
   public void teardown() throws Exception {
     localFs.delete(localFs.makeQualified(workDir), true);
   }
@@ -128,40 +128,40 @@ public class TestDtUtilShell {
   public void testPrint() throws Exception {
     args = new String[] {"print", tokenFilename};
     rc = dt.run(args);
-    assertEquals("test simple print exit code", 0, rc);
-    assertTrue("test simple print output kind:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple print output service:\n" + outContent.toString(),
-               outContent.toString().contains(SERVICE.toString()));
+    assertEquals(0, rc, "test simple print exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple print output kind:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(SERVICE.toString()),
+        "test simple print output service:\n" + outContent.toString());
 
     outContent.reset();
     args = new String[] {"print", tokenLegacyFile.toString()};
     rc = dt.run(args);
-    assertEquals("test legacy print exit code", 0, rc);
-    assertTrue("test simple print output kind:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple print output service:\n" + outContent.toString(),
-               outContent.toString().contains(SERVICE.toString()));
+    assertEquals(0, rc, "test legacy print exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple print output kind:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(SERVICE.toString()),
+        "test simple print output service:\n" + outContent.toString());
 
     outContent.reset();
     args = new String[] {
         "print", "-alias", SERVICE.toString(), tokenFilename};
     rc = dt.run(args);
-    assertEquals("test alias print exit code", 0, rc);
-    assertTrue("test simple print output kind:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple print output service:\n" + outContent.toString(),
-               outContent.toString().contains(SERVICE.toString()));
+    assertEquals(0, rc, "test alias print exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple print output kind:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(SERVICE.toString()),
+        "test simple print output service:\n" + outContent.toString());
 
     outContent.reset();
     args = new String[] {
         "print", "-alias", "not-a-serivce", tokenFilename};
     rc = dt.run(args);
-    assertEquals("test no alias print exit code", 0, rc);
-    assertFalse("test no alias print output kind:\n" + outContent.toString(),
-                outContent.toString().contains(KIND.toString()));
-    assertFalse("test no alias print output service:\n" + outContent.toString(),
-                outContent.toString().contains(SERVICE.toString()));
+    assertEquals(0, rc, "test no alias print exit code");
+    assertFalse(outContent.toString().contains(KIND.toString()),
+        "test no alias print output kind:\n" + outContent.toString());
+    assertFalse(outContent.toString().contains(SERVICE.toString()),
+        "test no alias print output service:\n" + outContent.toString());
   }
 
   @Test
@@ -171,66 +171,66 @@ public class TestDtUtilShell {
     args = new String[] {"edit",
         "-service", oldService, "-alias", newAlias, tokenFilename2};
     rc = dt.run(args);
-    assertEquals("test simple edit exit code", 0, rc);
+    assertEquals(0, rc, "test simple edit exit code");
     args = new String[] {"print", "-alias", oldService, tokenFilename2};
     rc = dt.run(args);
-    assertEquals("test simple edit print old exit code", 0, rc);
-    assertTrue("test simple edit output kind old:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple edit output service old:\n" + outContent.toString(),
-               outContent.toString().contains(oldService));
+    assertEquals(0, rc, "test simple edit print old exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple edit output kind old:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(oldService),
+        "test simple edit output service old:\n" + outContent.toString());
     args = new String[] {"print", "-alias", newAlias, tokenFilename2};
     rc = dt.run(args);
-    assertEquals("test simple edit print new exit code", 0, rc);
-    assertTrue("test simple edit output kind new:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple edit output service new:\n" + outContent.toString(),
-               outContent.toString().contains(newAlias));
+    assertEquals(0, rc, "test simple edit print new exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple edit output kind new:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(newAlias),
+        "test simple edit output service new:\n" + outContent.toString());
   }
 
   @Test
   public void testAppend() throws Exception {
     args = new String[] {"append", tokenFilename, tokenFilename2};
     rc = dt.run(args);
-    assertEquals("test simple append exit code", 0, rc);
+    assertEquals(0, rc, "test simple append exit code");
     args = new String[] {"print", tokenFilename2};
     rc = dt.run(args);
-    assertEquals("test simple append print exit code", 0, rc);
-    assertTrue("test simple append output kind:\n" + outContent.toString(),
-               outContent.toString().contains(KIND.toString()));
-    assertTrue("test simple append output service:\n" + outContent.toString(),
-               outContent.toString().contains(SERVICE.toString()));
-    assertTrue("test simple append output service:\n" + outContent.toString(),
-               outContent.toString().contains(SERVICE2.toString()));
+    assertEquals(0, rc, "test simple append print exit code");
+    assertTrue(outContent.toString().contains(KIND.toString()),
+        "test simple append output kind:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(SERVICE.toString()),
+        "test simple append output service:\n" + outContent.toString());
+    assertTrue(outContent.toString().contains(SERVICE2.toString()),
+        "test simple append output service:\n" + outContent.toString());
   }
 
   @Test
   public void testRemove() throws Exception {
     args = new String[] {"remove", "-alias", SERVICE.toString(), tokenFilename};
     rc = dt.run(args);
-    assertEquals("test simple remove exit code", 0, rc);
+    assertEquals(0, rc, "test simple remove exit code");
     args = new String[] {"print", tokenFilename};
     rc = dt.run(args);
-    assertEquals("test simple remove print exit code", 0, rc);
-    assertFalse("test simple remove output kind:\n" + outContent.toString(),
-                outContent.toString().contains(KIND.toString()));
-    assertFalse("test simple remove output service:\n" + outContent.toString(),
-                outContent.toString().contains(SERVICE.toString()));
+    assertEquals(0, rc, "test simple remove print exit code");
+    assertFalse(outContent.toString().contains(KIND.toString()),
+        "test simple remove output kind:\n" + outContent.toString());
+    assertFalse(outContent.toString().contains(SERVICE.toString()),
+        "test simple remove output service:\n" + outContent.toString());
   }
 
   @Test
   public void testGet() throws Exception {
     args = new String[] {"get", getUrl, tokenFilenameGet};
     rc = dt.run(args);
-    assertEquals("test mocked get exit code", 0, rc);
+    assertEquals(0, rc, "test mocked get exit code");
     args = new String[] {"print", tokenFilenameGet};
     rc = dt.run(args);
     String oc = outContent.toString();
-    assertEquals("test print after get exit code", 0, rc);
-    assertTrue("test print after get output kind:\n" + oc,
-               oc.contains(KIND_GET.toString()));
-    assertTrue("test print after get output service:\n" + oc,
-               oc.contains(SERVICE_GET.toString()));
+    assertEquals(0, rc, "test print after get exit code");
+    assertTrue(oc.contains(KIND_GET.toString()),
+        "test print after get output kind:\n" + oc);
+    assertTrue(oc.contains(SERVICE_GET.toString()),
+        "test print after get output service:\n" + oc);
   }
 
   @Test
@@ -238,39 +238,39 @@ public class TestDtUtilShell {
     args = new String[] {"get", getUrl2, "-service", SERVICE_GET.toString(),
                          tokenFilenameGet};
     rc = dt.run(args);
-    assertEquals("test mocked get with service flag exit code", 0, rc);
+    assertEquals(0, rc, "test mocked get with service flag exit code");
     args = new String[] {"print", tokenFilenameGet};
     rc = dt.run(args);
     String oc = outContent.toString();
-    assertEquals("test print after get with service flag exit code", 0, rc);
-    assertTrue("test print after get with service flag output kind:\n" + oc,
-               oc.contains(KIND_GET.toString()));
-    assertTrue("test print after get with service flag output service:\n" + oc,
-               oc.contains(SERVICE_GET.toString()));
+    assertEquals(0, rc, "test print after get with service flag exit code");
+    assertTrue(oc.contains(KIND_GET.toString()),
+        "test print after get with service flag output kind:\n" + oc);
+    assertTrue(oc.contains(SERVICE_GET.toString()),
+        "test print after get with service flag output service:\n" + oc);
   }
 
   @Test
   public void testGetWithAliasFlag() throws Exception {
     args = new String[] {"get", getUrl, "-alias", alias, tokenFilenameGet};
     rc = dt.run(args);
-    assertEquals("test mocked get with alias flag exit code", 0, rc);
+    assertEquals(0, rc, "test mocked get with alias flag exit code");
     args = new String[] {"print", tokenFilenameGet};
     rc = dt.run(args);
     String oc = outContent.toString();
-    assertEquals("test print after get with alias flag exit code", 0, rc);
-    assertTrue("test print after get with alias flag output kind:\n" + oc,
-               oc.contains(KIND_GET.toString()));
-    assertTrue("test print after get with alias flag output alias:\n" + oc,
-               oc.contains(alias));
-    assertFalse("test print after get with alias flag output old service:\n" +
-                oc, oc.contains(SERVICE_GET.toString()));
+    assertEquals(0, rc, "test print after get with alias flag exit code");
+    assertTrue(oc.contains(KIND_GET.toString()),
+        "test print after get with alias flag output kind:\n" + oc);
+    assertTrue(oc.contains(alias),
+        "test print after get with alias flag output alias:\n" + oc);
+    assertFalse(oc.contains(SERVICE_GET.toString()),
+        "test print after get with alias flag output old service:\n" + oc);
   }
 
   @Test
   public void testFormatJavaFlag() throws Exception {
     args = new String[] {"get", getUrl, "-format", "java", tokenFilenameGet};
     rc = dt.run(args);
-    assertEquals("test mocked get with java format flag exit code", 0, rc);
+    assertEquals(0, rc, "test mocked get with java format flag exit code");
     Credentials creds = new Credentials();
     Credentials spyCreds = Mockito.spy(creds);
     DataInputStream in = new DataInputStream(
@@ -284,7 +284,7 @@ public class TestDtUtilShell {
     args = new String[] {
         "get", getUrl, "-format", "protobuf", tokenFilenameGet};
     rc = dt.run(args);
-    assertEquals("test mocked get with protobuf format flag exit code", 0, rc);
+    assertEquals(0, rc, "test mocked get with protobuf format flag exit code");
     Credentials creds = new Credentials();
     Credentials spyCreds = Mockito.spy(creds);
     DataInputStream in = new DataInputStream(
@@ -298,17 +298,17 @@ public class TestDtUtilShell {
     String base64 = IMPORT_TOKEN.encodeToUrlString();
     args = new String[] {"import", base64, tokenFilenameImport};
     rc = dt.run(args);
-    assertEquals("test simple import print old exit code", 0, rc);
+    assertEquals(0, rc, "test simple import print old exit code");
 
     args = new String[] {"print", tokenFilenameImport};
     rc = dt.run(args);
-    assertEquals("test simple import print old exit code", 0, rc);
-    assertTrue("test print after import output:\n" + outContent,
-               outContent.toString().contains(KIND_IMPORT.toString()));
-    assertTrue("test print after import output:\n" + outContent,
-        outContent.toString().contains(SERVICE_IMPORT.toString()));
-    assertTrue("test print after simple import output:\n" + outContent,
-               outContent.toString().contains(base64));
+    assertEquals(0, rc, "test simple import print old exit code");
+    assertTrue(outContent.toString().contains(KIND_IMPORT.toString()),
+        "test print after import output:\n" + outContent);
+    assertTrue(outContent.toString().contains(SERVICE_IMPORT.toString()),
+        "test print after import output:\n" + outContent);
+    assertTrue(outContent.toString().contains(base64),
+        "test print after simple import output:\n" + outContent);
   }
 
   @Test
@@ -317,14 +317,14 @@ public class TestDtUtilShell {
     args = new String[] {"import", base64, "-alias", alias,
         tokenFilenameImport};
     rc = dt.run(args);
-    assertEquals("test import with alias print old exit code", 0, rc);
+    assertEquals(0, rc, "test import with alias print old exit code");
 
     args = new String[] {"print", tokenFilenameImport};
     rc = dt.run(args);
-    assertEquals("test simple import print old exit code", 0, rc);
-    assertTrue("test print after import output:\n" + outContent,
-               outContent.toString().contains(KIND_IMPORT.toString()));
-    assertTrue("test print after import with alias output:\n" + outContent,
-               outContent.toString().contains(alias));
+    assertEquals(0, rc, "test simple import print old exit code");
+    assertTrue(outContent.toString().contains(KIND_IMPORT.toString()),
+        "test print after import output:\n" + outContent);
+    assertTrue(outContent.toString().contains(alias),
+        "test print after import with alias output:\n" + outContent);
   }
 }

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/TestToken.java

@@ -26,10 +26,10 @@ import org.apache.hadoop.io.*;
 import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier;
 import org.apache.hadoop.security.token.delegation.TestDelegationToken.TestDelegationTokenIdentifier;
 import org.apache.hadoop.security.token.delegation.TestDelegationToken.TestDelegationTokenSecretManager;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import static org.apache.hadoop.test.LambdaTestUtils.intercept;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
 
 /** Unit tests for Token */
 public class TestToken {

+ 26 - 24
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/TestDelegationToken.java

@@ -37,7 +37,7 @@ import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.metrics2.lib.MutableCounterLong;
 import org.apache.hadoop.metrics2.lib.MutableRate;
 import org.apache.hadoop.test.LambdaTestUtils;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
 
 import org.apache.hadoop.io.DataInputBuffer;
 import org.apache.hadoop.io.DataOutputBuffer;
@@ -53,12 +53,13 @@ import org.apache.hadoop.security.token.TokenIdentifier;
 import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSecretManager.DelegationTokenInformation;
 import org.apache.hadoop.util.Daemon;
 import org.apache.hadoop.util.Time;
-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.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
 
 public class TestDelegationToken {
   private static final Logger LOG =
@@ -126,7 +127,7 @@ public class TestDelegationToken {
     @Override
     protected void removeStoredMasterKey(DelegationKey key) {
       isRemoveStoredMasterKeyCalled = true;
-      Assert.assertFalse(key.equals(allKeys.get(currentId)));
+      Assertions.assertFalse(key.equals(allKeys.get(currentId)));
     }
 
     @Override
@@ -263,10 +264,10 @@ public class TestDelegationToken {
                            Class<? extends Throwable> except) {
     try {
       action.run();
-      Assert.fail("action did not throw " + except);
+      Assertions.fail("action did not throw " + except);
     } catch (Throwable th) {
       LOG.info("Caught an exception: ", th);
-      assertEquals("action threw wrong exception", except, th.getClass());
+      assertEquals(except, th.getClass(), "action threw wrong exception");
     }
   }
 
@@ -349,7 +350,7 @@ public class TestDelegationToken {
       final Token<TestDelegationTokenIdentifier> token = 
         generateDelegationToken(
           dtSecretManager, "SomeUser", "JobTracker");
-      Assert.assertTrue(dtSecretManager.isStoreNewTokenCalled);
+      Assertions.assertTrue(dtSecretManager.isStoreNewTokenCalled);
       // Fake renewer should not be able to renew
       shouldThrow(new PrivilegedExceptionAction<Object>() {
         @Override
@@ -359,21 +360,21 @@ public class TestDelegationToken {
         }
       }, AccessControlException.class);
       long time = dtSecretManager.renewToken(token, "JobTracker");
-      Assert.assertTrue(dtSecretManager.isUpdateStoredTokenCalled);
-      assertTrue("renew time is in future", time > Time.now());
+      Assertions.assertTrue(dtSecretManager.isUpdateStoredTokenCalled);
+      assertTrue(time > Time.now(), "renew time is in future");
       TestDelegationTokenIdentifier identifier = 
         new TestDelegationTokenIdentifier();
       byte[] tokenId = token.getIdentifier();
       identifier.readFields(new DataInputStream(
           new ByteArrayInputStream(tokenId)));
-      Assert.assertTrue(null != dtSecretManager.retrievePassword(identifier));
+      Assertions.assertTrue(null != dtSecretManager.retrievePassword(identifier));
       LOG.info("Sleep to expire the token");
       Thread.sleep(2000);
       //Token should be expired
       try {
         dtSecretManager.retrievePassword(identifier);
         //Should not come here
-        Assert.fail("Token should have expired");
+        Assertions.fail("Token should have expired");
       } catch (InvalidToken e) {
         //Success
       }
@@ -411,7 +412,7 @@ public class TestDelegationToken {
         }
       }, AccessControlException.class);
       dtSecretManager.cancelToken(token, "JobTracker");
-      Assert.assertTrue(dtSecretManager.isRemoveStoredTokenCalled);
+      Assertions.assertTrue(dtSecretManager.isRemoveStoredTokenCalled);
       shouldThrow(new PrivilegedExceptionAction<Object>() {
         @Override
         public Object run() throws Exception {
@@ -424,7 +425,8 @@ public class TestDelegationToken {
     }
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testRollMasterKey() throws Exception {
     TestDelegationTokenSecretManager dtSecretManager = 
       new TestDelegationTokenSecretManager(800,
@@ -439,7 +441,7 @@ public class TestDelegationToken {
       int prevNumKeys = dtSecretManager.getAllKeys().length;
       
       dtSecretManager.rollMasterKey();
-      Assert.assertTrue(dtSecretManager.isStoreNewMasterKeyCalled);
+      Assertions.assertTrue(dtSecretManager.isStoreNewMasterKeyCalled);
 
       //after rolling, the length of the keys list must increase
       int currNumKeys = dtSecretManager.getAllKeys().length;
@@ -456,7 +458,7 @@ public class TestDelegationToken {
       byte[] newPasswd = 
         dtSecretManager.retrievePassword(identifier);
       //compare the passwords
-      Assert.assertEquals(oldPasswd, newPasswd);
+      Assertions.assertEquals(oldPasswd, newPasswd);
       // wait for keys to expire
       while(!dtSecretManager.isRemoveStoredMasterKeyCalled) {
         Thread.sleep(200);
@@ -494,7 +496,7 @@ public class TestDelegationToken {
       //try to select a token with a given service name (created earlier)
       Token<TestDelegationTokenIdentifier> t = 
         ds.selectToken(new Text("MY-SERVICE1"), tokens);
-      Assert.assertEquals(t, token1);
+      Assertions.assertEquals(t, token1);
     } finally {
       dtSecretManager.stopThreads();
     }
@@ -532,17 +534,17 @@ public class TestDelegationToken {
       }
       Map<TestDelegationTokenIdentifier, DelegationTokenInformation> tokenCache = dtSecretManager
           .getAllTokens();
-      Assert.assertEquals(numTokensPerThread*numThreads, tokenCache.size());
+      Assertions.assertEquals(numTokensPerThread*numThreads, tokenCache.size());
       Iterator<TestDelegationTokenIdentifier> iter = tokenCache.keySet().iterator();
       while (iter.hasNext()) {
         TestDelegationTokenIdentifier id = iter.next();
         DelegationTokenInformation info = tokenCache.get(id);
-        Assert.assertTrue(info != null);
+        Assertions.assertTrue(info != null);
         DelegationKey key = dtSecretManager.getKey(id);
-        Assert.assertTrue(key != null);
+        Assertions.assertTrue(key != null);
         byte[] storedPassword = dtSecretManager.retrievePassword(id);
         byte[] password = dtSecretManager.createPassword(id, key);
-        Assert.assertTrue(Arrays.equals(password, storedPassword));
+        Assertions.assertTrue(Arrays.equals(password, storedPassword));
         //verify by secret manager api
         dtSecretManager.verifyToken(id, password);
       }
@@ -561,10 +563,10 @@ public class TestDelegationToken {
         "theuser"), null, null);
     Token<TestDelegationTokenIdentifier> token = new Token<TestDelegationTokenIdentifier>(
         dtId, dtSecretManager);
-    Assert.assertTrue(token != null);
+    Assertions.assertTrue(token != null);
     try {
       dtSecretManager.renewToken(token, "");
-      Assert.fail("Renewal must not succeed");
+      Assertions.fail("Renewal must not succeed");
     } catch (IOException e) {
       //PASS
     }
@@ -618,8 +620,8 @@ public class TestDelegationToken {
     DelegationKey key1 = new DelegationKey(1111, 2222, "keyBytes".getBytes());
     DelegationKey key2 = new DelegationKey(1111, 2222, "keyBytes".getBytes());
     DelegationKey key3 = new DelegationKey(3333, 2222, "keyBytes".getBytes());
-    Assert.assertEquals(key1, key2);
-    Assert.assertFalse(key2.equals(key3));
+    Assertions.assertEquals(key1, key2);
+    Assertions.assertFalse(key2.equals(key3));
   }
 
   @Test

+ 14 - 15
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/web/TestDelegationTokenManager.java

@@ -25,30 +25,29 @@ import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class TestDelegationTokenManager {
 
   private static final long DAY_IN_SECS = 86400;
 
-  @Parameterized.Parameters
   public static Collection<Object[]> headers() {
-    return Arrays.asList(new Object[][] { { false }, { true } });
+    return Arrays.asList(new Object[][]{{false}, {true}});
   }
 
   private boolean enableZKKey;
 
-  public TestDelegationTokenManager(boolean enableZKKey) {
-    this.enableZKKey = enableZKKey;
+  public void initTestDelegationTokenManager(boolean pEnableZKKey) {
+    this.enableZKKey = pEnableZKKey;
   }
 
   @SuppressWarnings("unchecked")
-  @Test
-  public void testDTManager() throws Exception {
+  @ParameterizedTest
+  @MethodSource("headers")
+  public void testDTManager(boolean pEnableZKKey) throws Exception {
+    initTestDelegationTokenManager(pEnableZKKey);
     Configuration conf = new Configuration(false);
     conf.setLong(DelegationTokenManager.UPDATE_INTERVAL, DAY_IN_SECS);
     conf.setLong(DelegationTokenManager.MAX_LIFETIME, DAY_IN_SECS);
@@ -61,17 +60,17 @@ public class TestDelegationTokenManager {
     Token<DelegationTokenIdentifier> token =
         (Token<DelegationTokenIdentifier>) tm.createToken(
             UserGroupInformation.getCurrentUser(), "foo");
-    Assert.assertNotNull(token);
+    Assertions.assertNotNull(token);
     tm.verifyToken(token);
-    Assert.assertTrue(tm.renewToken(token, "foo") > System.currentTimeMillis());
+    Assertions.assertTrue(tm.renewToken(token, "foo") > System.currentTimeMillis());
     tm.cancelToken(token, "foo");
     try {
       tm.verifyToken(token);
-      Assert.fail();
+      Assertions.fail();
     } catch (IOException ex) {
       //NOP
     } catch (Exception ex) {
-      Assert.fail();
+      Assertions.fail();
     }
     tm.destroy();
   }

+ 97 - 92
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/web/TestWebDelegationToken.java

@@ -36,10 +36,9 @@ import org.apache.hadoop.test.GenericTestUtils;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
 import org.eclipse.jetty.servlet.ServletContextHandler;
-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.eclipse.jetty.servlet.FilterHolder;
 import org.eclipse.jetty.servlet.ServletHolder;
 import org.slf4j.event.Level;
@@ -78,6 +77,12 @@ import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.Callable;
 
+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;
+
 public class TestWebDelegationToken {
   private static final String OK_USER = "ok-user";
   private static final String FAIL_USER = "fail-user";
@@ -193,7 +198,7 @@ public class TestWebDelegationToken {
     return "http://" + c.getHost() + ":" + c.getLocalPort();
   }
 
-  @Before
+  @BeforeEach
   public void setUp() throws Exception {
     // resetting hadoop security to simple
     org.apache.hadoop.conf.Configuration conf =
@@ -205,7 +210,7 @@ public class TestWebDelegationToken {
         Level.TRACE);
   }
 
-  @After
+  @AfterEach
   public void cleanUp() throws Exception {
     jetty.stop();
 
@@ -235,45 +240,45 @@ public class TestWebDelegationToken {
 
       // unauthenticated access to URL
       HttpURLConnection conn = (HttpURLConnection) nonAuthURL.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
+      assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
           conn.getResponseCode());
 
       // authenticated access to URL
       conn = (HttpURLConnection) authURL.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 
       // unauthenticated access to get delegation token
       URL url = new URL(nonAuthURL.toExternalForm() + "?op=GETDELEGATIONTOKEN");
       conn = (HttpURLConnection) url.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
+      assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
           conn.getResponseCode());
 
       // authenticated access to get delegation token
       url = new URL(authURL.toExternalForm() +
           "&op=GETDELEGATIONTOKEN&renewer=foo");
       conn = (HttpURLConnection) url.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
       ObjectMapper mapper = new ObjectMapper();
       Map map = mapper.readValue(conn.getInputStream(), Map.class);
       String dt = (String) ((Map) map.get("Token")).get("urlString");
-      Assert.assertNotNull(dt);
+      assertNotNull(dt);
 
       // delegation token access to URL
       url = new URL(nonAuthURL.toExternalForm() + "?delegation=" + dt);
       conn = (HttpURLConnection) url.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 
       // delegation token and authenticated access to URL
       url = new URL(authURL.toExternalForm() + "&delegation=" + dt);
       conn = (HttpURLConnection) url.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 
       // renewew delegation token, unauthenticated access to URL
       url = new URL(nonAuthURL.toExternalForm() +
           "?op=RENEWDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
+      assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
           conn.getResponseCode());
 
       // renewew delegation token, authenticated access to URL
@@ -281,14 +286,14 @@ public class TestWebDelegationToken {
           "&op=RENEWDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 
       // renewew delegation token, authenticated access to URL, not renewer
       url = new URL(getJettyURL() +
           "/foo/bar?authenticated=bar&op=RENEWDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
+      assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
           conn.getResponseCode());
 
       // cancel delegation token, nonauthenticated access to URL
@@ -296,32 +301,32 @@ public class TestWebDelegationToken {
           "?op=CANCELDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 
       // cancel canceled delegation token, nonauthenticated access to URL
       url = new URL(nonAuthURL.toExternalForm() +
           "?op=CANCELDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
+      assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
           conn.getResponseCode());
 
       // get new delegation token
       url = new URL(authURL.toExternalForm() +
           "&op=GETDELEGATIONTOKEN&renewer=foo");
       conn = (HttpURLConnection) url.openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
       mapper = new ObjectMapper();
       map = mapper.readValue(conn.getInputStream(), Map.class);
       dt = (String) ((Map) map.get("Token")).get("urlString");
-      Assert.assertNotNull(dt);
+      assertNotNull(dt);
 
       // cancel delegation token, authenticated access to URL
       url = new URL(authURL.toExternalForm() +
           "&op=CANCELDELEGATIONTOKEN&token=" + dt);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("PUT");
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
     } finally {
       jetty.stop();
     }
@@ -364,32 +369,32 @@ public class TestWebDelegationToken {
 
       try {
         aUrl.getDelegationToken(nonAuthURL, token, FOO_USER);
-        Assert.fail();
+        fail();
       } catch (Exception ex) {
-        Assert.assertTrue(ex.getCause().getMessage().contains("401"));
+        assertTrue(ex.getCause().getMessage().contains("401"));
       }
 
       aUrl.getDelegationToken(authURL, token, FOO_USER);
-      Assert.assertNotNull(token.getDelegationToken());
-      Assert.assertEquals(new Text("token-kind"),
+      assertNotNull(token.getDelegationToken());
+      assertEquals(new Text("token-kind"),
           token.getDelegationToken().getKind());
 
       aUrl.renewDelegationToken(authURL, token);
 
       try {
         aUrl.renewDelegationToken(nonAuthURL, token);
-        Assert.fail();
+        fail();
       } catch (Exception ex) {
-        Assert.assertTrue(ex.getMessage().contains("401"));
+        assertTrue(ex.getMessage().contains("401"));
       }
 
       aUrl.getDelegationToken(authURL, token, FOO_USER);
 
       try {
         aUrl.renewDelegationToken(authURL2, token);
-        Assert.fail();
+        fail();
       } catch (Exception ex) {
-        Assert.assertTrue(ex.getMessage().contains("403"));
+        assertTrue(ex.getMessage().contains("403"));
       }
 
       aUrl.getDelegationToken(authURL, token, FOO_USER);
@@ -405,7 +410,7 @@ public class TestWebDelegationToken {
       try {
         aUrl.renewDelegationToken(nonAuthURL, token);
       } catch (Exception ex) {
-        Assert.assertTrue(ex.getMessage().contains("401"));
+        assertTrue(ex.getMessage().contains("401"));
       }
 
       aUrl.getDelegationToken(authURL, token, "foo");
@@ -413,20 +418,21 @@ public class TestWebDelegationToken {
       UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
       ugi.addToken(token.getDelegationToken());
       ugi.doAs(new PrivilegedExceptionAction<Void>() {
-                 @Override
-                 public Void run() throws Exception {
-                   HttpURLConnection conn = aUrl.openConnection(nonAuthURL, new DelegationTokenAuthenticatedURL.Token());
-                   Assert.assertEquals(HttpServletResponse.SC_OK, conn.getResponseCode());
-                   if (useQS) {
-                     Assert.assertNull(conn.getHeaderField("UsingHeader"));
-                     Assert.assertNotNull(conn.getHeaderField("UsingQueryString"));
-                   } else {
-                     Assert.assertNotNull(conn.getHeaderField("UsingHeader"));
-                     Assert.assertNull(conn.getHeaderField("UsingQueryString"));
-                   }
-                   return null;
-                 }
-               });
+        @Override
+        public Void run() throws Exception {
+          HttpURLConnection conn =
+              aUrl.openConnection(nonAuthURL, new DelegationTokenAuthenticatedURL.Token());
+          assertEquals(HttpServletResponse.SC_OK, conn.getResponseCode());
+          if (useQS) {
+            assertNull(conn.getHeaderField("UsingHeader"));
+            assertNotNull(conn.getHeaderField("UsingQueryString"));
+          } else {
+            assertNotNull(conn.getHeaderField("UsingHeader"));
+            assertNull(conn.getHeaderField("UsingQueryString"));
+          }
+          return null;
+        }
+      });
 
 
     } finally {
@@ -472,8 +478,8 @@ public class TestWebDelegationToken {
           new DelegationTokenAuthenticatedURL();
 
       aUrl.getDelegationToken(authURL, token, FOO_USER);
-      Assert.assertNotNull(token.getDelegationToken());
-      Assert.assertEquals(new Text("fooKind"),
+      assertNotNull(token.getDelegationToken());
+      assertEquals(new Text("fooKind"),
           token.getDelegationToken().getKind());
 
     } finally {
@@ -553,17 +559,17 @@ public class TestWebDelegationToken {
           DelegationTokenAuthenticatedURL aUrl =
               new DelegationTokenAuthenticatedURL();
           HttpURLConnection conn = aUrl.openConnection(url, token);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           List<String> ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals(FOO_USER, ret.get(0));
+          assertEquals(1, ret.size());
+          assertEquals(FOO_USER, ret.get(0));
 
           try {
             aUrl.getDelegationToken(url, token, FOO_USER);
-            Assert.fail();
+            fail();
           } catch (AuthenticationException ex) {
-            Assert.assertTrue(ex.getMessage().contains(
+            assertTrue(ex.getMessage().contains(
                 "delegation token operation"));
           }
           return null;
@@ -623,15 +629,15 @@ public class TestWebDelegationToken {
           DelegationTokenAuthenticatedURL aUrl =
               new DelegationTokenAuthenticatedURL();
           HttpURLConnection conn = aUrl.openConnection(url, token);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           List<String> ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals(FOO_USER, ret.get(0));
+          assertEquals(1, ret.size());
+          assertEquals(FOO_USER, ret.get(0));
 
           aUrl.getDelegationToken(url, token, FOO_USER);
-          Assert.assertNotNull(token.getDelegationToken());
-          Assert.assertEquals(new Text("token-kind"),
+          assertNotNull(token.getDelegationToken());
+          assertEquals(new Text("token-kind"),
               token.getDelegationToken().getKind());
           return null;
         }
@@ -746,7 +752,7 @@ public class TestWebDelegationToken {
     final String doAsUser = doAs ? OK_USER : null;
 
     File testDir = new File("target/" + UUID.randomUUID().toString());
-    Assert.assertTrue(testDir.mkdirs());
+    assertTrue(testDir.mkdirs());
     MiniKdc kdc = new MiniKdc(MiniKdc.createConf(), testDir);
     final Server jetty = createJettyServer();
     ServletContextHandler context = new ServletContextHandler();
@@ -774,9 +780,9 @@ public class TestWebDelegationToken {
 
       try {
         aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
-        Assert.fail();
+        fail();
       } catch (AuthenticationException ex) {
-        Assert.assertTrue(ex.getCause().getMessage().contains("GSSException"));
+        assertTrue(ex.getCause().getMessage().contains("GSSException"));
       }
 
       doAsKerberosUser("client", keytabFile.getAbsolutePath(),
@@ -785,8 +791,8 @@ public class TestWebDelegationToken {
             public Void call() throws Exception {
               aUrl.getDelegationToken(
                   url, token, doAs ? doAsUser : "client", doAsUser);
-              Assert.assertNotNull(token.getDelegationToken());
-              Assert.assertEquals(new Text("token-kind"),
+              assertNotNull(token.getDelegationToken());
+              assertEquals(new Text("token-kind"),
                   token.getDelegationToken().getKind());
               // Make sure the token belongs to the right owner
               ByteArrayInputStream buf = new ByteArrayInputStream(
@@ -796,29 +802,28 @@ public class TestWebDelegationToken {
                   new DelegationTokenIdentifier(new Text("token-kind"));
               id.readFields(dis);
               dis.close();
-              Assert.assertEquals(
-                  doAs ? new Text(OK_USER) : new Text("client"), id.getOwner());
+              assertEquals(doAs ? new Text(OK_USER) : new Text("client"), id.getOwner());
               if (doAs) {
-                Assert.assertEquals(new Text("client"), id.getRealUser());
+                assertEquals(new Text("client"), id.getRealUser());
               }
 
               aUrl.renewDelegationToken(url, token, doAsUser);
-              Assert.assertNotNull(token.getDelegationToken());
+              assertNotNull(token.getDelegationToken());
 
               aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
-              Assert.assertNotNull(token.getDelegationToken());
+              assertNotNull(token.getDelegationToken());
 
               try {
                 aUrl.renewDelegationToken(url, token, doAsUser);
-                Assert.fail();
+                fail();
               } catch (Exception ex) {
-                Assert.assertTrue(ex.getMessage().contains("403"));
+                assertTrue(ex.getMessage().contains("403"));
               }
 
               aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
 
               aUrl.cancelDelegationToken(url, token, doAsUser);
-              Assert.assertNull(token.getDelegationToken());
+              assertNull(token.getDelegationToken());
 
               return null;
             }
@@ -848,17 +853,17 @@ public class TestWebDelegationToken {
           url.toExternalForm(), FOO_USER, OK_USER);
       HttpURLConnection conn = 
           (HttpURLConnection) new URL(strUrl).openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
       List<String> ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-      Assert.assertEquals(1, ret.size());
-      Assert.assertEquals(OK_USER, ret.get(0));
+      assertEquals(1, ret.size());
+      assertEquals(OK_USER, ret.get(0));
       strUrl = String.format("%s?user.name=%s&DOAS=%s", url.toExternalForm(), 
           FOO_USER, OK_USER);
       conn = (HttpURLConnection) new URL(strUrl).openConnection();
-      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+      assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
       ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-      Assert.assertEquals(1, ret.size());
-      Assert.assertEquals(OK_USER, ret.get(0));
+      assertEquals(1, ret.size());
+      assertEquals(OK_USER, ret.get(0));
 
       UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
       ugi.doAs(new PrivilegedExceptionAction<Void>() {
@@ -871,16 +876,16 @@ public class TestWebDelegationToken {
 
           // proxyuser using authentication handler authentication
           HttpURLConnection conn = aUrl.openConnection(url, token, OK_USER);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           List<String> ret = IOUtils
               .readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals(OK_USER, ret.get(0));
+          assertEquals(1, ret.size());
+          assertEquals(OK_USER, ret.get(0));
 
           // unauthorized proxy user using authentication handler authentication
           conn = aUrl.openConnection(url, token, FAIL_USER);
-          Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
+          assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
               conn.getResponseCode());
 
           // proxy using delegation token authentication
@@ -892,12 +897,12 @@ public class TestWebDelegationToken {
 
           // requests using delegation token as auth do not honor doAs
           conn = aUrl.openConnection(url, token, OK_USER);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           ret = IOUtils
               .readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals(FOO_USER, ret.get(0));
+          assertEquals(1, ret.size());
+          assertEquals(FOO_USER, ret.get(0));
 
           return null;
         }
@@ -954,22 +959,22 @@ public class TestWebDelegationToken {
 
           // user foo
           HttpURLConnection conn = aUrl.openConnection(url, token);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           List<String> ret = IOUtils
               .readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals("remoteuser=" + FOO_USER+ ":ugi=" + FOO_USER, 
+          assertEquals(1, ret.size());
+          assertEquals("remoteuser=" + FOO_USER+ ":ugi=" + FOO_USER,
               ret.get(0));
 
           // user ok-user via proxyuser foo
           conn = aUrl.openConnection(url, token, OK_USER);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
               conn.getResponseCode());
           ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals("realugi=" + FOO_USER +":remoteuser=" + OK_USER + 
-                  ":ugi=" + OK_USER, ret.get(0));
+          assertEquals(1, ret.size());
+          assertEquals("realugi=" + FOO_USER + ":remoteuser=" + OK_USER +
+              ":ugi=" + OK_USER, ret.get(0));
 
           return null;
         }
@@ -1016,11 +1021,11 @@ public class TestWebDelegationToken {
 
           // user ok-user via proxyuser foo
           HttpURLConnection conn = aUrl.openConnection(url, token, OK_USER);
-          Assert.assertEquals(HttpURLConnection.HTTP_OK,
+          assertEquals(HttpURLConnection.HTTP_OK,
                   conn.getResponseCode());
           List<String> ret = IOUtils.readLines(conn.getInputStream(), StandardCharsets.UTF_8);
-          Assert.assertEquals(1, ret.size());
-          Assert.assertEquals("realugi=" + FOO_USER +":remoteuser=" + OK_USER +
+          assertEquals(1, ret.size());
+          assertEquals("realugi=" + FOO_USER +":remoteuser=" + OK_USER +
                   ":ugi=" + OK_USER, ret.get(0));
 
           return null;

+ 139 - 109
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestCompositeService.java

@@ -20,15 +20,16 @@ package org.apache.hadoop.service;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.service.Service.STATE;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestCompositeService {
 
@@ -47,7 +48,7 @@ public class TestCompositeService {
   private static final boolean STOP_ONLY_STARTED_SERVICES =
     CompositeServiceImpl.isPolicyToStopOnlyStartedServices();
 
-  @Before
+  @BeforeEach
   public void setup() {
     CompositeServiceImpl.resetCounter();
   }
@@ -65,8 +66,8 @@ public class TestCompositeService {
     CompositeServiceImpl[] services = serviceManager.getServices().toArray(
         new CompositeServiceImpl[0]);
 
-    assertEquals("Number of registered services ", NUM_OF_SERVICES,
-        services.length);
+    assertEquals(NUM_OF_SERVICES, services.length,
+        "Number of registered services ");
 
     Configuration conf = new Configuration();
     // Initialise the composite service
@@ -77,9 +78,9 @@ public class TestCompositeService {
 
     // Verify the init() call sequence numbers for every service
     for (int i = 0; i < NUM_OF_SERVICES; i++) {
-      assertEquals("For " + services[i]
-          + " service, init() call sequence number should have been ", i,
-          services[i].getCallSequenceNumber());
+      assertEquals(i, services[i].getCallSequenceNumber(),
+          "For " + services[i] +
+          " service, init() call sequence number should have been ");
     }
 
     // Reset the call sequence numbers
@@ -91,9 +92,9 @@ public class TestCompositeService {
 
     // Verify the start() call sequence numbers for every service
     for (int i = 0; i < NUM_OF_SERVICES; i++) {
-      assertEquals("For " + services[i]
-          + " service, start() call sequence number should have been ", i,
-          services[i].getCallSequenceNumber());
+      assertEquals(i,
+          services[i].getCallSequenceNumber(), "For " + services[i] +
+          " service, start() call sequence number should have been ");
     }
     resetServices(services);
 
@@ -104,18 +105,18 @@ public class TestCompositeService {
 
     // Verify the stop() call sequence numbers for every service
     for (int i = 0; i < NUM_OF_SERVICES; i++) {
-      assertEquals("For " + services[i]
-          + " service, stop() call sequence number should have been ",
-          ((NUM_OF_SERVICES - 1) - i), services[i].getCallSequenceNumber());
+      assertEquals(((NUM_OF_SERVICES - 1) - i), services[i].getCallSequenceNumber(),
+          "For " + services[i] +
+          " service, stop() call sequence number should have been ");
     }
 
     // Try to stop again. This should be a no-op.
     serviceManager.stop();
     // Verify that stop() call sequence numbers for every service don't change.
     for (int i = 0; i < NUM_OF_SERVICES; i++) {
-      assertEquals("For " + services[i]
-          + " service, stop() call sequence number should have been ",
-          ((NUM_OF_SERVICES - 1) - i), services[i].getCallSequenceNumber());
+      assertEquals(((NUM_OF_SERVICES - 1) - i), services[i].getCallSequenceNumber(),
+          "For " + services[i] +
+          " service, stop() call sequence number should have been ");
     }
   }
 
@@ -155,11 +156,11 @@ public class TestCompositeService {
       for (int i = 0; i < NUM_OF_SERVICES - 1; i++) {
         if (i >= FAILED_SERVICE_SEQ_NUMBER && STOP_ONLY_STARTED_SERVICES) {
           // Failed service state should be INITED
-          assertEquals("Service state should have been ", STATE.INITED,
-              services[NUM_OF_SERVICES - 1].getServiceState());
+          assertEquals(STATE.INITED, services[NUM_OF_SERVICES - 1].getServiceState(),
+              "Service state should have been ");
         } else {
-          assertEquals("Service state should have been ", STATE.STOPPED,
-              services[i].getServiceState());
+          assertEquals(STATE.STOPPED, services[i].getServiceState(),
+              "Service state should have been ");
         }
       }
 
@@ -223,10 +224,8 @@ public class TestCompositeService {
   }
 
   private void assertInState(STATE expected, Service service) {
-    assertEquals("Service state should have been " + expected + " in "
-                 + service,
-                 expected,
-                 service.getServiceState());
+    assertEquals(expected,  service.getServiceState(),
+        "Service state should have been " + expected + " in " + service);
   }
 
   /**
@@ -313,24 +312,24 @@ public class TestCompositeService {
     assertInState(STATE.INITED, child);
   }
 
-  @Test (timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddIfService() {
     CompositeService testService = new CompositeService("TestService") {
       Service service;
       @Override
       public void serviceInit(Configuration conf) {
         Integer notAService = new Integer(0);
-        assertFalse("Added an integer as a service",
-            addIfService(notAService));
+        assertFalse(addIfService(notAService), "Added an integer as a service");
 
         service = new AbstractService("Service") {};
-        assertTrue("Unable to add a service", addIfService(service));
+        assertTrue(addIfService(service), "Unable to add a service");
       }
     };
 
     testService.init(new Configuration());
-    assertEquals("Incorrect number of services",
-                 1, testService.getServices().size());
+    assertEquals(1, testService.getServices().size(),
+        "Incorrect number of services");
   }
 
   @Test
@@ -339,8 +338,7 @@ public class TestCompositeService {
       @Override
       public void serviceInit(Configuration conf) {
         Integer notAService = new Integer(0);
-        assertFalse("Added an integer as a service",
-            addIfService(notAService));
+        assertFalse(addIfService(notAService), "Added an integer as a service");
 
         Service service1 = new AbstractService("Service1") {};
         addIfService(service1);
@@ -356,15 +354,16 @@ public class TestCompositeService {
     };
 
     testService.init(new Configuration());
-    assertEquals("Incorrect number of services",
-        2, testService.getServices().size());
+    assertEquals(2, testService.getServices().size(),
+        "Incorrect number of services");
   }
 
   //
   // Tests for adding child service to parent
   //
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedChildBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -377,7 +376,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedChildInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -393,11 +393,12 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, child);
     parent.stop();
     assertInState(STATE.NOTINITED, child);
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedChildInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -409,7 +410,8 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedChildInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -420,7 +422,8 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedChildBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -434,7 +437,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedChildInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -447,7 +451,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedChildInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -460,7 +465,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedChildInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -472,7 +478,8 @@ public class TestCompositeService {
     assertInState(STATE.INITED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedChildBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -486,11 +493,12 @@ public class TestCompositeService {
       //expected
     }
     parent.stop();
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedChildInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -504,7 +512,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedChildInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -518,7 +527,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedChildInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -531,7 +541,8 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, child);
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedChildBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -546,11 +557,12 @@ public class TestCompositeService {
       //expected
     }
     parent.stop();
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedChildInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -567,11 +579,12 @@ public class TestCompositeService {
     }
     assertInState(STATE.STOPPED, child);
     parent.stop();
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedChildInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -584,7 +597,8 @@ public class TestCompositeService {
     parent.stop();
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedChildInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService child = new BreakableService();
@@ -601,7 +615,8 @@ public class TestCompositeService {
   // Tests for adding sibling service to parent
   //
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedSiblingBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -614,11 +629,12 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, sibling);
     parent.stop();
     assertInState(STATE.NOTINITED, sibling);
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedSiblingInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -633,11 +649,12 @@ public class TestCompositeService {
       //expected
     }
     parent.stop();
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedSiblingInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -650,11 +667,12 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, sibling);
     parent.stop();
     assertInState(STATE.NOTINITED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddUninitedSiblingInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -667,11 +685,12 @@ public class TestCompositeService {
     assertInState(STATE.NOTINITED, sibling);
     parent.stop();
     assertInState(STATE.NOTINITED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedSiblingBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -685,11 +704,12 @@ public class TestCompositeService {
     assertInState(STATE.INITED, sibling);
     parent.stop();
     assertInState(STATE.INITED, sibling);
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedSiblingInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -703,11 +723,12 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedSiblingInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -721,11 +742,12 @@ public class TestCompositeService {
     assertInState(STATE.INITED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddInitedSiblingInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -736,7 +758,8 @@ public class TestCompositeService {
     parent.init(new Configuration());
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedSiblingBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -751,11 +774,12 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, sibling);
     parent.stop();
     assertInState(STATE.STARTED, sibling);
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedSiblingInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -770,12 +794,13 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedSiblingInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -790,11 +815,12 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStartedSiblingInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -809,11 +835,12 @@ public class TestCompositeService {
     assertInState(STATE.STARTED, sibling);
     parent.stop();
     assertInState(STATE.STARTED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedSiblingBeforeInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -829,11 +856,12 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 1, parent.getServices().size());
+    assertEquals(1, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedSiblingInInit() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -853,11 +881,12 @@ public class TestCompositeService {
     }
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedSiblingInStart() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -873,11 +902,12 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testAddStoppedSiblingInStop() throws Throwable {
     CompositeService parent = new CompositeService("parent");
     BreakableService sibling = new BreakableService();
@@ -893,8 +923,8 @@ public class TestCompositeService {
     assertInState(STATE.STOPPED, sibling);
     parent.stop();
     assertInState(STATE.STOPPED, sibling);
-    assertEquals("Incorrect number of services",
-                 2, parent.getServices().size());
+    assertEquals(2, parent.getServices().size(),
+        "Incorrect number of services");
   }
 
   public static class CompositeServiceAddingAChild extends CompositeService{

+ 4 - 4
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestServiceOperations.java

@@ -19,11 +19,11 @@
 package org.apache.hadoop.service;
 
 import org.apache.hadoop.test.GenericTestUtils.LogCapturer;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
 import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,7 +38,7 @@ import static org.mockito.Mockito.verify;
 /**
  * Test miscellaneous service operations through mocked failures.
  */
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
 public class TestServiceOperations {
 
   @Mock

+ 11 - 25
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/AbstractServiceLauncherTestBase.java

@@ -25,13 +25,11 @@ import org.apache.hadoop.service.ServiceOperations;
 import static org.apache.hadoop.test.GenericTestUtils.*;
 import org.apache.hadoop.util.ExitCodeProvider;
 import org.apache.hadoop.util.ExitUtil;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -41,9 +39,9 @@ import java.io.IOException;
 import java.io.OutputStream;
 import java.util.Arrays;
 import java.util.List;
-import java.util.concurrent.TimeUnit;
 
-public class AbstractServiceLauncherTestBase extends Assert implements
+@Timeout(15)
+public class AbstractServiceLauncherTestBase extends Assertions implements
     LauncherExitCodes {
   private static final Logger LOG = LoggerFactory.getLogger(
       AbstractServiceLauncherTestBase.class);
@@ -54,22 +52,10 @@ public class AbstractServiceLauncherTestBase extends Assert implements
    */
   private Service serviceToTeardown;
 
-  /**
-   * All tests have a short life.
-   */
-  @Rule
-  public Timeout testTimeout = new Timeout(15000, TimeUnit.MILLISECONDS);
-
-  /**
-   * Rule to provide the method name.
-   */
-  @Rule
-  public TestName methodName = new TestName();
-
   /**
    * Turn off the exit util JVM exits, downgrading them to exception throws.
    */
-  @BeforeClass
+  @BeforeAll
   public static void disableJVMExits() {
     ExitUtil.disableSystemExit();
     ExitUtil.disableSystemHalt();
@@ -78,12 +64,12 @@ public class AbstractServiceLauncherTestBase extends Assert implements
   /**
    * rule to name the thread JUnit.
    */
-  @Before
+  @BeforeEach
   public void nameThread() {
     Thread.currentThread().setName("JUnit");
   }
 
-  @After
+  @AfterEach
   public void stopService() {
     ServiceOperations.stopQuietly(serviceToTeardown);
   }
@@ -209,7 +195,7 @@ public class AbstractServiceLauncherTestBase extends Assert implements
    */
   protected Configuration newConf(String... kvp) {
     int len = kvp.length;
-    assertEquals("unbalanced keypair len of " + len, 0, len % 2);
+    assertEquals(0, len % 2, "unbalanced keypair len of " + len);
     Configuration conf = new Configuration(false);
     for (int i = 0; i < len; i += 2) {
       conf.set(kvp[i], kvp[i + 1]);

+ 6 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceConf.java

@@ -23,7 +23,8 @@ import org.apache.hadoop.service.Service;
 import org.apache.hadoop.service.launcher.testservices.LaunchableRunningService;
 import org.apache.hadoop.service.launcher.testservices.RunningService;
 import static org.apache.hadoop.service.launcher.LauncherArguments.*;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
 
 import java.io.File;
 import java.io.FileWriter;
@@ -97,8 +98,7 @@ public class TestServiceConf
     List<String> args = launcher.extractCommandOptions(extracted,
         argsList);
     if (!args.isEmpty()) {
-      assertEquals("args beginning with " + args.get(0),
-          0, args.size());
+      assertEquals(0, args.size(), "args beginning with " + args.get(0));
     }
     assertEquals("true", extracted.get("propagated", "unset"));
   }
@@ -121,17 +121,16 @@ public class TestServiceConf
 
     List<String> args = launcher.extractCommandOptions(extracted, argsList);
     if (!args.isEmpty()) {
-      assertEquals("args beginning with " + args.get(0),
-          0, args.size());
+      assertEquals(0, args.size(), "args beginning with " + args.get(0));
     }
     assertTrue(extracted.getBoolean(key1, false));
     assertEquals(7, extracted.getInt(key2, -1));
   }
 
   @Test
-  public void testConfArgWrongFiletype() throws Throwable {
+  public void testConfArgWrongFiletype(TestInfo testInfo) throws Throwable {
     new File(CONF_FILE_DIR).mkdirs();
-    File file = new File(CONF_FILE_DIR, methodName.getMethodName());
+    File file = new File(CONF_FILE_DIR, testInfo.getDisplayName());
     try (FileWriter fileWriter = new FileWriter(file)) {
       fileWriter.write("not-a-conf-file");
       fileWriter.close();

+ 7 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceInterruptHandling.java

@@ -22,7 +22,7 @@ import org.apache.hadoop.service.BreakableService;
 import org.apache.hadoop.service.launcher.testservices.FailureTestService;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.ExitUtil;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -68,10 +68,10 @@ public class TestServiceInterruptHandling
     }
     //the service is now stopped
     assertStopped(service);
-    assertTrue("isSignalAlreadyReceived() == false in " + escalator,
-        escalator.isSignalAlreadyReceived());
-    assertFalse("isForcedShutdownTimedOut() == true in " + escalator,
-        escalator.isForcedShutdownTimedOut());
+    assertTrue(escalator.isSignalAlreadyReceived(),
+        "isSignalAlreadyReceived() == false in " + escalator);
+    assertFalse(escalator.isForcedShutdownTimedOut(),
+        "isForcedShutdownTimedOut() == true in " + escalator);
 
     // now interrupt it a second time and expect it to escalate to a halt
     try {
@@ -99,8 +99,8 @@ public class TestServiceInterruptHandling
       assertExceptionDetails(EXIT_INTERRUPTED, "", e);
     }
 
-    assertTrue("isForcedShutdownTimedOut() == false in " + escalator,
-        escalator.isForcedShutdownTimedOut());
+    assertTrue(escalator.isForcedShutdownTimedOut(),
+        "isForcedShutdownTimedOut() == false in " + escalator);
   }
 
   private static class InterruptCatcher implements IrqHandler.Interrupted {

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncher.java

@@ -32,7 +32,7 @@ import org.apache.hadoop.service.launcher.testservices.StringConstructorOnlyServ
 import static org.apache.hadoop.test.GenericTestUtils.*;
 import static org.apache.hadoop.service.launcher.testservices.ExceptionInExecuteLaunchableService.*;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class TestServiceLauncher extends AbstractServiceLauncherTestBase {
 

+ 1 - 1
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncherCreationFailures.java

@@ -22,7 +22,7 @@ import org.apache.hadoop.service.launcher.testservices.FailInConstructorService;
 import org.apache.hadoop.service.launcher.testservices.FailInInitService;
 import org.apache.hadoop.service.launcher.testservices.FailInStartService;
 import org.apache.hadoop.service.launcher.testservices.FailingStopInStartService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Explore the ways in which the launcher is expected to (safely) fail.

+ 3 - 3
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/TestServiceLauncherInnerMethods.java

@@ -24,7 +24,7 @@ import org.apache.hadoop.service.Service;
 import org.apache.hadoop.service.launcher.testservices.ExceptionInExecuteLaunchableService;
 import org.apache.hadoop.service.launcher.testservices.LaunchableRunningService;
 import org.apache.hadoop.service.launcher.testservices.NoArgsAllowedService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 import java.util.List;
 
@@ -40,7 +40,7 @@ public class TestServiceLauncherInnerMethods extends
     ServiceLauncher<NoArgsAllowedService> launcher =
         launchService(NoArgsAllowedService.class, new Configuration());
     NoArgsAllowedService service = launcher.getService();
-    assertNotNull("null service from " + launcher, service);
+    assertNotNull(service, "null service from " + launcher);
     service.stop();
   }
 
@@ -78,7 +78,7 @@ public class TestServiceLauncherInnerMethods extends
     ServiceLauncher<BreakableService> launcher =
         launchService(BreakableService.class, new Configuration());
     BreakableService service = launcher.getService();
-    assertNotNull("null service from " + launcher, service);
+    assertNotNull(service, "null service from " + launcher);
     service.stop();
   }
 

+ 7 - 7
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/testservices/InitInConstructorLaunchableService.java

@@ -20,7 +20,7 @@ package org.apache.hadoop.service.launcher.testservices;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.service.launcher.AbstractLaunchableService;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
 
 import java.util.List;
 
@@ -41,23 +41,23 @@ public class InitInConstructorLaunchableService extends
 
   @Override
   public void init(Configuration conf) {
-    Assert.assertEquals(STATE.NOTINITED, getServiceState());
+    Assertions.assertEquals(STATE.NOTINITED, getServiceState());
     super.init(conf);
   }
 
   @Override
   public Configuration bindArgs(Configuration config, List<String> args)
       throws Exception {
-    Assert.assertEquals(STATE.INITED, getServiceState());
-    Assert.assertTrue(isInState(STATE.INITED));
-    Assert.assertNotSame(getConfig(), config);
+    Assertions.assertEquals(STATE.INITED, getServiceState());
+    Assertions.assertTrue(isInState(STATE.INITED));
+    Assertions.assertNotSame(getConfig(), config);
     return null;
   }
 
   @Override
   public int execute() throws Exception {
-    Assert.assertEquals(STATE.STARTED, getServiceState());
-    Assert.assertSame(originalConf, getConfig());
+    Assertions.assertEquals(STATE.STARTED, getServiceState());
+    Assertions.assertSame(originalConf, getConfig());
     return super.execute();
   }
 }

+ 2 - 2
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/launcher/testservices/LaunchableRunningService.java

@@ -21,7 +21,7 @@ package org.apache.hadoop.service.launcher.testservices;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.service.launcher.LaunchableService;
 import org.apache.hadoop.service.launcher.LauncherExitCodes;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -63,7 +63,7 @@ public class LaunchableRunningService extends RunningService implements
   @Override
   public Configuration bindArgs(Configuration config, List<String> args) throws
       Exception {
-    Assert.assertEquals(STATE.NOTINITED, getServiceState());
+    Assertions.assertEquals(STATE.NOTINITED, getServiceState());
     for (String arg : args) {
       LOG.info(arg);
     }

+ 9 - 6
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestGenericTestUtils.java

@@ -18,7 +18,8 @@
 
 package org.apache.hadoop.test;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -26,9 +27,9 @@ import org.slf4j.LoggerFactory;
 import java.util.function.Supplier;
 import org.slf4j.event.Level;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 public class TestGenericTestUtils extends GenericTestUtils {
 
@@ -85,7 +86,8 @@ public class TestGenericTestUtils extends GenericTestUtils {
     }
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testLogCapturer() {
     final Logger log = LoggerFactory.getLogger(TestGenericTestUtils.class);
     LogCapturer logCapturer = LogCapturer.captureLogs(log);
@@ -103,7 +105,8 @@ public class TestGenericTestUtils extends GenericTestUtils {
     assertTrue(logCapturer.getOutput().isEmpty());
   }
 
-  @Test(timeout = 10000)
+  @Test
+  @Timeout(value = 10)
   public void testLogCapturerSlf4jLogger() {
     final Logger logger = LoggerFactory.getLogger(TestGenericTestUtils.class);
     LogCapturer logCapturer = LogCapturer.captureLogs(logger);

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

@@ -18,11 +18,12 @@
 
 package org.apache.hadoop.test;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static org.junit.jupiter.api.Assertions.fail;
+
 public class TestJUnitSetup {
   public static final Logger LOG =
       LoggerFactory.getLogger(TestJUnitSetup.class);
@@ -35,6 +36,6 @@ public class TestJUnitSetup {
       LOG.info("The AssertionError is expected.", ae);
       return;
     }
-    Assert.fail("Java assert does not work.");
+    fail("Java assert does not work.");
   }
 }

+ 9 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestLambdaTestUtils.java

@@ -18,8 +18,8 @@
 
 package org.apache.hadoop.test;
 
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -39,7 +39,7 @@ import static org.apache.hadoop.test.GenericTestUtils.*;
  * This test suite includes Java 8 and Java 7 code; the Java 8 code exists
  * to verify that the API is easily used with Lambda expressions.
  */
-public class TestLambdaTestUtils extends Assert {
+public class TestLambdaTestUtils extends Assertions {
 
   public static final int INTERVAL = 10;
   public static final int TIMEOUT = 50;
@@ -116,7 +116,7 @@ public class TestLambdaTestUtils extends Assert {
    * @param expected expected value
    */
   protected void assertRetryCount(int expected) {
-    assertEquals(retry.toString(), expected, retry.getInvocationCount());
+    assertEquals(expected, retry.getInvocationCount(), retry.toString());
   }
 
   /**
@@ -124,8 +124,8 @@ public class TestLambdaTestUtils extends Assert {
    * @param minCount minimum value
    */
   protected void assertMinRetryCount(int minCount) {
-    assertTrue("retry count of " + retry + " is not >= " + minCount,
-        minCount <= retry.getInvocationCount());
+    assertTrue(minCount <= retry.getInvocationCount(),
+        "retry count of " + retry + " is not >= " + minCount);
   }
 
   /**
@@ -181,8 +181,8 @@ public class TestLambdaTestUtils extends Assert {
           TIMEOUT_FAILURE_HANDLER);
       fail("should not have got here");
     } catch (TimeoutException e) {
-      assertEquals(linearRetry.toString(),
-          2, linearRetry.getInvocationCount());
+      assertEquals(2, linearRetry.getInvocationCount(),
+          linearRetry.toString());
     }
   }
 
@@ -499,7 +499,7 @@ public class TestLambdaTestUtils extends Assert {
 
   @Test
   public void testEvalToSuccess() {
-    assertTrue("Eval to success", eval(() -> true));
+    assertTrue(eval(() -> true), "Eval to success");
   }
 
   /**

+ 11 - 12
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestMultithreadedTestUtil.java

@@ -17,12 +17,14 @@
  */
 package org.apache.hadoop.test;
 
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.apache.hadoop.test.MultithreadedTestUtil.TestContext;
 import org.apache.hadoop.test.MultithreadedTestUtil.TestingThread;
 import org.apache.hadoop.test.MultithreadedTestUtil.RepeatingTestThread;
@@ -56,8 +58,7 @@ public class TestMultithreadedTestUtil {
     assertEquals(3, threadsRun.get());
     // Test shouldn't have waited the full 30 seconds, since
     // the threads exited faster than that.
-    assertTrue("Test took " + (et - st) + "ms",
-        et - st < 5000);
+    assertTrue(et - st < 5000, "Test took " + (et - st) + "ms");
   }
 
   @Test
@@ -81,8 +82,7 @@ public class TestMultithreadedTestUtil {
     long et = Time.now();
     // Test shouldn't have waited the full 30 seconds, since
     // the thread throws faster than that
-    assertTrue("Test took " + (et - st) + "ms",
-        et - st < 5000);
+    assertTrue(et - st < 5000, "Test took " + (et - st) + "ms");
   }
 
   @Test
@@ -106,8 +106,7 @@ public class TestMultithreadedTestUtil {
     long et = Time.now();
     // Test shouldn't have waited the full 30 seconds, since
     // the thread throws faster than that
-    assertTrue("Test took " + (et - st) + "ms",
-        et - st < 5000);
+    assertTrue(et - st < 5000, "Test took " + (et - st) + "ms");
   }
 
   @Test
@@ -129,11 +128,11 @@ public class TestMultithreadedTestUtil {
     long elapsed = et - st;
 
     // Test should have waited just about 3 seconds
-    assertTrue("Test took " + (et - st) + "ms",
-        Math.abs(elapsed - 3000) < 500);
+    assertTrue(Math.abs(elapsed - 3000) < 500,
+        "Test took " + (et - st) + "ms");
     // Counter should have been incremented lots of times in 3 full seconds
-    assertTrue("Counter value = " + counter.get(),
-        counter.get() > 1000);
+    assertTrue(counter.get() > 1000,
+        "Counter value = " + counter.get());
   }
 
 }

+ 12 - 9
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestTimedOutTestsListener.java

@@ -23,9 +23,11 @@ import java.util.concurrent.CyclicBarrier;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.notification.Failure;
+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 TestTimedOutTestsListener {
 
@@ -143,7 +145,8 @@ public class TestTimedOutTestsListener {
   
   }
 
-  @Test(timeout=30000)
+  @Test
+  @Timeout(value = 30)
   public void testThreadDumpAndDeadlocks() throws Exception {
     new Deadlock();
     String s = null;
@@ -154,16 +157,16 @@ public class TestTimedOutTestsListener {
       Thread.sleep(100);
     }
     
-    Assert.assertEquals(3, countStringOccurrences(s, "BLOCKED"));
+    assertEquals(3, countStringOccurrences(s, "BLOCKED"));
     
-    Failure failure = new Failure(
-        null, new Exception(TimedOutTestsListener.TEST_TIMED_OUT_PREFIX));
+    RuntimeException failure =
+        new RuntimeException(TimedOutTestsListener.TEST_TIMED_OUT_PREFIX);
     StringWriter writer = new StringWriter();
     new TimedOutTestsListener(new PrintWriter(writer)).testFailure(failure);
     String out = writer.toString();
     
-    Assert.assertTrue(out.contains("THREAD DUMP"));
-    Assert.assertTrue(out.contains("DEADLOCKS DETECTED"));
+    assertTrue(out.contains("THREAD DUMP"));
+    assertTrue(out.contains("DEADLOCKS DETECTED"));
     
     System.out.println(out);
   }

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

@@ -30,14 +30,12 @@ import java.util.Date;
 import java.util.Map;
 
 import org.apache.hadoop.util.StringUtils;
-import org.junit.runner.notification.Failure;
-import org.junit.runner.notification.RunListener;
 
 /**
  * JUnit run listener which prints full thread dump into System.err
  * in case a test is failed due to timeout.
  */
-public class TimedOutTestsListener extends RunListener {
+public class TimedOutTestsListener {
 
   static final String TEST_TIMED_OUT_PREFIX = "test timed out after";
   
@@ -53,8 +51,7 @@ public class TimedOutTestsListener extends RunListener {
     this.output = output;
   }
 
-  @Override
-  public void testFailure(Failure failure) throws Exception {
+  public void testFailure(RuntimeException failure) throws Exception {
     if (failure != null && failure.getMessage() != null 
         && failure.getMessage().startsWith(TEST_TIMED_OUT_PREFIX)) {
       output.println("====> TEST TIMED OUT. PRINTING THREAD DUMP. <====");

+ 14 - 14
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/tools/TestCommandShell.java

@@ -23,10 +23,10 @@ import java.io.PrintStream;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.tools.CommandShell;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class TestCommandShell {
 
@@ -92,7 +92,7 @@ public class TestCommandShell {
     return "OUT:\n" + outContent.toString() + "\n" + message;
   }
 
-  @Before
+  @BeforeEach
   public void setup() throws Exception {
     System.setOut(new PrintStream(outContent));
   }
@@ -106,22 +106,22 @@ public class TestCommandShell {
     outContent.reset();
     String[] args1 = {"hello"};
     rc = ex.run(args1);
-    assertEquals(outMsg("test exit code - normal hello"), 0, rc);
-    assertTrue(outMsg("test normal hello message"),
-               outContent.toString().contains(Example.HELLO_MSG));
+    assertEquals(0, rc, outMsg("test exit code - normal hello"));
+    assertTrue(outContent.toString().contains(Example.HELLO_MSG),
+        outMsg("test normal hello message"));
 
     outContent.reset();
     String[] args2 = {"hello", "x"};
     rc = ex.run(args2);
-    assertEquals(outMsg("test exit code - bad hello"), 1, rc);
-    assertTrue(outMsg("test bad hello message"),
-               outContent.toString().contains(Example.Hello.HELLO_USAGE));
+    assertEquals(1, rc, outMsg("test exit code - bad hello"));
+    assertTrue(outContent.toString().contains(Example.Hello.HELLO_USAGE),
+        outMsg("test bad hello message"));
 
     outContent.reset();
     String[] args3 = {"goodbye"};
     rc = ex.run(args3);
-    assertEquals(outMsg("test exit code - normal goodbye"), 0, rc);
-    assertTrue(outMsg("test normal goodbye message"),
-               outContent.toString().contains(Example.GOODBYE_MSG));
+    assertEquals(0, rc, outMsg("test exit code - normal goodbye"));
+    assertTrue(outContent.toString().contains(Example.GOODBYE_MSG),
+        outMsg("test normal goodbye message"));
   }
 }